From 99b8394a646556a8b76fcb746990faae0beb0d48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Thu, 2 Apr 2026 20:00:34 +0100 Subject: [PATCH 01/10] Refactor login from trait to AdapterFactory and add adapter for GCS and R2 --- composer.json | 3 + config/uppy.php | 82 ++++++- src/Controller/FilesController.php | 15 +- src/Model/Table/FilesTable.php | 27 +- src/Storage/AdapterFactory.php | 31 +++ src/Storage/GcsAdapter.php | 82 +++++++ src/Storage/R2Adapter.php | 105 ++++++++ src/Storage/S3Adapter.php | 86 +++++++ src/Storage/StorageAdapterInterface.php | 44 ++++ src/Util/S3Trait.php | 230 ------------------ tests/TestCase/Storage/AdapterFactoryTest.php | 53 ++++ tests/TestCase/Storage/GcsAdapterTest.php | 109 +++++++++ tests/TestCase/Storage/R2AdapterTest.php | 55 +++++ tests/TestCase/Storage/S3AdapterTest.php | 59 +++++ 14 files changed, 728 insertions(+), 253 deletions(-) create mode 100644 src/Storage/AdapterFactory.php create mode 100644 src/Storage/GcsAdapter.php create mode 100644 src/Storage/R2Adapter.php create mode 100644 src/Storage/S3Adapter.php create mode 100644 src/Storage/StorageAdapterInterface.php delete mode 100644 src/Util/S3Trait.php create mode 100644 tests/TestCase/Storage/AdapterFactoryTest.php create mode 100644 tests/TestCase/Storage/GcsAdapterTest.php create mode 100644 tests/TestCase/Storage/R2AdapterTest.php create mode 100644 tests/TestCase/Storage/S3AdapterTest.php diff --git a/composer.json b/composer.json index 0bd0144..546dd86 100644 --- a/composer.json +++ b/composer.json @@ -22,6 +22,9 @@ "cakephp/migrations": "^4.0.0", "markstory/asset_compress": "^5.0.0" }, + "suggest": { + "google/cloud-storage": "Required to use the GCS storage adapter (^1.50)" + }, "autoload": { "psr-4": { "CakeDC\\Uppy\\": "src" diff --git a/config/uppy.php b/config/uppy.php index c8356ab..830b616 100644 --- a/config/uppy.php +++ b/config/uppy.php @@ -2,6 +2,7 @@ declare(strict_types=1); /** + ** * Copyright 2023, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License @@ -9,17 +10,34 @@ * * @copyright Copyright 2023, Cake Development Corporation (https://www.cakedc.com) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * + * Uppy plugin configuration template. + * Copy this file to your application's config/ directory and customise it. + * + * Required env vars per driver: + * s3: S3_REGION, S3_KEY, S3_SECRET, S3_BUCKET + * gcs: GCS_PROJECT_ID, GCS_KEY_FILE_PATH, GCS_BUCKET + * r2: R2_ACCOUNT_ID, R2_KEY, R2_SECRET, R2_BUCKET, R2_PUBLIC_DOMAIN */ return [ 'Uppy' => [ + /* + * Storage driver: 's3' | 'gcs' | 'r2' + * Set UPPY_DRIVER in your .env file or override here. + */ + 'driver' => env('UPPY_DRIVER', 's3'), + 'Props' => [ - // the Table Alias to identify the user who uploaded the file - 'usersAliasModel' => 'Users', - // the Table className to identify the user who uploaded the file 'usersModel' => 'Users', - 'deleteFileS3' => true, + /* + * When true and a file record is deleted, the object is also + * removed from storage. Renamed from deleteFileS3 to apply to + * all drivers. Falls back to deleteFileS3 for backwards compat. + */ + 'deleteFileStorage' => true, 'tableFiles' => 'uppy_files', ], + 'AcceptedContentTypes' => [ 'application/pdf', 'image/png', @@ -29,6 +47,7 @@ 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', ], + 'AcceptedExtensions' => [ 'pdf', 'png', @@ -38,25 +57,62 @@ 'ppt', 'pptx', ], + /* - * S3 configuration to manage files - */ + * Amazon S3 — used when driver = 's3' + * Set connection = 'dummy' in test environments. + */ 'S3' => [ - 'contants' => [ + 'constants' => [ 'lifeTimeGetObject' => '+20 minutes', 'lifeTimePutObject' => '+5 minutes', ], 'config' => [ 'version' => 'latest', - 'connection' => 'real', //dummy - 'region' => filter_var(env('S3_REGION', null)), - 'endpoint' => filter_var(env('S3_END_POINT', null)), + 'region' => env('S3_REGION', null), + 'credentials' => [ + 'key' => env('S3_KEY', null), + 'secret' => env('S3_SECRET', null), + ], + ], + 'bucket' => env('S3_BUCKET', null), + ], + + /* + * Google Cloud Storage — used when driver = 'gcs' + * Requires: composer require google/cloud-storage ^1.50 + */ + 'GCS' => [ + 'projectId' => env('GCS_PROJECT_ID', null), + 'keyFilePath' => env('GCS_KEY_FILE_PATH', null), + 'bucket' => env('GCS_BUCKET', null), + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + ], + + /* + * Cloudflare R2 — used when driver = 'r2' + * R2 is S3-compatible; uses AWS SDK with a custom endpoint. + * publicDomain: your custom domain or pub-.r2.dev URL. + * Set connection = 'dummy' in test environments. + */ + 'R2' => [ + 'bucket' => env('R2_BUCKET', null), + 'publicDomain' => env('R2_PUBLIC_DOMAIN', null), + 'constants' => [ + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + ], + 'config' => [ + 'version' => env('R2_VERSION', 'latest'), + 'region' => env('R2_REGION', 'auto'), + 'endpoint' => env('R2_ENDPOINT', null), 'credentials' => [ - 'key' => filter_var(env('S3_KEY', null)), - 'secret' => filter_var(env('S3_SECRET', null)), + 'key' => env('R2_KEY', null), + 'secret' => env('R2_SECRET', null), ], + 'use_path_style_endpoint' => true, ], - 'bucket' => filter_var(env('S3_BUCKET')), ], ], ]; diff --git a/src/Controller/FilesController.php b/src/Controller/FilesController.php index 4c3a8a7..eeaf3bd 100644 --- a/src/Controller/FilesController.php +++ b/src/Controller/FilesController.php @@ -19,7 +19,8 @@ use Cake\ORM\Exception\MissingTableClassException; use Cake\Utility\Inflector; use Cake\Utility\Text; -use CakeDC\Uppy\Util\S3Trait; +use CakeDC\Uppy\Storage\AdapterFactory; +use CakeDC\Uppy\Storage\StorageAdapterInterface; use function Cake\I18n\__; /** @@ -29,7 +30,7 @@ */ class FilesController extends AppController { - use S3Trait; + private StorageAdapterInterface $storageAdapter; /** * Initialize method @@ -41,6 +42,7 @@ class FilesController extends AppController public function initialize(): void { parent::initialize(); + $this->storageAdapter = AdapterFactory::create(); if (!$this->components()->has('FormProtection')) { $this->loadComponent('FormProtection'); } @@ -65,7 +67,7 @@ public function view(string|int|null $id = null): ?Response /** @var \CakeDC\Uppy\Model\Entity\File $file */ $file = $this->Files->get($id); - $presignedUrl = $this->presignedUrl($file->path, $file->filename); + $presignedUrl = $this->storageAdapter->presignedUrl($file->path); return $this->redirect($presignedUrl); } @@ -170,6 +172,11 @@ public function delete(string|int|null $id = null): ?Response $this->getRequest()->allowMethod(['post', 'delete']); $file = $this->Files->get($id); if ($this->Files->delete($file)) { + $shouldDelete = Configure::read('Uppy.Props.deleteFileStorage', + Configure::read('Uppy.Props.deleteFileS3', true)); + if ($shouldDelete) { + $this->storageAdapter->deleteObject($file->path); + } $this->Flash->success(__('The file has been deleted.')); } else { $this->Flash->error(__('The file could not be deleted. Please, try again.')); @@ -199,7 +206,7 @@ public function sign(): ?Response throw new PageOutOfBoundsException(__('contenType {0} is not valid', h($contentType))); } - $presignedRequest = $this->createPresignedRequest($filename, $contentType); + $presignedRequest = $this->storageAdapter->createPresignedRequest($filename, $contentType); return $this->getResponse() ->withHeader('content-type', 'application/json') diff --git a/src/Model/Table/FilesTable.php b/src/Model/Table/FilesTable.php index c8475b8..efff522 100644 --- a/src/Model/Table/FilesTable.php +++ b/src/Model/Table/FilesTable.php @@ -24,7 +24,8 @@ use Cake\ORM\Table; use Cake\Validation\Validator; use CakeDC\Uppy\Model\Entity\File; -use CakeDC\Uppy\Util\S3Trait; +use CakeDC\Uppy\Storage\AdapterFactory; +use CakeDC\Uppy\Storage\StorageAdapterInterface; use function Cake\I18n\__; /** @@ -42,7 +43,19 @@ */ class FilesTable extends Table { - use S3Trait; + private StorageAdapterInterface $storageAdapter; + + /** + * @return void + */ + public function getStorageAdapter(): StorageAdapterInterface + { + if (!isset($this->storageAdapter)) { + $this->storageAdapter = AdapterFactory::create(); + } + + return $this->storageAdapter; + } /** * Initialize method @@ -158,7 +171,7 @@ public function buildRules(RulesChecker $rules): RulesChecker } /** - * If it's configured prop deleteFileS3 delete file in S3 repository + * If it's configured prop deleteFileStorage delete file from storage * * @param \Cake\Event\EventInterface $event The beforeSave event that was fired * @param \CakeDC\Uppy\Model\Entity\File $entity The entity that is going to be saved @@ -167,8 +180,10 @@ public function buildRules(RulesChecker $rules): RulesChecker */ public function afterDelete(EventInterface $event, File $entity, ArrayObject $options): void { - if (Configure::read('Uppy.Props.deleteFileS3', false)) { - $this->deleteObject($entity->path, $entity->filename); + $shouldDelete = Configure::read('Uppy.Props.deleteFileStorage', + Configure::read('Uppy.Props.deleteFileS3', false)); + if ($shouldDelete) { + $this->getStorageAdapter()->deleteObject($entity->path); } } @@ -220,7 +235,7 @@ public function findDatatable( $row = []; $row['filename'] = $file->filename; $row['extension'] = $file->extension; - $row['signedUrl'] = $this->presignedUrl($file->path, $file->filename); + $row['signedUrl'] = $this->getStorageAdapter()->presignedUrl($file->path); $row['filesize'] = Number::toReadableSize($file->filesize ?? 0); $row['created'] = $file->created?->i18nFormat('yyyy-MM-dd'); $row['id'] = $file->id; diff --git a/src/Storage/AdapterFactory.php b/src/Storage/AdapterFactory.php new file mode 100644 index 0000000..307a50d --- /dev/null +++ b/src/Storage/AdapterFactory.php @@ -0,0 +1,31 @@ + new S3Adapter(), + 'gcs' => new GcsAdapter(), + 'r2' => new R2Adapter(), + default => throw new InvalidArgumentException("Unknown Uppy driver: {$driver}"), + }; + } +} diff --git a/src/Storage/GcsAdapter.php b/src/Storage/GcsAdapter.php new file mode 100644 index 0000000..22e8942 --- /dev/null +++ b/src/Storage/GcsAdapter.php @@ -0,0 +1,82 @@ +client ??= new StorageClient([ + 'projectId' => Configure::readOrFail('Uppy.GCS.projectId'), + 'keyFilePath' => Configure::readOrFail('Uppy.GCS.keyFilePath'), + ]); + } + + private function bucket(): string + { + return (string)Configure::readOrFail('Uppy.GCS.bucket'); + } + + public function createPresignedRequest(string $path, string $contentType): RequestInterface + { + $expires = new DateTime(Configure::readOrFail('Uppy.GCS.lifeTimePutObject')); + $signedUrl = $this->getClient() + ->bucket($this->bucket()) + ->object($path) + ->signedUrl($expires, [ + 'method' => 'PUT', + 'contentType' => $contentType, + 'version' => 'v4', + ]); + + return (new Request($signedUrl, 'PUT'))->withHeader('Content-Type', $contentType); + } + + public function presignedUrl(string $path, int $ttlSeconds = 3600): string + { + $expires = new DateTime("+{$ttlSeconds} seconds"); + + return (string)$this->getClient() + ->bucket($this->bucket()) + ->object($path) + ->signedUrl($expires, [ + 'method' => 'GET', + 'version' => 'v4', + ]); + } + + public function deleteObject(string $path): bool + { + try { + $this->getClient()->bucket($this->bucket())->object($path)->delete(); + + return true; + } catch (NotFoundException) { + return true; // already gone — idempotent + } catch (GoogleException) { + return false; + } + } +} diff --git a/src/Storage/R2Adapter.php b/src/Storage/R2Adapter.php new file mode 100644 index 0000000..0812361 --- /dev/null +++ b/src/Storage/R2Adapter.php @@ -0,0 +1,105 @@ +client ??= new S3Client(Configure::read('Uppy.R2.config')); + } + + /** + * @return string + */ + private function bucket(): string + { + return (string)Configure::readOrFail('Uppy.R2.bucket'); + } + + /** + * @param string $path + * @param string $contentType + * @return \Psr\Http\Message\RequestInterface + */ + public function createPresignedRequest(string $path, string $contentType): RequestInterface + { + $client = $this->getClient(); + + $command = $client->getCommand('PutObject', [ + 'Bucket' => $this->bucket(), + 'Key' => $path, + 'ContentType' => $contentType, + ]); + + return $client->createPresignedRequest( + $command, + Configure::readOrFail('Uppy.R2.constants.lifeTimePutObject'), + ); + } + + /** + * @param string $path + * @param int $ttlSeconds + * @return string + */ + public function presignedUrl(string $path, int $ttlSeconds = 3600): string + { + $client = $this->getClient(); + + $cmd = $client->getCommand('GetObject', [ + 'Bucket' => $this->bucket(), + 'Key' => $path, + ]); + + $request = $client->createPresignedRequest($cmd, "+{$ttlSeconds} seconds"); + + return (string)$request->getUri(); + } + + /** + * @param string $path + * @return bool + */ + public function deleteObject(string $path): bool + { + if (Configure::read('Uppy.R2.connection') === 'dummy') { + return true; + } + + $client = $this->getClient(); + if (!$client->doesObjectExist($this->bucket(), $path)) { + return true; + } + + $client->deleteObject(['Bucket' => $this->bucket(), 'Key' => $path]); + + return !$client->doesObjectExist($this->bucket(), $path); + } +} diff --git a/src/Storage/S3Adapter.php b/src/Storage/S3Adapter.php new file mode 100644 index 0000000..8acf123 --- /dev/null +++ b/src/Storage/S3Adapter.php @@ -0,0 +1,86 @@ +client ??= new S3Client(Configure::readOrFail('Uppy.S3.config')); + } + + private function bucket(): string + { + return (string)Configure::readOrFail('Uppy.S3.bucket'); + } + + public function createPresignedRequest(string $path, string $contentType): RequestInterface + { + if (Configure::read('Uppy.S3.config.connection') === 'dummy') { + return (new Request())->withUri(new Uri('https://example.com')); + } + + $command = $this->getClient()->getCommand('putObject', [ + 'Bucket' => $this->bucket(), + 'Key' => $path, + 'ContentType' => $contentType, + 'Body' => '', + ]); + + return $this->getClient()->createPresignedRequest( + $command, + Configure::readOrFail('Uppy.S3.constants.lifeTimePutObject'), + ); + } + + public function presignedUrl(string $path, int $ttlSeconds = 3600): string + { + if (Configure::read('Uppy.S3.config.connection') === 'dummy') { + return 'https://example.com'; + } + + $cmd = $this->getClient()->getCommand('GetObject', [ + 'Bucket' => $this->bucket(), + 'Key' => $path, + ]); + $request = $this->getClient()->createPresignedRequest($cmd, "+{$ttlSeconds} seconds"); + + return (string)$request->getUri(); + } + + public function deleteObject(string $path): bool + { + if (Configure::read('Uppy.S3.config.connection') === 'dummy') { + return true; + } + + $client = $this->getClient(); + if (!$client->doesObjectExist($this->bucket(), $path)) { + return true; + } + + $client->deleteObject(['Bucket' => $this->bucket(), 'Key' => $path]); + + return !$client->doesObjectExist($this->bucket(), $path); + } +} diff --git a/src/Storage/StorageAdapterInterface.php b/src/Storage/StorageAdapterInterface.php new file mode 100644 index 0000000..b370f06 --- /dev/null +++ b/src/Storage/StorageAdapterInterface.php @@ -0,0 +1,44 @@ +doesObjectExist(Configure::readOrFail('Uppy.S3.bucket'), $path); - if ($exist) { - $s3Client->deleteObject([ - 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), - 'Key' => $path, - ]); - if ($s3Client->doesObjectExist(Configure::readOrFail('Uppy.S3.bucket'), $path)) { - return false; - } - } - } - - return true; - } - - /** - * Generate a signed GET uRI to acces files in S3, note CORS must be configured for the domain - * - * @see /config/cors.xml - * @param string|null $path string used as path in S3 - * @param string|null $name string filename - * @return string - */ - protected function presignedUrl(?string $path, ?string $name): string - { - if (Configure::read('Uppy.S3.config.connection') === 'dummy') { - return 'https://example.com'; - } - - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - $cmd = $s3Client->getCommand('GetObject', [ - 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), - 'Key' => $path, - ]); - $request = $s3Client->createPresignedRequest($cmd, Configure::read('Uppy.S3.contants.lifeTimeGetObject')); - - return (string)$request->getUri(); - } - - /** - * Generate a presigned PUT request to send files to S3, note CORS must be configured for the domain - * - * @see /config/cors.xml - * @param string $path string used as path in S3 - * @param string $contentType string contenttype - * @return \Psr\Http\Message\RequestInterface - */ - protected function createPresignedRequest(string $path, string $contentType): RequestInterface - { - if (Configure::read('Uppy.S3.config.connection') === 'dummy') { - return (new Request()) - ->withUri(new Uri('https://example.com')); - } else { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - $command = $s3Client->getCommand('putObject', [ - 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), - 'Key' => $path, - 'ContentType' => $contentType, - 'Body' => '', - ]); - - return $s3Client->createPresignedRequest($command, Configure::readOrFail('Uppy.S3.contants.lifeTimePutObject')); - } - } - - /** - * Upload source dir to target path using transfer options - * - * @see /config/cors.xml - * @param string $source string used as filesystem source dir - * @param string $target string used as path in S3 - * @return void - */ - public function uploadDir(string $source, string $target): void - { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - $dest = 's3://' . Configure::readOrFail('Uppy.S3.bucket') . DS . $target; - $manager = new Transfer($s3Client, $source, $dest); - $manager->transfer(); - - $promise = $manager->promise(); - - $promise->then(function (): void { - //Do nothing - }); - - $promise->otherwise(function ($reason): void { - throw new Exception('Transfer failed. Please try again.'); - }); - } - - /** - * Upload file using S3 putObject method - * - * @param string $sourceFilePath string used as filesystem source file - * @param string $destinationS3Path string used as path in S3 - * @return void - * @throws \Exception - * @see /config/cors.xml - */ - public function uploadFile(string $sourceFilePath, string $destinationS3Path): void - { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - $s3Options = [ - 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), - 'Key' => $destinationS3Path, - 'SourceFile' => $sourceFilePath, - ]; - $result = $s3Client->putObject($s3Options)->toArray(); - - if ( - !array_key_exists('@metadata', $result) || - !array_key_exists('statusCode', $result['@metadata']) - ) { - throw new Exception('Error on response data. Please try again.'); - } - if ($result['@metadata']['statusCode'] !== 200) { - throw new Exception('Error coping/moving file. Please try again.'); - } - } - - /** - * Delete file using S3 deleteObject method - * - * @see /config/cors.xml - * @param string $fileS3Path string used as path in S3 - * @return void - */ - public function deleteFile(string $fileS3Path): void - { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - $s3Options = [ - 'Bucket' => Configure::read('Uppy.S3.bucket'), - 'Key' => $fileS3Path, - ]; - $s3Client->deleteObject($s3Options); - } - - /** - * Delete dir on S3 usign matching rule - * - * @param string $fileS3Path string used as path in S3 - * @return void - * @throws \Exception - * @see /config/cors.xml - */ - public function deleteDir(string $fileS3Path): void - { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - if ($this->folderExists($fileS3Path)) { - $s3Client->deleteMatchingObjects(Configure::readOrFail('Uppy.S3.bucket'), $fileS3Path); - } else { - throw new Exception('File doesn\'t exist. Please try again.'); - } - } - - /** - * Check if file exists in S3 bucket - * - * @param string $filename filename - * @return bool - */ - public function fileExists(string $filename): bool - { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - - return $s3Client->doesObjectExist(Configure::readOrFail('Uppy.S3.bucket'), $filename); - } - - /** - * Check if folder exists in S3 bucket - * - * @param string $filename filename - * @return bool - * @throws \Exception - */ - public function folderExists(string $filename): bool - { - $s3Client = new S3Client(Configure::readOrFail('Uppy.S3.config')); - $list = $s3Client->listObjectsV2([ - 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), - 'Prefix' => $filename, - ]); - if ($list['Contents'] > 0) { - return true; - } else { - throw new Exception('Folder doesn\'t exist. Please try again.'); - } - } -} diff --git a/tests/TestCase/Storage/AdapterFactoryTest.php b/tests/TestCase/Storage/AdapterFactoryTest.php new file mode 100644 index 0000000..58795ae --- /dev/null +++ b/tests/TestCase/Storage/AdapterFactoryTest.php @@ -0,0 +1,53 @@ +assertInstanceOf(S3Adapter::class, AdapterFactory::create()); + } + + public function testCreateReturnsGcsAdapterForGcsDriver(): void + { + Configure::write('Uppy.driver', 'gcs'); + $this->assertInstanceOf(GcsAdapter::class, AdapterFactory::create()); + } + + public function testCreateReturnsR2AdapterForR2Driver(): void + { + Configure::write('Uppy.driver', 'r2'); + $this->assertInstanceOf(R2Adapter::class, AdapterFactory::create()); + } + + public function testCreateDefaultsToS3WhenDriverNotSet(): void + { + Configure::delete('Uppy.driver'); + $this->assertInstanceOf(S3Adapter::class, AdapterFactory::create()); + } + + public function testCreateThrowsForUnknownDriver(): void + { + Configure::write('Uppy.driver', 'azure'); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unknown Uppy driver: azure'); + AdapterFactory::create(); + } +} diff --git a/tests/TestCase/Storage/GcsAdapterTest.php b/tests/TestCase/Storage/GcsAdapterTest.php new file mode 100644 index 0000000..6b68544 --- /dev/null +++ b/tests/TestCase/Storage/GcsAdapterTest.php @@ -0,0 +1,109 @@ + 'test-project', + 'keyFilePath' => '/tmp/fake-key.json', + 'bucket' => 'test-bucket', + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + ]); + + $this->mockObject = $this->createMock(StorageObject::class); + $this->mockBucket = $this->createMock(Bucket::class); + $this->mockBucket->method('object')->willReturn($this->mockObject); + $this->mockClient = $this->createMock(StorageClient::class); + $this->mockClient->method('bucket')->willReturn($this->mockBucket); + } + + protected function tearDown(): void + { + Configure::delete('Uppy.GCS'); + parent::tearDown(); + } + + public function testCreatePresignedRequestReturnsPsrRequestWithPutMethod(): void + { + $this->mockObject + ->method('signedUrl') + ->with($this->isInstanceOf(DateTime::class), $this->arrayHasKey('method')) + ->willReturn('https://storage.googleapis.com/signed-put-url'); + + $adapter = new GcsAdapter($this->mockClient); + $result = $adapter->createPresignedRequest('users/uuid/file.jpg', 'image/jpeg'); + + $this->assertInstanceOf(RequestInterface::class, $result); + $this->assertSame('PUT', $result->getMethod()); + $this->assertStringContainsString('signed-put-url', (string)$result->getUri()); + $this->assertSame('image/jpeg', $result->getHeaderLine('Content-Type')); + } + + public function testPresignedUrlReturnsSignedGetUrl(): void + { + $this->mockObject + ->method('signedUrl') + ->with($this->isInstanceOf(DateTime::class), $this->arrayHasKey('method')) + ->willReturn('https://storage.googleapis.com/signed-get-url'); + + $adapter = new GcsAdapter($this->mockClient); + $result = $adapter->presignedUrl('users/uuid/file.jpg', 3600); + + $this->assertSame('https://storage.googleapis.com/signed-get-url', $result); + } + + public function testDeleteObjectReturnsTrueOnSuccess(): void + { + $this->mockObject->expects($this->once())->method('delete'); + + $adapter = new GcsAdapter($this->mockClient); + $result = $adapter->deleteObject('users/uuid/file.jpg'); + + $this->assertTrue($result); + } + + public function testDeleteObjectReturnsFalseOnException(): void + { + $this->mockObject + ->method('delete') + ->willThrowException(new GoogleException('GCS error')); + + $adapter = new GcsAdapter($this->mockClient); + $result = $adapter->deleteObject('users/uuid/file.jpg'); + + $this->assertFalse($result); + } + + public function testDeleteObjectReturnsTrueWhenObjectNotFound(): void + { + $this->mockObject + ->method('delete') + ->willThrowException(new NotFoundException('Not found')); + + $adapter = new GcsAdapter($this->mockClient); + $result = $adapter->deleteObject('users/uuid/file.jpg'); + + $this->assertTrue($result); + } +} diff --git a/tests/TestCase/Storage/R2AdapterTest.php b/tests/TestCase/Storage/R2AdapterTest.php new file mode 100644 index 0000000..d29da3b --- /dev/null +++ b/tests/TestCase/Storage/R2AdapterTest.php @@ -0,0 +1,55 @@ + 'test-account-id', + 'credentials' => ['key' => 'fake', 'secret' => 'fake'], + 'bucket' => 'test-bucket', + 'publicDomain' => 'files.example.com', + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + 'connection' => 'dummy', + ]); + } + + protected function tearDown(): void + { + Configure::delete('Uppy.R2'); + parent::tearDown(); + } + + public function testCreatePresignedRequestReturnsPsrRequest(): void + { + $adapter = new R2Adapter(); + $result = $adapter->createPresignedRequest('users/uuid/file.jpg', 'image/jpeg'); + $this->assertInstanceOf(RequestInterface::class, $result); + $this->assertSame('https://example.com', (string)$result->getUri()); + } + + public function testPresignedUrlReturnsString(): void + { + $adapter = new R2Adapter(); + $result = $adapter->presignedUrl('users/uuid/file.jpg'); + $this->assertSame('https://example.com', $result); + } + + public function testDeleteObjectReturnsTrueWhenConnectionDummy(): void + { + $adapter = new R2Adapter(); + $result = $adapter->deleteObject('users/uuid/file.jpg'); + $this->assertTrue($result); + } +} diff --git a/tests/TestCase/Storage/S3AdapterTest.php b/tests/TestCase/Storage/S3AdapterTest.php new file mode 100644 index 0000000..449de46 --- /dev/null +++ b/tests/TestCase/Storage/S3AdapterTest.php @@ -0,0 +1,59 @@ + [ + 'lifeTimeGetObject' => '+20 minutes', + 'lifeTimePutObject' => '+5 minutes', + ], + 'config' => [ + 'version' => 'latest', + 'region' => 'us-east-1', + 'connection' => 'dummy', + 'credentials' => ['key' => 'fake', 'secret' => 'fake'], + ], + 'bucket' => 'test-bucket', + ]); + } + + protected function tearDown(): void + { + Configure::delete('Uppy.S3'); + parent::tearDown(); + } + + public function testCreatePresignedRequestReturnsPsrRequest(): void + { + $adapter = new S3Adapter(); + $result = $adapter->createPresignedRequest('users/uuid/file.jpg', 'image/jpeg'); + $this->assertInstanceOf(RequestInterface::class, $result); + $this->assertSame('https://example.com', (string)$result->getUri()); + } + + public function testPresignedUrlReturnsString(): void + { + $adapter = new S3Adapter(); + $result = $adapter->presignedUrl('users/uuid/file.jpg'); + $this->assertSame('https://example.com', $result); + } + + public function testDeleteObjectReturnsTrueWhenConnectionDummy(): void + { + $adapter = new S3Adapter(); + $result = $adapter->deleteObject('users/uuid/file.jpg'); + $this->assertTrue($result); + } +} From 02abbe36a5f316392164689647856fa84c06d43a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Mon, 6 Apr 2026 11:08:01 +0100 Subject: [PATCH 02/10] Add backward compatibility --- config/uppy.php | 1 + src/Model/Table/FilesTable.php | 12 +- src/Storage/S3Adapter.php | 18 ++- src/Util/S3Trait.php | 229 +++++++++++++++++++++++++++++++++ 4 files changed, 256 insertions(+), 4 deletions(-) create mode 100644 src/Util/S3Trait.php diff --git a/config/uppy.php b/config/uppy.php index 830b616..68d8a40 100644 --- a/config/uppy.php +++ b/config/uppy.php @@ -28,6 +28,7 @@ 'driver' => env('UPPY_DRIVER', 's3'), 'Props' => [ + 'usersAliasModel' => 'Users', 'usersModel' => 'Users', /* * When true and a file record is deleted, the object is also diff --git a/src/Model/Table/FilesTable.php b/src/Model/Table/FilesTable.php index efff522..4c2bb45 100644 --- a/src/Model/Table/FilesTable.php +++ b/src/Model/Table/FilesTable.php @@ -45,6 +45,14 @@ class FilesTable extends Table { private StorageAdapterInterface $storageAdapter; + private function getUsersAliasModel(): string + { + return (string)Configure::read( + 'Uppy.Props.usersAliasModel', + Configure::readOrFail('Uppy.Props.usersModel') + ); + } + /** * @return void */ @@ -73,7 +81,7 @@ public function initialize(array $config): void $this->addBehavior('Timestamp'); - $this->belongsTo(Configure::readOrFail('Uppy.Props.usersAliasModel'), [ + $this->belongsTo($this->getUsersAliasModel(), [ 'foreignKey' => 'user_id', 'className' => Configure::readOrFail('Uppy.Props.usersModel'), ]); @@ -162,7 +170,7 @@ public function buildRules(RulesChecker $rules): RulesChecker $rules->add( $rules->existsIn( 'user_id', - Configure::readOrFail('Uppy.Props.usersAliasModel') + $this->getUsersAliasModel() ), ['errorField' => 'user_id'] ); diff --git a/src/Storage/S3Adapter.php b/src/Storage/S3Adapter.php index 8acf123..bfb194a 100644 --- a/src/Storage/S3Adapter.php +++ b/src/Storage/S3Adapter.php @@ -34,6 +34,17 @@ private function bucket(): string return (string)Configure::readOrFail('Uppy.S3.bucket'); } + private function getLegacyAwareLifetime(string $operation): string + { + $newKey = "Uppy.S3.constants.{$operation}"; + $legacyKey = "Uppy.S3.contants.{$operation}"; + + return (string)( + Configure::read($newKey) + ?? Configure::readOrFail($legacyKey) + ); + } + public function createPresignedRequest(string $path, string $contentType): RequestInterface { if (Configure::read('Uppy.S3.config.connection') === 'dummy') { @@ -49,7 +60,7 @@ public function createPresignedRequest(string $path, string $contentType): Reque return $this->getClient()->createPresignedRequest( $command, - Configure::readOrFail('Uppy.S3.constants.lifeTimePutObject'), + $this->getLegacyAwareLifetime('lifeTimePutObject'), ); } @@ -63,7 +74,10 @@ public function presignedUrl(string $path, int $ttlSeconds = 3600): string 'Bucket' => $this->bucket(), 'Key' => $path, ]); - $request = $this->getClient()->createPresignedRequest($cmd, "+{$ttlSeconds} seconds"); + $expires = $ttlSeconds === 3600 + ? $this->getLegacyAwareLifetime('lifeTimeGetObject') + : "+{$ttlSeconds} seconds"; + $request = $this->getClient()->createPresignedRequest($cmd, $expires); return (string)$request->getUri(); } diff --git a/src/Util/S3Trait.php b/src/Util/S3Trait.php new file mode 100644 index 0000000..882cc03 --- /dev/null +++ b/src/Util/S3Trait.php @@ -0,0 +1,229 @@ +getS3Client(); + $exist = $s3Client->doesObjectExist(Configure::readOrFail('Uppy.S3.bucket'), $path); + if ($exist) { + $s3Client->deleteObject([ + 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), + 'Key' => $path, + ]); + if ($s3Client->doesObjectExist(Configure::readOrFail('Uppy.S3.bucket'), $path)) { + return false; + } + } + } + + return true; + } + + /** + * @see /config/cors.xml + * @param string|null $path string used as path in S3 + * @param string|null $name string filename + * @return string + */ + protected function presignedUrl(?string $path, ?string $name): string + { + if (Configure::read('Uppy.S3.config.connection') === 'dummy') { + return 'https://example.com'; + } + + $s3Client = $this->getS3Client(); + $cmd = $s3Client->getCommand('GetObject', [ + 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), + 'Key' => $path, + ]); + $request = $s3Client->createPresignedRequest($cmd, $this->getS3Lifetime('lifeTimeGetObject')); + + return (string)$request->getUri(); + } + + /** + * @see /config/cors.xml + * @param string $path string used as path in S3 + * @param string $contentType string contenttype + * @return \Psr\Http\Message\RequestInterface + */ + protected function createPresignedRequest(string $path, string $contentType): RequestInterface + { + if (Configure::read('Uppy.S3.config.connection') === 'dummy') { + return (new Request()) + ->withUri(new Uri('https://example.com')); + } + + $s3Client = $this->getS3Client(); + $command = $s3Client->getCommand('putObject', [ + 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), + 'Key' => $path, + 'ContentType' => $contentType, + 'Body' => '', + ]); + + return $s3Client->createPresignedRequest($command, $this->getS3Lifetime('lifeTimePutObject')); + } + + /** + * @see /config/cors.xml + * @param string $source string used as filesystem source dir + * @param string $target string used as path in S3 + * @return void + */ + public function uploadDir(string $source, string $target): void + { + $s3Client = $this->getS3Client(); + $dest = 's3://' . Configure::readOrFail('Uppy.S3.bucket') . DS . $target; + $manager = new Transfer($s3Client, $source, $dest); + $manager->transfer(); + + $promise = $manager->promise(); + + $promise->then(function (): void { + }); + + $promise->otherwise(function ($reason): void { + throw new Exception('Transfer failed. Please try again.'); + }); + } + + /** + * @param string $sourceFilePath string used as filesystem source file + * @param string $destinationS3Path string used as path in S3 + * @return void + * @throws \Exception + * @see /config/cors.xml + */ + public function uploadFile(string $sourceFilePath, string $destinationS3Path): void + { + $s3Client = $this->getS3Client(); + $s3Options = [ + 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), + 'Key' => $destinationS3Path, + 'SourceFile' => $sourceFilePath, + ]; + $result = $s3Client->putObject($s3Options)->toArray(); + + if ( + !array_key_exists('@metadata', $result) || + !array_key_exists('statusCode', $result['@metadata']) + ) { + throw new Exception('Error on response data. Please try again.'); + } + if ($result['@metadata']['statusCode'] !== 200) { + throw new Exception('Error coping/moving file. Please try again.'); + } + } + + /** + * @see /config/cors.xml + * @param string $fileS3Path string used as path in S3 + * @return void + */ + public function deleteFile(string $fileS3Path): void + { + $s3Client = $this->getS3Client(); + $s3Options = [ + 'Bucket' => Configure::read('Uppy.S3.bucket'), + 'Key' => $fileS3Path, + ]; + $s3Client->deleteObject($s3Options); + } + + /** + * @param string $fileS3Path string used as path in S3 + * @return void + * @throws \Exception + * @see /config/cors.xml + */ + public function deleteDir(string $fileS3Path): void + { + $s3Client = $this->getS3Client(); + if ($this->folderExists($fileS3Path)) { + $s3Client->deleteMatchingObjects(Configure::readOrFail('Uppy.S3.bucket'), $fileS3Path); + } else { + throw new Exception('File doesn\'t exist. Please try again.'); + } + } + + /** + * @param string $filename filename + * @return bool + */ + public function fileExists(string $filename): bool + { + $s3Client = $this->getS3Client(); + + return $s3Client->doesObjectExist(Configure::readOrFail('Uppy.S3.bucket'), $filename); + } + + /** + * @param string $filename filename + * @return bool + * @throws \Exception + */ + public function folderExists(string $filename): bool + { + $s3Client = $this->getS3Client(); + $list = $s3Client->listObjectsV2([ + 'Bucket' => Configure::readOrFail('Uppy.S3.bucket'), + 'Prefix' => $filename, + ]); + if ($list['Contents'] > 0) { + return true; + } + + throw new Exception('Folder doesn\'t exist. Please try again.'); + } +} From 52225686526913a7c47c8dfff1e432286df684fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Fri, 22 May 2026 13:25:37 +0100 Subject: [PATCH 03/10] phpcs --- config/uppy.php | 1 - src/Controller/FilesController.php | 7 ++--- src/Model/Table/FilesTable.php | 32 ++++++++++------------- src/Storage/AdapterFactory.php | 9 ++++--- src/Storage/GcsAdapter.php | 24 +++++++++++++++++ src/Storage/S3Adapter.php | 41 ++++++++++++++++++------------ 6 files changed, 72 insertions(+), 42 deletions(-) diff --git a/config/uppy.php b/config/uppy.php index 68d8a40..830b616 100644 --- a/config/uppy.php +++ b/config/uppy.php @@ -28,7 +28,6 @@ 'driver' => env('UPPY_DRIVER', 's3'), 'Props' => [ - 'usersAliasModel' => 'Users', 'usersModel' => 'Users', /* * When true and a file record is deleted, the object is also diff --git a/src/Controller/FilesController.php b/src/Controller/FilesController.php index eeaf3bd..d725764 100644 --- a/src/Controller/FilesController.php +++ b/src/Controller/FilesController.php @@ -172,8 +172,10 @@ public function delete(string|int|null $id = null): ?Response $this->getRequest()->allowMethod(['post', 'delete']); $file = $this->Files->get($id); if ($this->Files->delete($file)) { - $shouldDelete = Configure::read('Uppy.Props.deleteFileStorage', - Configure::read('Uppy.Props.deleteFileS3', true)); + $shouldDelete = Configure::read( + 'Uppy.Props.deleteFileStorage', + Configure::read('Uppy.Props.deleteFileS3', true), + ); if ($shouldDelete) { $this->storageAdapter->deleteObject($file->path); } @@ -230,7 +232,6 @@ public function sign(): ?Response public function add(): void { $this->getRequest()->allowMethod('get'); - $file = $this->Files->newEmptyEntity(); $this->set(compact('file')); diff --git a/src/Model/Table/FilesTable.php b/src/Model/Table/FilesTable.php index 4c2bb45..a4fe539 100644 --- a/src/Model/Table/FilesTable.php +++ b/src/Model/Table/FilesTable.php @@ -45,14 +45,6 @@ class FilesTable extends Table { private StorageAdapterInterface $storageAdapter; - private function getUsersAliasModel(): string - { - return (string)Configure::read( - 'Uppy.Props.usersAliasModel', - Configure::readOrFail('Uppy.Props.usersModel') - ); - } - /** * @return void */ @@ -81,7 +73,7 @@ public function initialize(array $config): void $this->addBehavior('Timestamp'); - $this->belongsTo($this->getUsersAliasModel(), [ + $this->belongsTo(Configure::readOrFail('Uppy.Props.usersAliasModel'), [ 'foreignKey' => 'user_id', 'className' => Configure::readOrFail('Uppy.Props.usersModel'), ]); @@ -170,9 +162,9 @@ public function buildRules(RulesChecker $rules): RulesChecker $rules->add( $rules->existsIn( 'user_id', - $this->getUsersAliasModel() + Configure::readOrFail('Uppy.Props.usersAliasModel'), ), - ['errorField' => 'user_id'] + ['errorField' => 'user_id'], ); return $rules; @@ -188,8 +180,10 @@ public function buildRules(RulesChecker $rules): RulesChecker */ public function afterDelete(EventInterface $event, File $entity, ArrayObject $options): void { - $shouldDelete = Configure::read('Uppy.Props.deleteFileStorage', - Configure::read('Uppy.Props.deleteFileS3', false)); + $shouldDelete = Configure::read( + 'Uppy.Props.deleteFileStorage', + Configure::read('Uppy.Props.deleteFileS3', false), + ); if ($shouldDelete) { $this->getStorageAdapter()->deleteObject($entity->path); } @@ -210,22 +204,22 @@ public function findDatatable( int|string $patient_id, array $q = [], ?string $from_date = null, - ?string $to_date = null + ?string $to_date = null, ): SelectQuery { if ($q['value'] ?? false) { - $query->where(fn (QueryExpression $exp): QueryExpression => $exp + $query->where(fn(QueryExpression $exp): QueryExpression => $exp ->like($this->aliasField('filename'), "%{$q['value']}%")); } - $query->where(fn (QueryExpression $exp): QueryExpression => $exp + $query->where(fn(QueryExpression $exp): QueryExpression => $exp ->eq($this->aliasField('user_id'), $patient_id)); if ($from_date && $to_date) { - $query->where(fn (QueryExpression $exp): QueryExpression => $exp->between( + $query->where(fn(QueryExpression $exp): QueryExpression => $exp->between( $this->aliasField('created'), DateTime::parse($from_date)->startOfDay(), DateTime::parse($to_date)->endOfDay(), - 'datetime' + 'datetime', )); } @@ -238,7 +232,7 @@ public function findDatatable( 'path', 'created', ]) - ->formatResults(fn (CollectionInterface $results): CollectionInterface => $results + ->formatResults(fn(CollectionInterface $results): CollectionInterface => $results ->map(function (File $file): array { $row = []; $row['filename'] = $file->filename; diff --git a/src/Storage/AdapterFactory.php b/src/Storage/AdapterFactory.php index 307a50d..0e4572b 100644 --- a/src/Storage/AdapterFactory.php +++ b/src/Storage/AdapterFactory.php @@ -17,14 +17,17 @@ class AdapterFactory { + /** + * @return \CakeDC\Uppy\Storage\StorageAdapterInterface + */ public static function create(): StorageAdapterInterface { $driver = Configure::read('Uppy.driver', 's3'); return match ($driver) { - 's3' => new S3Adapter(), - 'gcs' => new GcsAdapter(), - 'r2' => new R2Adapter(), + 's3' => new S3Adapter(), + 'gcs' => new GcsAdapter(), + 'r2' => new R2Adapter(), default => throw new InvalidArgumentException("Unknown Uppy driver: {$driver}"), }; } diff --git a/src/Storage/GcsAdapter.php b/src/Storage/GcsAdapter.php index 22e8942..6b15d76 100644 --- a/src/Storage/GcsAdapter.php +++ b/src/Storage/GcsAdapter.php @@ -22,10 +22,16 @@ class GcsAdapter implements StorageAdapterInterface { + /** + * @param \Google\Cloud\Storage\StorageClient|null $client + */ public function __construct(private ?StorageClient $client = null) { } + /** + * @return \Google\Cloud\Storage\StorageClient + */ private function getClient(): StorageClient { return $this->client ??= new StorageClient([ @@ -34,11 +40,20 @@ private function getClient(): StorageClient ]); } + /** + * @return string + */ private function bucket(): string { return (string)Configure::readOrFail('Uppy.GCS.bucket'); } + /** + * @param string $path + * @param string $contentType + * @return \Psr\Http\Message\RequestInterface + * @throws \Exception + */ public function createPresignedRequest(string $path, string $contentType): RequestInterface { $expires = new DateTime(Configure::readOrFail('Uppy.GCS.lifeTimePutObject')); @@ -54,6 +69,11 @@ public function createPresignedRequest(string $path, string $contentType): Reque return (new Request($signedUrl, 'PUT'))->withHeader('Content-Type', $contentType); } + /** + * @param string $path + * @param int $ttlSeconds + * @return string + */ public function presignedUrl(string $path, int $ttlSeconds = 3600): string { $expires = new DateTime("+{$ttlSeconds} seconds"); @@ -67,6 +87,10 @@ public function presignedUrl(string $path, int $ttlSeconds = 3600): string ]); } + /** + * @param string $path + * @return bool + */ public function deleteObject(string $path): bool { try { diff --git a/src/Storage/S3Adapter.php b/src/Storage/S3Adapter.php index bfb194a..0a540e3 100644 --- a/src/Storage/S3Adapter.php +++ b/src/Storage/S3Adapter.php @@ -20,31 +20,34 @@ class S3Adapter implements StorageAdapterInterface { + /** + * @param \Aws\S3\S3Client|null $client + */ public function __construct(private ?S3Client $client = null) { } + /** + * @return \Aws\S3\S3Client + */ private function getClient(): S3Client { return $this->client ??= new S3Client(Configure::readOrFail('Uppy.S3.config')); } + /** + * @return string + */ private function bucket(): string { return (string)Configure::readOrFail('Uppy.S3.bucket'); } - private function getLegacyAwareLifetime(string $operation): string - { - $newKey = "Uppy.S3.constants.{$operation}"; - $legacyKey = "Uppy.S3.contants.{$operation}"; - - return (string)( - Configure::read($newKey) - ?? Configure::readOrFail($legacyKey) - ); - } - + /** + * @param string $path + * @param string $contentType + * @return \Psr\Http\Message\RequestInterface + */ public function createPresignedRequest(string $path, string $contentType): RequestInterface { if (Configure::read('Uppy.S3.config.connection') === 'dummy') { @@ -60,10 +63,15 @@ public function createPresignedRequest(string $path, string $contentType): Reque return $this->getClient()->createPresignedRequest( $command, - $this->getLegacyAwareLifetime('lifeTimePutObject'), + Configure::readOrFail('Uppy.S3.constants.lifeTimePutObject'), ); } + /** + * @param string $path + * @param int $ttlSeconds + * @return string + */ public function presignedUrl(string $path, int $ttlSeconds = 3600): string { if (Configure::read('Uppy.S3.config.connection') === 'dummy') { @@ -74,14 +82,15 @@ public function presignedUrl(string $path, int $ttlSeconds = 3600): string 'Bucket' => $this->bucket(), 'Key' => $path, ]); - $expires = $ttlSeconds === 3600 - ? $this->getLegacyAwareLifetime('lifeTimeGetObject') - : "+{$ttlSeconds} seconds"; - $request = $this->getClient()->createPresignedRequest($cmd, $expires); + $request = $this->getClient()->createPresignedRequest($cmd, "+{$ttlSeconds} seconds"); return (string)$request->getUri(); } + /** + * @param string $path + * @return bool + */ public function deleteObject(string $path): bool { if (Configure::read('Uppy.S3.config.connection') === 'dummy') { From 842a611e622d8d452366e209fac646b7ac1ec8aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Fri, 22 May 2026 20:46:08 +0100 Subject: [PATCH 04/10] Update documentation --- CHANGELOG.md | 7 ++ Docs/Documentation/Configure.md | 145 ++++++++++++++++++++++---------- Docs/Home.md | 2 +- README.md | 5 +- 4 files changed, 111 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab866e3..2a7732d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ Changelog Releases for CakePHP 5.0 ------------------------ +* 2.1.0 + * Add pluggable storage drivers via `StorageAdapterInterface` and `AdapterFactory` + * Add Google Cloud Storage (`gcs`) adapter (requires `google/cloud-storage`) + * Add Cloudflare R2 (`r2`) adapter + * New config key `Uppy.driver` (env `UPPY_DRIVER`) selects the active backend + * Rename `Uppy.Props.deleteFileS3` to `deleteFileStorage`; the old key is still honored for backwards compatibility + * 2.0.3 * Update documentation diff --git a/Docs/Documentation/Configure.md b/Docs/Documentation/Configure.md index 1c4e1b2..ee8e8ba 100644 --- a/Docs/Documentation/Configure.md +++ b/Docs/Documentation/Configure.md @@ -6,7 +6,7 @@ To configure the plugin first copy the base configuration to your project $> cp vendor/cakedc/cakephp-uppy/config/uppy.php config/uppy.php ``` -Then run migration to create table *uppy_files* where save data for files uploaded +Then run migration to create table *uppy_files* where data for uploaded files is stored ``` $> bin/cake migrations migrate -p CakeDC/Uppy @@ -14,80 +14,135 @@ $> bin/cake migrations migrate -p CakeDC/Uppy Note: you can change the name of this table in the configuration file *config/uppy.php* +## Storage drivers + +The plugin supports three storage backends, selected via `Uppy.driver`: + +| Driver | Backend | Required env vars | Extra packages | +|---------|--------------------------|----------------------------------------------------------------|--------------------------------------| +| `s3` | Amazon S3 | `S3_REGION`, `S3_KEY`, `S3_SECRET`, `S3_BUCKET` | none (uses `aws/aws-sdk-php`) | +| `gcs` | Google Cloud Storage | `GCS_PROJECT_ID`, `GCS_KEY_FILE_PATH`, `GCS_BUCKET` | `composer require google/cloud-storage:^1.50` | +| `r2` | Cloudflare R2 | `R2_ACCOUNT_ID`, `R2_KEY`, `R2_SECRET`, `R2_BUCKET`, `R2_PUBLIC_DOMAIN`, `R2_ENDPOINT` | none (R2 is S3-compatible) | + +Set the driver via the `UPPY_DRIVER` env var (`s3` | `gcs` | `r2`), or override `Uppy.driver` directly in `config/uppy.php`. Default is `s3`. + +All drivers implement `CakeDC\Uppy\Storage\StorageAdapterInterface` and are instantiated by `CakeDC\Uppy\Storage\AdapterFactory::create()`. To add a custom driver, implement the interface and register a new case in the factory. + ## Configuration file *config/uppy.php* -By default, when debug is set to true the plugin will add a number of routes to your application `/uppy/files` in order to -upload and view the uploaded files. You should protect these endpoints in case your application requires -authentication to upload or manage files. Failing to do so would allow an authenticated user to *upload* files -to your application. +By default, when debug is set to true the plugin will add a number of routes to your application under `/uppy/files` for uploading and viewing files. You should protect these endpoints if your application requires authentication to upload or manage files. Failing to do so would allow any visitor to *upload* files to your application. -### Default uppy config file: +### Default uppy config file ```php [ + // Storage driver: 's3' | 'gcs' | 'r2' + 'driver' => env('UPPY_DRIVER', 's3'), + 'Props' => [ 'usersModel' => 'Users', - 'deleteFileS3' => true, + 'deleteFileStorage' => true, 'tableFiles' => 'uppy_files', ], + 'AcceptedContentTypes' => [ 'application/pdf', 'image/png', + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/vnd.ms-excel', + 'application/vnd.ms-powerpoint', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', ], + 'AcceptedExtensions' => [ - 'pdf', - 'png', + 'pdf', 'png', 'doc', 'docx', 'xls', 'ppt', 'pptx', ], - /* - * S3 configuration to manage files - */ + + // Amazon S3 — used when driver = 's3' 'S3' => [ - 'contants' => [ + 'constants' => [ 'lifeTimeGetObject' => '+20 minutes', 'lifeTimePutObject' => '+5 minutes', ], 'config' => [ 'version' => 'latest', - 'region' => filter_var(env('S3_REGION', null)), - 'endpoint' => filter_var(env('S3_END_POINT', null)), + 'region' => env('S3_REGION', null), 'credentials' => [ - 'key' => filter_var(env('S3_KEY', null)), - 'secret' => filter_var(env('S3_SECRET', null)), + 'key' => env('S3_KEY', null), + 'secret' => env('S3_SECRET', null), ], ], - 'bucket' => filter_var(env('S3_BUCKET')), + 'bucket' => env('S3_BUCKET', null), + ], + + // Google Cloud Storage — used when driver = 'gcs' + // Requires: composer require google/cloud-storage ^1.50 + 'GCS' => [ + 'projectId' => env('GCS_PROJECT_ID', null), + 'keyFilePath' => env('GCS_KEY_FILE_PATH', null), + 'bucket' => env('GCS_BUCKET', null), + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + ], + + // Cloudflare R2 — used when driver = 'r2' + // R2 is S3-compatible; uses the AWS SDK with a custom endpoint. + 'R2' => [ + 'bucket' => env('R2_BUCKET', null), + 'publicDomain' => env('R2_PUBLIC_DOMAIN', null), + 'constants' => [ + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + ], + 'config' => [ + 'version' => env('R2_VERSION', 'latest'), + 'region' => env('R2_REGION', 'auto'), + 'endpoint' => env('R2_ENDPOINT', null), + 'credentials' => [ + 'key' => env('R2_KEY', null), + 'secret' => env('R2_SECRET', null), + ], + 'use_path_style_endpoint' => true, + ], ], ], ]; ``` -- usersModel = is the alias name used in you app -- deleteFileS3 = if the record of the file in the database is deleted and it's marked true, the deletion is launched in the S3 deposit -- tableFiles = name of table used to store file data, default is `uppy_files` -- AcceptedContentTypes = list of content-type stored in S3 and saved in database -- AcceptedExtensions = list of file extensions stored in S3 and saved in database -- lifeTimeGetObject = life time generated link to access file in S3 -- lifeTimePutObject = life time generated link to post file in S3 -- region = configured region S3 -- endpoint = endpoint server to PUT/POST/GET S3 files -- key = S3 account key -- secret = S3 account secret -- bucket = bucket name - -Enpoints -------- - -- /uppy/files/sign = sign with credentials and return signed url to upload file in S3 directly in front -- /uppy/files/save = save register just uploaded in database with correct S3 path -- /uppy/files/delete = delete register in database, if Uppy.Props.deleteFileS3 is true remove from S3 -- /uppy/files/view = sign with credentials and return signed url to access file in S3 directly in front - -Sample -------- - -- /uppy/files = list of files in database and link to view/delete in S3 -- /uppy/files/add = example uppy upload file to configured S3 and save data relationed in database -- /uppy/files/drag = example uppy drag and upload multiple file, using Dashboard to configured S3 and save data relationed in database +### Props + +- `usersModel` — alias name used in your app for the users association +- `deleteFileStorage` — when `true`, deleting a file record also removes the object from the active storage backend. (Renamed from `deleteFileS3`; the old key still works as a fallback for backwards compatibility.) +- `tableFiles` — name of the table used to store file metadata, default `uppy_files` + +### Accepted types + +- `AcceptedContentTypes` — MIME types accepted for upload and persisted in the database +- `AcceptedExtensions` — file extensions accepted for upload and persisted in the database + +### Per-driver options + +- **S3 / R2** — `constants.lifeTimePutObject` / `constants.lifeTimeGetObject` control the signed URL lifetime for upload and read URLs respectively. `config` is passed directly to `Aws\S3\S3Client`. +- **GCS** — `lifeTimePutObject` / `lifeTimeGetObject` at the top level of the `GCS` block; `keyFilePath` is the path to a service-account JSON key file. +- **R2** — `publicDomain` is your custom domain or `pub-.r2.dev` URL; `endpoint` is the R2 S3-compatible endpoint (`https://.r2.cloudflarestorage.com`). + +In test environments, set `Uppy.S3.config.connection` or `Uppy.R2.config.connection` to `'dummy'` to bypass real network calls. + +## Endpoints + +- `/uppy/files/sign` — returns a signed URL for uploading a file directly from the browser to the configured storage +- `/uppy/files/save` — persists the database record for a file just uploaded, with the correct storage path +- `/uppy/files/delete` — deletes the database record and, when `Uppy.Props.deleteFileStorage` is `true`, also removes the object from storage +- `/uppy/files/view` — returns a signed URL for reading the file from the configured storage + +## Sample pages (debug only) + +These routes are only registered when `debug` is `true`: + +- `/uppy/files` — list of files in the database with view/delete links +- `/uppy/files/add` — example single-file upload to the configured storage +- `/uppy/files/drag` — example multi-file drag-and-drop upload using Uppy Dashboard diff --git a/Docs/Home.md b/Docs/Home.md index d4ae13a..fcd03d7 100644 --- a/Docs/Home.md +++ b/Docs/Home.md @@ -1,6 +1,6 @@ Home ==== -The **Uppy** Plugin integrate https://github.com/transloadit/uppy to upload files directly to a configured S3 usign a signature, and in the callback response save data related to files uploaded in database. +The **Uppy** Plugin integrates https://github.com/transloadit/uppy to upload files directly from the browser to a configured cloud storage backend using a presigned URL, and on callback persists the related file metadata in the database. Supported backends: Amazon S3, Google Cloud Storage, and Cloudflare R2. The plugin is thought as a base to extend and use your app specific controllers and views from. diff --git a/README.md b/README.md index 1d4e84f..c73b84e 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,9 @@ CakeDC Uppy Plugin The **Uppy** plugin covers the following features: -* Upload directly files to configured S3 from frontside using a signature -* Save on configured table path to uploaded files on S3, mime_type, date, metadata and relation to user and specified related model in database indicated +* Upload files directly from the browser to a configured cloud storage backend using a presigned URL +* Pluggable storage drivers: **Amazon S3**, **Google Cloud Storage**, and **Cloudflare R2** (selectable via `Uppy.driver`) +* Persist file path, mime type, date, metadata and the relation to the user (or other related model) in the `uppy_files` table Requirements ------------ From 0e9ccaba82fffc990d67bf111b29d874d9149309 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Tue, 26 May 2026 10:56:53 +0100 Subject: [PATCH 05/10] Fix Tests and minor issues --- src/Controller/FilesController.php | 7 ------- src/Model/Table/FilesTable.php | 2 +- src/Storage/GcsAdapter.php | 9 ++++++--- src/Storage/R2Adapter.php | 22 +++++++++++++++++----- src/Storage/S3Adapter.php | 12 ++++++++---- src/Storage/StorageAdapterInterface.php | 4 ++-- tests/TestCase/Storage/R2AdapterTest.php | 17 ++++++++++++----- 7 files changed, 46 insertions(+), 27 deletions(-) diff --git a/src/Controller/FilesController.php b/src/Controller/FilesController.php index d725764..41266b3 100644 --- a/src/Controller/FilesController.php +++ b/src/Controller/FilesController.php @@ -172,13 +172,6 @@ public function delete(string|int|null $id = null): ?Response $this->getRequest()->allowMethod(['post', 'delete']); $file = $this->Files->get($id); if ($this->Files->delete($file)) { - $shouldDelete = Configure::read( - 'Uppy.Props.deleteFileStorage', - Configure::read('Uppy.Props.deleteFileS3', true), - ); - if ($shouldDelete) { - $this->storageAdapter->deleteObject($file->path); - } $this->Flash->success(__('The file has been deleted.')); } else { $this->Flash->error(__('The file could not be deleted. Please, try again.')); diff --git a/src/Model/Table/FilesTable.php b/src/Model/Table/FilesTable.php index a4fe539..37de3d3 100644 --- a/src/Model/Table/FilesTable.php +++ b/src/Model/Table/FilesTable.php @@ -46,7 +46,7 @@ class FilesTable extends Table private StorageAdapterInterface $storageAdapter; /** - * @return void + * @return \CakeDC\Uppy\Storage\StorageAdapterInterface */ public function getStorageAdapter(): StorageAdapterInterface { diff --git a/src/Storage/GcsAdapter.php b/src/Storage/GcsAdapter.php index 6b15d76..72b6298 100644 --- a/src/Storage/GcsAdapter.php +++ b/src/Storage/GcsAdapter.php @@ -71,12 +71,15 @@ public function createPresignedRequest(string $path, string $contentType): Reque /** * @param string $path - * @param int $ttlSeconds + * @param int|null $ttlSeconds * @return string */ - public function presignedUrl(string $path, int $ttlSeconds = 3600): string + public function presignedUrl(string $path, ?int $ttlSeconds = null): string { - $expires = new DateTime("+{$ttlSeconds} seconds"); + $ttlString = $ttlSeconds !== null + ? "+{$ttlSeconds} seconds" + : Configure::read('Uppy.GCS.lifeTimeGetObject', '+1 hour'); + $expires = new DateTime($ttlString); return (string)$this->getClient() ->bucket($this->bucket()) diff --git a/src/Storage/R2Adapter.php b/src/Storage/R2Adapter.php index 0812361..f80b75c 100644 --- a/src/Storage/R2Adapter.php +++ b/src/Storage/R2Adapter.php @@ -32,7 +32,7 @@ public function __construct(private ?S3Client $client = null) */ private function getClient(): S3Client { - return $this->client ??= new S3Client(Configure::read('Uppy.R2.config')); + return $this->client ??= new S3Client(Configure::readOrFail('Uppy.R2.config')); } /** @@ -50,6 +50,10 @@ private function bucket(): string */ public function createPresignedRequest(string $path, string $contentType): RequestInterface { + if (Configure::read('Uppy.R2.config.connection') === 'dummy') { + return (new Request())->withUri(new Uri('https://example.com')); + } + $client = $this->getClient(); $command = $client->getCommand('PutObject', [ @@ -66,19 +70,27 @@ public function createPresignedRequest(string $path, string $contentType): Reque /** * @param string $path - * @param int $ttlSeconds + * @param int|null $ttlSeconds * @return string */ - public function presignedUrl(string $path, int $ttlSeconds = 3600): string + public function presignedUrl(string $path, ?int $ttlSeconds = null): string { + if (Configure::read('Uppy.R2.config.connection') === 'dummy') { + return 'https://example.com'; + } + $client = $this->getClient(); + $ttl = $ttlSeconds !== null + ? "+{$ttlSeconds} seconds" + : Configure::read('Uppy.R2.constants.lifeTimeGetObject', '+1 hour'); + $cmd = $client->getCommand('GetObject', [ 'Bucket' => $this->bucket(), 'Key' => $path, ]); - $request = $client->createPresignedRequest($cmd, "+{$ttlSeconds} seconds"); + $request = $client->createPresignedRequest($cmd, $ttl); return (string)$request->getUri(); } @@ -89,7 +101,7 @@ public function presignedUrl(string $path, int $ttlSeconds = 3600): string */ public function deleteObject(string $path): bool { - if (Configure::read('Uppy.R2.connection') === 'dummy') { + if (Configure::read('Uppy.R2.config.connection') === 'dummy') { return true; } diff --git a/src/Storage/S3Adapter.php b/src/Storage/S3Adapter.php index 0a540e3..24b5550 100644 --- a/src/Storage/S3Adapter.php +++ b/src/Storage/S3Adapter.php @@ -54,7 +54,7 @@ public function createPresignedRequest(string $path, string $contentType): Reque return (new Request())->withUri(new Uri('https://example.com')); } - $command = $this->getClient()->getCommand('putObject', [ + $command = $this->getClient()->getCommand('PutObject', [ 'Bucket' => $this->bucket(), 'Key' => $path, 'ContentType' => $contentType, @@ -69,20 +69,24 @@ public function createPresignedRequest(string $path, string $contentType): Reque /** * @param string $path - * @param int $ttlSeconds + * @param int|null $ttlSeconds * @return string */ - public function presignedUrl(string $path, int $ttlSeconds = 3600): string + public function presignedUrl(string $path, ?int $ttlSeconds = null): string { if (Configure::read('Uppy.S3.config.connection') === 'dummy') { return 'https://example.com'; } + $ttl = $ttlSeconds !== null + ? "+{$ttlSeconds} seconds" + : Configure::read('Uppy.S3.constants.lifeTimeGetObject', '+1 hour'); + $cmd = $this->getClient()->getCommand('GetObject', [ 'Bucket' => $this->bucket(), 'Key' => $path, ]); - $request = $this->getClient()->createPresignedRequest($cmd, "+{$ttlSeconds} seconds"); + $request = $this->getClient()->createPresignedRequest($cmd, $ttl); return (string)$request->getUri(); } diff --git a/src/Storage/StorageAdapterInterface.php b/src/Storage/StorageAdapterInterface.php index b370f06..831f523 100644 --- a/src/Storage/StorageAdapterInterface.php +++ b/src/Storage/StorageAdapterInterface.php @@ -29,10 +29,10 @@ public function createPresignedRequest(string $path, string $contentType): Reque * Generate a presigned GET URL for reading a stored object. * * @param string $path Object storage path - * @param int $ttlSeconds URL lifetime in seconds (default 3600) + * @param int|null $ttlSeconds URL lifetime in seconds; null falls back to the driver's lifeTimeGetObject config * @return string Signed URL */ - public function presignedUrl(string $path, int $ttlSeconds = 3600): string; + public function presignedUrl(string $path, ?int $ttlSeconds = null): string; /** * Delete an object from storage. diff --git a/tests/TestCase/Storage/R2AdapterTest.php b/tests/TestCase/Storage/R2AdapterTest.php index d29da3b..9231408 100644 --- a/tests/TestCase/Storage/R2AdapterTest.php +++ b/tests/TestCase/Storage/R2AdapterTest.php @@ -15,13 +15,20 @@ protected function setUp(): void { parent::setUp(); Configure::write('Uppy.R2', [ - 'accountId' => 'test-account-id', - 'credentials' => ['key' => 'fake', 'secret' => 'fake'], 'bucket' => 'test-bucket', 'publicDomain' => 'files.example.com', - 'lifeTimePutObject' => '+5 minutes', - 'lifeTimeGetObject' => '+20 minutes', - 'connection' => 'dummy', + 'constants' => [ + 'lifeTimePutObject' => '+5 minutes', + 'lifeTimeGetObject' => '+20 minutes', + ], + 'config' => [ + 'version' => 'latest', + 'region' => 'auto', + 'endpoint' => 'https://test.r2.cloudflarestorage.com', + 'credentials' => ['key' => 'fake', 'secret' => 'fake'], + 'connection' => 'dummy', + 'use_path_style_endpoint' => true, + ], ]); } From 86b682692c5021df2220a0ccca37e3be8378de16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Tue, 26 May 2026 15:31:05 +0100 Subject: [PATCH 06/10] Fix tests, phpcs and phpstan --- composer.json | 15 +++++++++------ phpcs.xml | 2 +- src/Controller/FilesController.php | 4 +++- src/Model/Table/FilesTable.php | 4 ++-- src/UppyPlugin.php | 4 ++++ src/Util/S3Trait.php | 7 +++++++ tests/TestCase/Storage/AdapterFactoryTest.php | 4 ++-- tests/TestCase/Storage/GcsAdapterTest.php | 2 +- tests/TestCase/Storage/R2AdapterTest.php | 3 +-- tests/TestCase/Storage/S3AdapterTest.php | 3 +-- 10 files changed, 31 insertions(+), 17 deletions(-) diff --git a/composer.json b/composer.json index 546dd86..3b2c239 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,10 @@ "cakephp/cakephp-codesniffer": "^5.0", "phpunit/phpunit": "^10.1.0", "cakephp/migrations": "^4.0.0", - "markstory/asset_compress": "^5.0.0" + "markstory/asset_compress": "^5.0.0", + "google/cloud-storage": "^1.50", + "phpstan/phpstan": "^1.10", + "vimeo/psalm": "^5.15" }, "suggest": { "google/cloud-storage": "Required to use the GCS storage adapter (^1.50)" @@ -43,15 +46,15 @@ ], "cs-check": "phpcs --colors --parallel=16 -p src/ tests/", "cs-fix": "phpcbf --colors --parallel=16 -p src/ tests/", - "phpstan": "tools/phpstan analyse", - "psalm": "tools/psalm --show-info=false", + "phpstan": "vendor/bin/phpstan analyse", + "psalm": "vendor/bin/psalm --show-info=false", "stan": [ "@phpstan", "@psalm" ], - "phpstan-tests": "tools/phpstan analyze -c tests/phpstan.neon", - "phpstan-baseline": "tools/phpstan --generate-baseline", - "psalm-baseline": "tools/psalm --set-baseline=psalm-baseline.xml", + "phpstan-tests": "vendor/bin/phpstan analyze -c tests/phpstan.neon", + "phpstan-baseline": "vendor/bin/phpstan --generate-baseline", + "psalm-baseline": "vendor/bin/psalm --set-baseline=psalm-baseline.xml", "stan-setup": "phive install", "test": "phpunit" }, diff --git a/phpcs.xml b/phpcs.xml index 015430f..61734da 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,6 +1,6 @@ - + diff --git a/src/Controller/FilesController.php b/src/Controller/FilesController.php index 41266b3..981e371 100644 --- a/src/Controller/FilesController.php +++ b/src/Controller/FilesController.php @@ -21,6 +21,8 @@ use Cake\Utility\Text; use CakeDC\Uppy\Storage\AdapterFactory; use CakeDC\Uppy\Storage\StorageAdapterInterface; +use UnexpectedValueException; +use function Cake\Core\h; use function Cake\I18n\__; /** @@ -67,7 +69,7 @@ public function view(string|int|null $id = null): ?Response /** @var \CakeDC\Uppy\Model\Entity\File $file */ $file = $this->Files->get($id); - $presignedUrl = $this->storageAdapter->presignedUrl($file->path); + $presignedUrl = $this->storageAdapter->presignedUrl($file->path ?? ''); return $this->redirect($presignedUrl); } diff --git a/src/Model/Table/FilesTable.php b/src/Model/Table/FilesTable.php index 37de3d3..03c41ff 100644 --- a/src/Model/Table/FilesTable.php +++ b/src/Model/Table/FilesTable.php @@ -185,7 +185,7 @@ public function afterDelete(EventInterface $event, File $entity, ArrayObject $op Configure::read('Uppy.Props.deleteFileS3', false), ); if ($shouldDelete) { - $this->getStorageAdapter()->deleteObject($entity->path); + $this->getStorageAdapter()->deleteObject($entity->path ?? ''); } } @@ -237,7 +237,7 @@ public function findDatatable( $row = []; $row['filename'] = $file->filename; $row['extension'] = $file->extension; - $row['signedUrl'] = $this->getStorageAdapter()->presignedUrl($file->path); + $row['signedUrl'] = $this->getStorageAdapter()->presignedUrl($file->path ?? ''); $row['filesize'] = Number::toReadableSize($file->filesize ?? 0); $row['created'] = $file->created?->i18nFormat('yyyy-MM-dd'); $row['id'] = $file->id; diff --git a/src/UppyPlugin.php b/src/UppyPlugin.php index 1f5ff5a..cd75b82 100644 --- a/src/UppyPlugin.php +++ b/src/UppyPlugin.php @@ -21,6 +21,10 @@ */ class UppyPlugin extends BasePlugin { + /** + * @param \Cake\Core\PluginApplicationInterface $app Application instance. + * @return void + */ public function bootstrap(PluginApplicationInterface $app): void { parent::bootstrap($app); diff --git a/src/Util/S3Trait.php b/src/Util/S3Trait.php index 882cc03..52a88f5 100644 --- a/src/Util/S3Trait.php +++ b/src/Util/S3Trait.php @@ -27,11 +27,18 @@ */ trait S3Trait { + /** + * @return \Aws\S3\S3Client + */ protected function getS3Client(): S3Client { return new S3Client(Configure::readOrFail('Uppy.S3.config')); } + /** + * @param string $operation Operation name (lifeTimePutObject or lifeTimeGetObject). + * @return string + */ protected function getS3Lifetime(string $operation): string { $newKey = "Uppy.S3.constants.{$operation}"; diff --git a/tests/TestCase/Storage/AdapterFactoryTest.php b/tests/TestCase/Storage/AdapterFactoryTest.php index 58795ae..725c27c 100644 --- a/tests/TestCase/Storage/AdapterFactoryTest.php +++ b/tests/TestCase/Storage/AdapterFactoryTest.php @@ -3,12 +3,12 @@ namespace CakeDC\Uppy\Test\TestCase\Storage; +use Cake\Core\Configure; +use Cake\TestSuite\TestCase; use CakeDC\Uppy\Storage\AdapterFactory; use CakeDC\Uppy\Storage\GcsAdapter; use CakeDC\Uppy\Storage\R2Adapter; use CakeDC\Uppy\Storage\S3Adapter; -use Cake\Core\Configure; -use Cake\TestSuite\TestCase; use InvalidArgumentException; class AdapterFactoryTest extends TestCase diff --git a/tests/TestCase/Storage/GcsAdapterTest.php b/tests/TestCase/Storage/GcsAdapterTest.php index 6b68544..c7c1bfe 100644 --- a/tests/TestCase/Storage/GcsAdapterTest.php +++ b/tests/TestCase/Storage/GcsAdapterTest.php @@ -3,9 +3,9 @@ namespace CakeDC\Uppy\Test\TestCase\Storage; -use CakeDC\Uppy\Storage\GcsAdapter; use Cake\Core\Configure; use Cake\TestSuite\TestCase; +use CakeDC\Uppy\Storage\GcsAdapter; use DateTime; use Google\Cloud\Core\Exception\GoogleException; use Google\Cloud\Core\Exception\NotFoundException; diff --git a/tests/TestCase/Storage/R2AdapterTest.php b/tests/TestCase/Storage/R2AdapterTest.php index 9231408..1af5449 100644 --- a/tests/TestCase/Storage/R2AdapterTest.php +++ b/tests/TestCase/Storage/R2AdapterTest.php @@ -3,10 +3,9 @@ namespace CakeDC\Uppy\Test\TestCase\Storage; -use Aws\S3\S3Client; -use CakeDC\Uppy\Storage\R2Adapter; use Cake\Core\Configure; use Cake\TestSuite\TestCase; +use CakeDC\Uppy\Storage\R2Adapter; use Psr\Http\Message\RequestInterface; class R2AdapterTest extends TestCase diff --git a/tests/TestCase/Storage/S3AdapterTest.php b/tests/TestCase/Storage/S3AdapterTest.php index 449de46..b373888 100644 --- a/tests/TestCase/Storage/S3AdapterTest.php +++ b/tests/TestCase/Storage/S3AdapterTest.php @@ -3,10 +3,9 @@ namespace CakeDC\Uppy\Test\TestCase\Storage; -use Aws\S3\S3Client; -use CakeDC\Uppy\Storage\S3Adapter; use Cake\Core\Configure; use Cake\TestSuite\TestCase; +use CakeDC\Uppy\Storage\S3Adapter; use Psr\Http\Message\RequestInterface; class S3AdapterTest extends TestCase From 0563e0b1e46b5fa582ef14e9797e2bc1546ddb6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Tue, 26 May 2026 17:38:44 +0100 Subject: [PATCH 07/10] Update composer.json --- composer.json | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 3b2c239..9832fb7 100644 --- a/composer.json +++ b/composer.json @@ -22,8 +22,7 @@ "cakephp/migrations": "^4.0.0", "markstory/asset_compress": "^5.0.0", "google/cloud-storage": "^1.50", - "phpstan/phpstan": "^1.10", - "vimeo/psalm": "^5.15" + "phpstan/phpstan": "^1.10" }, "suggest": { "google/cloud-storage": "Required to use the GCS storage adapter (^1.50)" @@ -47,14 +46,14 @@ "cs-check": "phpcs --colors --parallel=16 -p src/ tests/", "cs-fix": "phpcbf --colors --parallel=16 -p src/ tests/", "phpstan": "vendor/bin/phpstan analyse", - "psalm": "vendor/bin/psalm --show-info=false", + "psalm": "tools/psalm --show-info=false", "stan": [ "@phpstan", "@psalm" ], "phpstan-tests": "vendor/bin/phpstan analyze -c tests/phpstan.neon", "phpstan-baseline": "vendor/bin/phpstan --generate-baseline", - "psalm-baseline": "vendor/bin/psalm --set-baseline=psalm-baseline.xml", + "psalm-baseline": "tools/psalm --set-baseline=psalm-baseline.xml", "stan-setup": "phive install", "test": "phpunit" }, From f858ceee7cc576448bb9413350974f77a5c030d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Wed, 27 May 2026 12:55:03 +0100 Subject: [PATCH 08/10] phpcs --- config/uppy.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/config/uppy.php b/config/uppy.php index 830b616..7d935b8 100644 --- a/config/uppy.php +++ b/config/uppy.php @@ -2,7 +2,6 @@ declare(strict_types=1); /** - ** * Copyright 2023, Cake Development Corporation (https://www.cakedc.com) * * Licensed under The MIT License @@ -71,7 +70,7 @@ 'version' => 'latest', 'region' => env('S3_REGION', null), 'credentials' => [ - 'key' => env('S3_KEY', null), + 'key' => env('S3_KEY', null), 'secret' => env('S3_SECRET', null), ], ], @@ -83,9 +82,9 @@ * Requires: composer require google/cloud-storage ^1.50 */ 'GCS' => [ - 'projectId' => env('GCS_PROJECT_ID', null), + 'projectId' => env('GCS_PROJECT_ID', null), 'keyFilePath' => env('GCS_KEY_FILE_PATH', null), - 'bucket' => env('GCS_BUCKET', null), + 'bucket' => env('GCS_BUCKET', null), 'lifeTimePutObject' => '+5 minutes', 'lifeTimeGetObject' => '+20 minutes', ], From e07a7cde9fd58bd5dc40d83330c6acb409579693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Thu, 28 May 2026 13:56:12 +0100 Subject: [PATCH 09/10] Fix cs-stan / Coding Standard & Static Analysis step in Github workflow --- .phive/phars.xml | 4 ++-- phive.xml | 5 +++++ phpcs.xml | 2 ++ 3 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 phive.xml diff --git a/.phive/phars.xml b/.phive/phars.xml index 17093fd..7ef9317 100644 --- a/.phive/phars.xml +++ b/.phive/phars.xml @@ -1,5 +1,5 @@ - - + + diff --git a/phive.xml b/phive.xml new file mode 100644 index 0000000..7ef9317 --- /dev/null +++ b/phive.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/phpcs.xml b/phpcs.xml index 61734da..b29774e 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -3,4 +3,6 @@ + src + tests From 2ab0ab70cf8f2e50628cb4df41002d20f3228d38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florencio=20Hern=C3=A1ndez?= Date: Thu, 28 May 2026 17:39:15 +0100 Subject: [PATCH 10/10] Fix psalm issues --- config/aliases.php | 4 ++++ phpstan-baseline.neon | 8 +++++++ phpstan.neon | 7 ++++-- psalm.xml | 4 ++++ src/Controller/FilesController.php | 36 ++++++++++++++++-------------- src/Model/Table/FilesTable.php | 10 ++++----- src/Storage/GcsAdapter.php | 2 +- 7 files changed, 46 insertions(+), 25 deletions(-) diff --git a/config/aliases.php b/config/aliases.php index 3b3e913..3cf0946 100644 --- a/config/aliases.php +++ b/config/aliases.php @@ -13,5 +13,9 @@ use Cake\Controller\Controller; use Cake\View\View; +if (!defined('CONFIG')) { + define('CONFIG', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR); +} + class_alias(Controller::class, 'App\Controller\AppController'); class_alias(View::class, '\App\View\AppView'); diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 364905f..0fd0e7b 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1,2 +1,10 @@ parameters: ignoreErrors: + - + message: '#^Negated boolean expression is always false\.$#' + path: src/Storage/S3Adapter.php + count: 1 + - + message: '#^Negated boolean expression is always false\.$#' + path: src/Storage/R2Adapter.php + count: 1 diff --git a/phpstan.neon b/phpstan.neon index 0411426..dc64bec 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -2,8 +2,11 @@ includes: - phpstan-baseline.neon parameters: level: 8 - checkMissingIterableValueType: false - checkGenericClassInNonGenericObjectType: false + ignoreErrors: + - + identifier: missingType.iterableValue + - + identifier: missingType.generics bootstrapFiles: - config/aliases.php paths: diff --git a/psalm.xml b/psalm.xml index b525688..6a8bebf 100644 --- a/psalm.xml +++ b/psalm.xml @@ -30,5 +30,9 @@ + + + + diff --git a/src/Controller/FilesController.php b/src/Controller/FilesController.php index 981e371..189e7d9 100644 --- a/src/Controller/FilesController.php +++ b/src/Controller/FilesController.php @@ -91,8 +91,8 @@ public function save(): void $files = []; $result = []; foreach ($items as $item) { - $tableAlias = $item['model'] ?? null; - if (!$tableAlias) { + $tableAlias = isset($item['model']) ? (string)$item['model'] : ''; + if ($tableAlias === '') { $result['error'] = true; $result['message'] = __('model is required'); $this->set('result', $result); @@ -110,8 +110,8 @@ public function save(): void return; } - $foreignKey = $item['foreign_key'] ?? null; - if (!$foreignKey) { + $foreignKey = isset($item['foreign_key']) ? (string)$item['foreign_key'] : ''; + if ($foreignKey === '') { $result['error'] = true; $result['message'] = __('foreign key is required'); $this->set('result', $result); @@ -140,7 +140,7 @@ public function save(): void $files[] = $file; } - if ($this->Files->saveMany($files)) { + if ($this->Files->saveMany($files) !== false) { $result['error'] = false; $result['message'] = __('The association has been be saved correctly'); } else { @@ -205,20 +205,22 @@ public function sign(): ?Response $presignedRequest = $this->storageAdapter->createPresignedRequest($filename, $contentType); + $encoded = json_encode([ + 'error' => false, + 'code' => 200, + 'method' => $presignedRequest->getMethod(), + 'url' => (string)$presignedRequest->getUri(), + 'fields' => [], + // Also set the content-type header on the request, to make sure that it is the same as the one we used to generate the signature. + // Else, the browser picks a content-type as it sees fit. + 'headers' => [ + 'content-type' => $contentType, + ], + ]); + return $this->getResponse() ->withHeader('content-type', 'application/json') - ->withStringBody(json_encode([ - 'error' => false, - 'code' => 200, - 'method' => $presignedRequest->getMethod(), - 'url' => (string)$presignedRequest->getUri(), - 'fields' => [], - // Also set the content-type header on the request, to make sure that it is the same as the one we used to generate the signature. - // Else, the browser picks a content-type as it sees fit. - 'headers' => [ - 'content-type' => $contentType, - ], - ]) ?: ''); + ->withStringBody($encoded !== false ? $encoded : ''); } /** diff --git a/src/Model/Table/FilesTable.php b/src/Model/Table/FilesTable.php index 03c41ff..d4aaf27 100644 --- a/src/Model/Table/FilesTable.php +++ b/src/Model/Table/FilesTable.php @@ -34,7 +34,7 @@ * @method \CakeDC\Uppy\Model\Entity\File newEmptyEntity() * @method \CakeDC\Uppy\Model\Entity\File newEntity(array $data, array $options = []) * @method \CakeDC\Uppy\Model\Entity\File[] newEntities(array $data, array $options = []) - * @method \CakeDC\Uppy\Model\Entity\File findOrCreate($search, ?callable $callback = null, $options = []) + * @method \CakeDC\Uppy\Model\Entity\File findOrCreate(array|callable $search, ?callable $callback = null, array $options = []) * @method \CakeDC\Uppy\Model\Entity\File patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = []) * @method \CakeDC\Uppy\Model\Entity\File[] patchEntities(iterable $entities, array $data, array $options = []) * @method \CakeDC\Uppy\Model\Entity\File|false save(\Cake\Datasource\EntityInterface $entity, $options = []) @@ -43,14 +43,14 @@ */ class FilesTable extends Table { - private StorageAdapterInterface $storageAdapter; + private ?StorageAdapterInterface $storageAdapter = null; /** * @return \CakeDC\Uppy\Storage\StorageAdapterInterface */ public function getStorageAdapter(): StorageAdapterInterface { - if (!isset($this->storageAdapter)) { + if ($this->storageAdapter === null) { $this->storageAdapter = AdapterFactory::create(); } @@ -206,7 +206,7 @@ public function findDatatable( ?string $from_date = null, ?string $to_date = null, ): SelectQuery { - if ($q['value'] ?? false) { + if (isset($q['value']) && (string)$q['value'] !== '') { $query->where(fn(QueryExpression $exp): QueryExpression => $exp ->like($this->aliasField('filename'), "%{$q['value']}%")); } @@ -214,7 +214,7 @@ public function findDatatable( $query->where(fn(QueryExpression $exp): QueryExpression => $exp ->eq($this->aliasField('user_id'), $patient_id)); - if ($from_date && $to_date) { + if ($from_date !== null && $to_date !== null) { $query->where(fn(QueryExpression $exp): QueryExpression => $exp->between( $this->aliasField('created'), DateTime::parse($from_date)->startOfDay(), diff --git a/src/Storage/GcsAdapter.php b/src/Storage/GcsAdapter.php index 72b6298..ea66dc7 100644 --- a/src/Storage/GcsAdapter.php +++ b/src/Storage/GcsAdapter.php @@ -81,7 +81,7 @@ public function presignedUrl(string $path, ?int $ttlSeconds = null): string : Configure::read('Uppy.GCS.lifeTimeGetObject', '+1 hour'); $expires = new DateTime($ttlString); - return (string)$this->getClient() + return $this->getClient() ->bucket($this->bucket()) ->object($path) ->signedUrl($expires, [