From 0d4568b8120f042b053742e503be1844c03bfafd Mon Sep 17 00:00:00 2001 From: Erik Niebla Date: Wed, 13 Oct 2021 17:23:23 -0500 Subject: [PATCH 1/7] Avoid exception when hits 403,404,etc --- src/GoogleDriveAdapter.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/GoogleDriveAdapter.php b/src/GoogleDriveAdapter.php index 80fbf97..87187ad 100644 --- a/src/GoogleDriveAdapter.php +++ b/src/GoogleDriveAdapter.php @@ -294,7 +294,10 @@ public function refreshToken() if ($client->isUsingApplicationDefaultCredentials()) { $client->fetchAccessTokenWithAssertion(); } else { - $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); + $refreshToken = $client->getRefreshToken(); + if ($refreshToken) { + $client->fetchAccessTokenWithRefreshToken($refreshToken); + } } } } From 0935fc9193a7ab7924755a5866476c4ac5232d6e Mon Sep 17 00:00:00 2001 From: David Eleazar Date: Mon, 27 Dec 2021 00:12:05 +0700 Subject: [PATCH 2/7] [1.x] Improved Google library class loading I updated all Google class load in the /src and /tests folder to reflect the PSR-4 autoloading standard, and get rid of VSCode PHP intelephense. And updated the README as well. This commit is targeted to the branch 1.x with (hopefully) no breaking changes. --- README.md | 65 ++++++++++++++++++--------- src/GoogleDriveAdapter.php | 73 ++++++++++++++++--------------- src/StreamableUpload.php | 13 +++--- tests/GoogleDriveAdapterTests.php | 4 +- 4 files changed, 92 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index f0147d4..ee816cc 100644 --- a/README.md +++ b/README.md @@ -21,21 +21,23 @@ composer require masbug/flysystem-google-drive-ext:"^1.0.0" ## Getting Google Keys -#### Please follow [Google Docs](https://developers.google.com/drive/v3/web/enable-sdk) to obtain your `client ID, client secret & refresh token`. +#### Please follow [Google Docs](https://developers.google.com/drive/v3/web/enable-sdk) to obtain your `client ID, client secret & refresh token`. + #### In addition you can also check these easy-to-follow tutorial by [@ivanvermeyen](https://github.com/ivanvermeyen/laravel-google-drive-demo) -- [Getting your Client ID and Secret](https://github.com/ivanvermeyen/laravel-google-drive-demo/blob/master/README/1-getting-your-dlient-id-and-secret.md) -- [Getting your Refresh Token](https://github.com/ivanvermeyen/laravel-google-drive-demo/blob/master/README/2-getting-your-refresh-token.md) + +- [Getting your Client ID and Secret](https://github.com/ivanvermeyen/laravel-google-drive-demo/blob/master/README/1-getting-your-dlient-id-and-secret.md) +- [Getting your Refresh Token](https://github.com/ivanvermeyen/laravel-google-drive-demo/blob/master/README/2-getting-your-refresh-token.md) ## Usage ```php -$client = new \Google_Client(); +$client = new \Google\Client(); $client->setClientId([client_id]); $client->setClientSecret([client_secret]); $client->refreshToken([refresh_token]); $client->setApplicationName('My Google Drive App'); -$service = new \Google_Service_Drive($client); +$service = new \Google\Service\Drive($client); // variant 1 $adapter = new \Masbug\Flysystem\GoogleDriveAdapter($service, 'My_App_Root'); @@ -66,6 +68,7 @@ $adapter3 = new \Masbug\Flysystem\GoogleDriveAdapter( $fs = new \League\Flysystem\Filesystem($adapter, ['visibility' => AdapterInterface::VISIBILITY_PRIVATE]); ``` + ```php // List selected root folder contents $contents = $fs->listContents('', true /* is_recursive */); @@ -75,6 +78,7 @@ $contents = $fs->listContents('MyFolder', true /* is_recursive */); ``` ##### File upload + ```php // Upload a file $local_filepath = '/home/user/downloads/file_to_upload.ext'; @@ -97,10 +101,11 @@ try { echo 'Source doesn\'t exist!'; } -// NOTE: Remote folders are automatically created. +// NOTE: Remote folders are automatically created. ``` ##### File download + ```php // Download a file $remote_filepath = 'MyFolder/file.ext'; @@ -125,14 +130,15 @@ try { ``` ##### How to get TeamDrive list and IDs + ```php -$client = new \Google_Client(); +$client = new \Google\Client(); $client->setClientId([client_id]); $client->setClientSecret([client_secret]); $client->refreshToken([refresh_token]); $client->setApplicationName('My Google Drive App'); -$service = new \Google_Service_Drive($client); +$service = new \Google\Service\Drive($client); $drives = $service->teamdrives->listTeamdrives()->getTeamDrives(); foreach ($drives as $drive) { @@ -145,7 +151,9 @@ foreach ($drives as $drive) { ## Using with Laravel Framework ##### Update `.env` file with google keys + Add the keys you created to your `.env` file and set `google` as your default cloud storage. You can copy the `.env.example` file and fill in the blanks. + ``` FILESYSTEM_CLOUD=google GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com @@ -163,6 +171,7 @@ GOOGLE_DRIVE_FOLDER= ``` ##### Add disks on `config/filesystems.php` + ```php 'disks' => [ // ... @@ -174,7 +183,7 @@ GOOGLE_DRIVE_FOLDER= 'folder' => env('GOOGLE_DRIVE_FOLDER'), // without folder is root of drive or team drive //'teamDriveId' => env('GOOGLE_DRIVE_TEAM_DRIVE_ID'), ], - // you can use more accounts, only add more disks and configs on .env + // you can use more accounts, only add more disks and configs on .env // also you can use the same account and point to a diferent folders for each disk /*'second_google' => [ 'driver' => 'google', @@ -188,27 +197,39 @@ GOOGLE_DRIVE_FOLDER= ``` ##### Add driver storage in a `ServiceProvider` on path `app/Providers/` + Example: + ```php namespace App\Providers; -class AppServiceProvider extends \Illuminate\Support\ServiceProvider{ // can be a custom ServiceProvider +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\ServiceProvider; + +class AppServiceProvider extends ServiceProvider { // can be a custom ServiceProvider // ... public function boot(){ // ... - try{ - \Storage::extend('google', function($app, $config) { - $options = []; - if(!empty($config['teamDriveId']??null)) $options['teamDriveId']=$config['teamDriveId']; - $client = new \Google_Client(); + try { + Storage::extend('google', function($app, $config) { + $options = []; + + if(!empty($config['teamDriveId'] ?? null)) { + $options['teamDriveId'] = $config['teamDriveId']; + } + + $client = new \Google\Client(); $client->setClientId($config['clientId']); $client->setClientSecret($config['clientSecret']); $client->refreshToken($config['refreshToken']); - $service = new \Google_Service_Drive($client); - $adapter = new \Masbug\Flysystem\GoogleDriveAdapter($service,$config['folder']??'/', $options); + $service = new \Google\Service\Drive($client); + $adapter = new \Masbug\Flysystem\GoogleDriveAdapter($service, $config['folder'] ?? '/', $options); + return new \League\Flysystem\Filesystem($adapter); }); - }catch(\Exception $e){ } + } catch(\Exception $e) { + // ... + } // ... } // ... @@ -216,27 +237,31 @@ class AppServiceProvider extends \Illuminate\Support\ServiceProvider{ // can be ``` Now you can access the drives like so: + ```php $googleDisk = Storage::disk('google'); //$secondDisk = Storage::disk('second_google'); //others disks ``` Keep in mind that there can only be one default cloud storage drive, defined by `FILESYSTEM_CLOUD` in your `.env` (or config) file. If you set it to `google`, that will be the cloud drive: + ```php Storage::cloud(); // refers to Storage::disk('google') ``` ## Limitations + Using display paths as identifiers for folders and files requires them to be unique. Unfortunately Google Drive allows users to create files and folders with same (displayed) names. In such cases when unique path cannot be determined this adapter chooses the oldest (first) instance. In case the newer duplicate is a folder and user puts a unique file or folder inside the adapter will be able to reach it properly (because full path is unique). -Concurrent use of same Google Drive might lead to unexpected problems due to heavy caching of file/folder identifiers and file objects. +Concurrent use of same Google Drive might lead to unexpected problems due to heavy caching of file/folder identifiers and file objects. ## Acknowledgements + This adapter is based on wonderful [flysystem-google-drive](https://github.com/nao-pon/flysystem-google-drive) by Naoki Sawada. It also contains an adaptation of [Google_Http_MediaFileUpload](https://github.com/googleapis/google-api-php-client/blob/master/src/Http/MediaFileUpload.php) by Google. I've added support for resumable uploads directly from streams (avoiding copying data to memory). TeamDrive support was implemented by Maximilian Ruta - [Deltachaos](https://github.com/Deltachaos). -Adapter rewrite for Flysystem V2 and various fixes were implemented by Erik Niebla - [erikn69](https://github.com/erikn69). \ No newline at end of file +Adapter rewrite for Flysystem V2 and various fixes were implemented by Erik Niebla - [erikn69](https://github.com/erikn69). diff --git a/src/GoogleDriveAdapter.php b/src/GoogleDriveAdapter.php index 80fbf97..09b251e 100644 --- a/src/GoogleDriveAdapter.php +++ b/src/GoogleDriveAdapter.php @@ -3,9 +3,10 @@ namespace Masbug\Flysystem; use Google_Service_Drive; -use Google_Service_Drive_DriveFile; -use Google_Service_Drive_FileList; -use Google_Service_Drive_Permission; +use Google\Service\Drive; +use Google\Service\Drive\DriveFile; +use Google\Service\Drive\FileList; +use Google\Service\Drive\Permission; use League\Flysystem\Adapter\AbstractAdapter; use League\Flysystem\AdapterInterface; use League\Flysystem\Config; @@ -56,7 +57,7 @@ class GoogleDriveAdapter extends AbstractAdapter /** * Google_Service_Drive instance * - * @var Google_Service_Drive + * @var Google_Service_Drive|Drive */ protected $service; @@ -202,11 +203,11 @@ class GoogleDriveAdapter extends AbstractAdapter /** * GoogleDriveAdapter constructor. * - * @param Google_Service_Drive $service + * @param Google_Service_Drive|Drive $service * @param string|null $root * @param array $options */ - public function __construct(Google_Service_Drive $service, $root = null, $options = []) + public function __construct($service, $root = null, $options = []) { $this->service = $service; @@ -422,7 +423,7 @@ public function rename($path, $newpath) [$newParent, $newName] = $this->splitPath($newpath); } - $file = new Google_Service_Drive_DriveFile(); + $file = new DriveFile(); $file->setName($newName); $opts = [ 'fields' => self::FETCHFIELDS_GET @@ -475,7 +476,7 @@ public function copy($path, $newpath) [$newParentId, $fileName] = $this->splitPath($newpath); } - $file = new Google_Service_Drive_DriveFile(); + $file = new DriveFile(); $file->setName($fileName); $file->setParents([ $newParentId @@ -485,7 +486,7 @@ public function copy($path, $newpath) 'fields' => self::FETCHFIELDS_GET ], 'files.copy')); - if ($newFile instanceof Google_Service_Drive_DriveFile) { + if ($newFile instanceof DriveFile) { $id = $newFile->getId(); $this->cacheFileObjects[$id] = $newFile; $this->cacheObjects([$id => $newFile]); @@ -526,7 +527,7 @@ protected function delete_by_id($ids) $deleted = true; } else { if (!$this->usePermanentDelete) { - $file = new Google_Service_Drive_DriveFile(); + $file = new DriveFile(); $file->setTrashed(true); if ($this->service->files->update($id, $file, $this->applyDefaultParams([], 'files.update'))) { $this->uncacheId($id); @@ -638,7 +639,7 @@ public function has($path) return false; } } - return ($this->getFileObject($path, true) instanceof Google_Service_Drive_DriveFile); + return ($this->getFileObject($path, true) instanceof DriveFile); } /** @@ -816,7 +817,7 @@ public function getMetadata($path) $path = $this->toVirtualPath($path, true, true); } if (($obj = $this->getFileObject($path, true))) { - if ($obj instanceof Google_Service_Drive_DriveFile) { + if ($obj instanceof DriveFile) { return $this->normaliseObject($obj, self::dirname($path)); } } @@ -956,7 +957,7 @@ protected function setHasDir($targets, $object) } $results = $batch->execute(); foreach ($results as $key => $result) { - if ($result instanceof Google_Service_Drive_FileList) { + if ($result instanceof FileList) { $object[$paths[$key]]['hasdir'] = $this->cacheHasDirs[$paths[$key]] = (bool)$result->getFiles(); } } @@ -998,12 +999,12 @@ protected function publish($path) return true; } try { - $new_permission = new Google_Service_Drive_Permission($this->publishPermission); + $new_permission = new Permission($this->publishPermission); if ($permission = $this->service->permissions->create($file->getId(), $new_permission, $this->applyDefaultParams([], 'files.create'))) { $file->setPermissions([$permission]); return true; } - } catch (Exception $e) { + } catch (\Exception $e) { return false; } } @@ -1030,7 +1031,7 @@ protected function unPublish($path) } $file->setPermissions([]); return true; - } catch (Exception $e) { + } catch (\Exception $e) { return false; } } @@ -1084,13 +1085,13 @@ protected function splitFileExtension($name) } /** - * Get normalised files array from Google_Service_Drive_DriveFile + * Get normalised files array from DriveFile * - * @param Google_Service_Drive_DriveFile $object + * @param DriveFile $object * @param string $dirname Parent directory itemId path * @return array Normalised files array */ - protected function normaliseObject(Google_Service_Drive_DriveFile $object, $dirname) + protected function normaliseObject(DriveFile $object, $dirname) { $id = $object->getId(); $path_parts = $this->splitFileExtension($object->getName()); @@ -1104,7 +1105,7 @@ protected function normaliseObject(Google_Service_Drive_DriveFile $object, $dirn break; } } - } catch (Exception $e) { + } catch (\Exception $e) { // Unnecesary } if ($this->useDisplayPaths) { @@ -1172,7 +1173,7 @@ protected function getItems($dirname, $recursive = false, $maxResults = 0, $quer $parameters['pageToken'] = $pageToken; } $fileObjs = $gFiles->listFiles($this->applyDefaultParams($parameters, 'files.list')); - if ($fileObjs instanceof Google_Service_Drive_FileList) { + if ($fileObjs instanceof FileList) { foreach ($fileObjs as $obj) { $id = $obj->getId(); $this->cacheFileObjects[$id] = $obj; @@ -1195,7 +1196,7 @@ protected function getItems($dirname, $recursive = false, $maxResults = 0, $quer } else { $pageToken = null; } - } catch (Exception $e) { + } catch (\Exception $e) { $pageToken = null; } } while ($pageToken && $maxResults === 0); @@ -1207,11 +1208,11 @@ protected function getItems($dirname, $recursive = false, $maxResults = 0, $quer } /** - * Get file oblect Google_Service_Drive_DriveFile + * Get file object DriveFile * * @param string $path itemId path * @param bool $checkDir do check hasdir - * @return Google_Service_Drive_DriveFile|null + * @return DriveFile|null */ public function getFileObject($path, $checkDir = false) { @@ -1252,9 +1253,9 @@ public function getFileObject($path, $checkDir = false) $client->setUseBatch(false); } - if ($fileObj instanceof Google_Service_Drive_DriveFile) { + if ($fileObj instanceof DriveFile) { if ($hasdir && $fileObj->mimeType === self::DIRMIME) { - if ($hasdir instanceof Google_Service_Drive_FileList) { + if ($hasdir instanceof FileList) { $this->cacheHasDirs[$fileObj->getId()] = (bool)$hasdir->getFiles(); } } @@ -1273,7 +1274,7 @@ public function getFileObject($path, $checkDir = false) /** * Get download url * - * @param Google_Service_Drive_DriveFile $file + * @param DriveFile $file * @return string|false */ protected function getDownloadUrl($file) @@ -1300,12 +1301,12 @@ protected function getDownloadUrl($file) * * @param string $name * @param string $parentId - * @return Google_Service_Drive_DriveFile|null + * @return DriveFile|null */ protected function createDirectory($name, $parentId) { $this->refreshToken(); - $file = new Google_Service_Drive_DriveFile(); + $file = new DriveFile(); $file->setName($name); $file->setParents([ $parentId @@ -1317,7 +1318,7 @@ protected function createDirectory($name, $parentId) ], 'files.create')); $this->resetRequest($parentId); - return ($obj instanceof Google_Service_Drive_DriveFile) ? $obj : null; + return ($obj instanceof DriveFile) ? $obj : null; } /** @@ -1334,7 +1335,7 @@ protected function upload($path, $contents, Config $config, $updating = null) $this->refreshToken(); [$parentId, $fileName] = $this->splitPath($path); $mime = $config->get('mimetype'); - $file = new Google_Service_Drive_DriveFile(); + $file = new DriveFile(); if ($updating === null || $updating === true) { $srcFile = $this->getFileObject($path); @@ -1414,7 +1415,7 @@ protected function upload($path, $contents, Config $config, $updating = null) $this->resetRequest($parentId); - if (isset($obj) && $obj instanceof Google_Service_Drive_DriveFile) { + if (isset($obj) && $obj instanceof DriveFile) { $this->cacheFileObjects[$obj->getId()] = $obj; $this->cacheObjects([$obj->getId() => $obj]); $result = $this->normaliseObject($obj, self::dirname($path)); @@ -1505,14 +1506,14 @@ protected function getObjects($ids, $checkDir = false) } foreach ($results as $key => $value) { - if ($value instanceof Google_Service_Drive_DriveFile) { + if ($value instanceof DriveFile) { $itemId = $value->getId(); $this->cacheFileObjects[$itemId] = $value; if (!$this->rootId && strcmp($key, 'response-rootdir') === 0) { $this->rootId = $itemId; } } else { - if ($checkDir && $value instanceof Google_Service_Drive_FileList) { + if ($checkDir && $value instanceof FileList) { if (strncmp($key, 'response-hasdir-', 16) === 0) { $key = substr($key, 16); if (isset($this->cacheFileObjects[$key]) && $this->cacheFileObjects[$key]->mimeType === self::DIRMIME) { @@ -1626,7 +1627,7 @@ protected function uncacheId($id) protected function cacheObjects($objects) { foreach ($objects as $key => $value) { - if ($value instanceof Google_Service_Drive_DriveFile) { + if ($value instanceof DriveFile) { $complete_paths = $this->buildPathFromCacheFileObjects($value->getId()); foreach ($complete_paths as $itemId => $path) { if (DEBUG_ME) { @@ -1958,7 +1959,7 @@ protected function toDisplayPath($virtualPath) $tokens = explode('/', trim($virtualPath, '/')); - /** @var Google_Service_Drive_DriveFile[] $objects */ + /** @var DriveFile[] $objects */ $objects = $this->getObjects($tokens); $display = ''; foreach ($tokens as $token) { diff --git a/src/StreamableUpload.php b/src/StreamableUpload.php index c31346f..ec0ee3c 100644 --- a/src/StreamableUpload.php +++ b/src/StreamableUpload.php @@ -23,6 +23,9 @@ use Google_Client; use Google_Http_REST; +use Google\Client; +use Google\Exception; +use Google\Http\REST; use GuzzleHttp\Psr7\LimitStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; @@ -61,7 +64,7 @@ class StreamableUpload /** @var int */ private $progress; - /** @var Google_Client */ + /** @var Google_Client|Client */ private $client; /** @var \Psr\Http\Message\RequestInterface */ @@ -78,7 +81,7 @@ class StreamableUpload private $httpResultCode; /** - * @param Google_Client $client + * @param Google_Client|Client $client * @param RequestInterface $request * @param string $mimeType * @param null|string|resource|StreamInterface $data Data you want to upload @@ -87,7 +90,7 @@ class StreamableUpload * Only used if resumable=True. */ public function __construct( - Google_Client $client, + $client, RequestInterface $request, $mimeType, $data, @@ -238,7 +241,7 @@ private function makePutRequest(RequestInterface $request) return false; } - return Google_Http_REST::decodeHttpResponse($response, $this->request); + return REST::decodeHttpResponse($response, $this->request); } /** @@ -397,7 +400,7 @@ private function fetchResumeUri() $error = "Failed to start the resumable upload (HTTP {$message})"; $this->client->getLogger()->error($error); - throw new \Google_Exception($error); + throw new Exception($error); } private function transformToUploadUrl() diff --git a/tests/GoogleDriveAdapterTests.php b/tests/GoogleDriveAdapterTests.php index c130781..f3b4b49 100644 --- a/tests/GoogleDriveAdapterTests.php +++ b/tests/GoogleDriveAdapterTests.php @@ -96,11 +96,11 @@ protected static function createFilesystemAdapter() if (!empty($config['teamDriveId'] ?? null)) { $options['teamDriveId'] = $config['teamDriveId']; } - $client = new \Google_Client(); + $client = new \Google\Client(); $client->setClientId($config['GOOGLE_DRIVE_CLIENT_ID']); $client->setClientSecret($config['GOOGLE_DRIVE_CLIENT_SECRET']); $client->refreshToken($config['GOOGLE_DRIVE_REFRESH_TOKEN']); - $service = new \Google_Service_Drive($client); + $service = new \Google\Service\Drive($client); return new GoogleDriveAdapter($service, 'tests/', $options); } catch (\Exception $e) { self::markTestSkipped($e->getMessage()); From 7f074173f9558b5e02875674eafc15c1403e7de5 Mon Sep 17 00:00:00 2001 From: Erik Niebla Date: Mon, 27 Dec 2021 16:17:24 -0500 Subject: [PATCH 3/7] File .gitattributes --- .gitattributes | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9119de6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,15 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.editorconfig export-ignore +/.php_cs.dist.php export-ignore +/.scrutinizer.yml export-ignore +/.styleci.yml export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/docs export-ignore +/tests export-ignore From 4d8e181f8abc22be92f207a5e321ed6ed6a4db2e Mon Sep 17 00:00:00 2001 From: Erik Niebla Date: Thu, 18 Nov 2021 17:42:34 -0500 Subject: [PATCH 4/7] Fix docs (listTeamdrives,emptyTrash) --- README.md | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f0147d4..105cb8f 100644 --- a/README.md +++ b/README.md @@ -126,20 +126,16 @@ try { ##### How to get TeamDrive list and IDs ```php -$client = new \Google_Client(); -$client->setClientId([client_id]); -$client->setClientSecret([client_secret]); -$client->refreshToken([refresh_token]); -$client->setApplicationName('My Google Drive App'); - -$service = new \Google_Service_Drive($client); - -$drives = $service->teamdrives->listTeamdrives()->getTeamDrives(); +$drives = $fs->getAdapter()->getService()->teamdrives->listTeamdrives()->getTeamDrives(); foreach ($drives as $drive) { echo 'TeamDrive: ' . $drive->name . PHP_EOL; - echo 'ID: ' . $drive->id . PHP_EOL; + echo 'ID: ' . $drive->id . PHP_EOL. PHP_EOL; } +``` +##### How permanently deletes all of the user's trashed files +```php +$fs->getAdapter()->emptyTrash([]); ``` ## Using with Laravel Framework @@ -239,4 +235,4 @@ It also contains an adaptation of [Google_Http_MediaFileUpload](https://github.c TeamDrive support was implemented by Maximilian Ruta - [Deltachaos](https://github.com/Deltachaos). -Adapter rewrite for Flysystem V2 and various fixes were implemented by Erik Niebla - [erikn69](https://github.com/erikn69). \ No newline at end of file +Adapter rewrite for Flysystem V2 and various fixes were implemented by Erik Niebla - [erikn69](https://github.com/erikn69). From 1645675e97cce2f00b5471d1d7759df08f985037 Mon Sep 17 00:00:00 2001 From: Mitja Spes Date: Mon, 3 Jan 2022 10:15:38 +0100 Subject: [PATCH 5/7] Google classes PSR cleanup --- src/GoogleDriveAdapter.php | 13 ++++++------- src/StreamableUpload.php | 10 ++++------ 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/GoogleDriveAdapter.php b/src/GoogleDriveAdapter.php index 439fc65..d8e5d9b 100644 --- a/src/GoogleDriveAdapter.php +++ b/src/GoogleDriveAdapter.php @@ -2,7 +2,6 @@ namespace Masbug\Flysystem; -use Google_Service_Drive; use Google\Service\Drive; use Google\Service\Drive\DriveFile; use Google\Service\Drive\FileList; @@ -55,9 +54,9 @@ class GoogleDriveAdapter extends AbstractAdapter const DIRMIME = 'application/vnd.google-apps.folder'; /** - * Google_Service_Drive instance + * Google\Service\Drive instance * - * @var Google_Service_Drive|Drive + * @var Drive */ protected $service; @@ -203,7 +202,7 @@ class GoogleDriveAdapter extends AbstractAdapter /** * GoogleDriveAdapter constructor. * - * @param Google_Service_Drive|Drive $service + * @param Drive $service * @param string|null $root * @param array $options */ @@ -260,9 +259,9 @@ public function __construct($service, $root = null, $options = []) } /** - * Gets the service (Google_Service_Drive) + * Gets the service * - * @return object Google_Service_Drive + * @return Google\Service\Drive */ public function getService() { @@ -1554,7 +1553,7 @@ protected function buildPathFromCacheFileObjects($lastItemId) continue; } - /* @var Google_Service_Drive_DriveFile $obj */ + /* @var DriveFile $obj */ $obj = $this->cacheFileObjects[$itemId]; $parents = $obj->getParents(); diff --git a/src/StreamableUpload.php b/src/StreamableUpload.php index ec0ee3c..2358324 100644 --- a/src/StreamableUpload.php +++ b/src/StreamableUpload.php @@ -21,11 +21,9 @@ * limitations under the License. */ -use Google_Client; -use Google_Http_REST; use Google\Client; -use Google\Exception; use Google\Http\REST; +use Google\Exception as GoogleException; use GuzzleHttp\Psr7\LimitStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; @@ -64,7 +62,7 @@ class StreamableUpload /** @var int */ private $progress; - /** @var Google_Client|Client */ + /** @var Client */ private $client; /** @var \Psr\Http\Message\RequestInterface */ @@ -81,7 +79,7 @@ class StreamableUpload private $httpResultCode; /** - * @param Google_Client|Client $client + * @param Client $client * @param RequestInterface $request * @param string $mimeType * @param null|string|resource|StreamInterface $data Data you want to upload @@ -400,7 +398,7 @@ private function fetchResumeUri() $error = "Failed to start the resumable upload (HTTP {$message})"; $this->client->getLogger()->error($error); - throw new Exception($error); + throw new GoogleException($error); } private function transformToUploadUrl() From a7f656fe196de300e0a20b346d9d8c75c4ca73c4 Mon Sep 17 00:00:00 2001 From: StyleCI Bot Date: Mon, 3 Jan 2022 09:19:48 +0000 Subject: [PATCH 6/7] Apply fixes from StyleCI --- src/StreamableUpload.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/StreamableUpload.php b/src/StreamableUpload.php index 2358324..264865d 100644 --- a/src/StreamableUpload.php +++ b/src/StreamableUpload.php @@ -22,8 +22,8 @@ */ use Google\Client; -use Google\Http\REST; use Google\Exception as GoogleException; +use Google\Http\REST; use GuzzleHttp\Psr7\LimitStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; @@ -79,7 +79,7 @@ class StreamableUpload private $httpResultCode; /** - * @param Client $client + * @param Client $client * @param RequestInterface $request * @param string $mimeType * @param null|string|resource|StreamInterface $data Data you want to upload From 0bd495e0d71c7479faa6ac3cb6e5ef8c3aba357f Mon Sep 17 00:00:00 2001 From: Erik Niebla Date: Mon, 3 Jan 2022 11:02:02 -0500 Subject: [PATCH 7/7] Drop support Guzzle\Psr7 <1.7 --- README.md | 3 ++- composer.json | 3 ++- src/GoogleDriveAdapter.php | 11 ++++------- src/StreamableUpload.php | 24 ++++-------------------- 4 files changed, 12 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 7319f63..fbbe874 100644 --- a/README.md +++ b/README.md @@ -220,8 +220,9 @@ class AppServiceProvider extends ServiceProvider { // can be a custom ServicePro $client->refreshToken($config['refreshToken']); $service = new \Google\Service\Drive($client); $adapter = new \Masbug\Flysystem\GoogleDriveAdapter($service, $config['folder'] ?? '/', $options); + $driver = new \League\Flysystem\Filesystem($adapter); - return new \League\Flysystem\Filesystem($adapter); + return new \Illuminate\Filesystem\FilesystemAdapter($driver); }); } catch(\Exception $e) { // ... diff --git a/composer.json b/composer.json index 10391f2..5dcaa41 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,8 @@ "ext-mbstring": "*", "guzzlehttp/guzzle": "^6.3 | ^7.0", "league/flysystem": "^1.0", - "google/apiclient": "^2.2" + "google/apiclient": "^2.2", + "guzzlehttp/psr7": "^1.7|^2.0" }, "require-dev": { "phpunit/phpunit": "^8.0 | ^9.3" diff --git a/src/GoogleDriveAdapter.php b/src/GoogleDriveAdapter.php index d8e5d9b..e9b90f0 100644 --- a/src/GoogleDriveAdapter.php +++ b/src/GoogleDriveAdapter.php @@ -6,6 +6,7 @@ use Google\Service\Drive\DriveFile; use Google\Service\Drive\FileList; use Google\Service\Drive\Permission; +use GuzzleHttp\Psr7\Utils; use League\Flysystem\Adapter\AbstractAdapter; use League\Flysystem\AdapterInterface; use League\Flysystem\Config; @@ -54,7 +55,7 @@ class GoogleDriveAdapter extends AbstractAdapter const DIRMIME = 'application/vnd.google-apps.folder'; /** - * Google\Service\Drive instance + * \Google\Service\Drive instance * * @var Drive */ @@ -261,7 +262,7 @@ public function __construct($service, $root = null, $options = []) /** * Gets the service * - * @return Google\Service\Drive + * @return \Google\Service\Drive */ public function getService() { @@ -1361,11 +1362,7 @@ protected function upload($path, $contents, Config $config, $updating = null) $file->setMimeType($mime); /** @var StreamInterface $stream */ - if (function_exists('\GuzzleHttp\Psr7\stream_for')) { - $stream = \GuzzleHttp\Psr7\stream_for($contents); - } else { - $stream = \GuzzleHttp\Psr7\Utils::streamFor($contents); - } + $stream = Utils::streamFor($contents); $size = $stream->getSize(); if ($size <= self::MAX_CHUNK_SIZE) { diff --git a/src/StreamableUpload.php b/src/StreamableUpload.php index 264865d..c44e0a7 100644 --- a/src/StreamableUpload.php +++ b/src/StreamableUpload.php @@ -27,6 +27,7 @@ use GuzzleHttp\Psr7\LimitStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; +use GuzzleHttp\Psr7\Utils; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; @@ -98,15 +99,7 @@ public function __construct( $this->client = $client; $this->request = $request; $this->mimeType = $mimeType; - if ($data !== null) { - if (function_exists('\GuzzleHttp\Psr7\stream_for')) { - $this->data = \GuzzleHttp\Psr7\stream_for($data); - } else { - $this->data = \GuzzleHttp\Psr7\Utils::streamFor($data); - } - } else { - $this->data = null; - } + $this->data = $data !== null ? Utils::streamFor($data) : null; $this->resumable = $resumable; $this->chunkSize = is_bool($chunkSize) ? 0 : $chunkSize; $this->progress = 0; @@ -165,11 +158,7 @@ public function nextChunk($chunk = false) } $chunk = new LimitStream($this->data, $this->chunkSize, $this->data->tell()); } else { - if (function_exists('\GuzzleHttp\Psr7\stream_for')) { - $chunk = \GuzzleHttp\Psr7\stream_for($chunk); - } else { - $chunk = \GuzzleHttp\Psr7\Utils::streamFor($chunk); - } + $chunk = Utils::streamFor($chunk); } $size = $chunk->getSize(); @@ -311,13 +300,8 @@ private function process() } } } - if (function_exists('\GuzzleHttp\Psr7\stream_for')) { - $stream = \GuzzleHttp\Psr7\stream_for($postBody); - } else { - $stream = \GuzzleHttp\Psr7\Utils::streamFor($postBody); - } - $request = $request->withBody($stream); + $request = $request->withBody(Utils::streamFor($postBody)); if (isset($contentType) && $contentType) { $request = $request->withHeader('content-type', $contentType);