From 594def5adbe91d7646d2330b3f11d229b1595874 Mon Sep 17 00:00:00 2001 From: Evert Harmeling Date: Mon, 5 Feb 2024 12:59:17 +0100 Subject: [PATCH] Allow Symfony 7 (#436) * 1. Implemented the AsCommand attributes for final $defaultName 2. Removed support for PHP <8.0 3. Reworked the __construct methods to be on-par with php >=8.0 4. Removed all rferences to GetMasterRequest - using only getMainRequest now 5. Fixed custom_uploader.md documentation to use getMainRequest * Changed the ci.yml fot gihub actions * Ran php cs fixer for code style Reran testes, all passes * Updated php_cs_fixer to v4 Changed the config file to work with the new version Ran php_cs_fixer on codebase Tests still pass * Updated php_stan and config file * Updated php unit-brdge to v6.0.* * Add tyope hint var comment/Annotation to the $helper class * Fixe some more phpstan issues with regards to type hints and retur types * Some mroe php cs fixer changes * Removed unused sensio/framework-extra-bundle + updated symfony/phpunit-bridge version constraint * Allow Symfony 7 * Updated CI to test SF 6.2 - 7.0 * Fixes phpstan errors * Refactored phpstan fixes * Fix CI for prefer lowest run * Drop support for symfony/* ^4.4 * Fix CI for Yaml incompatibility --------- Co-authored-by: Johan Kasselman --- .github/workflows/ci.yml | 147 ++++++++++-------- .php_cs.dist => .php-cs-fixer.dist.php | 14 +- composer.json | 31 ++-- doc/custom_uploader.md | 10 +- phpstan.neon | 33 +++- src/Command/ClearChunkCommand.php | 6 +- src/Command/ClearOrphansCommand.php | 4 + src/Controller/AbstractChunkedController.php | 6 +- src/Controller/AbstractController.php | 75 +++------ src/Controller/BlueimpController.php | 9 +- src/Controller/DropzoneController.php | 9 +- src/Controller/MooUploadController.php | 4 +- src/DependencyInjection/Configuration.php | 4 +- .../OneupUploaderExtension.php | 34 ++-- src/Event/PostChunkUploadEvent.php | 46 +----- src/Event/PostPersistEvent.php | 35 +---- src/Event/PostUploadEvent.php | 35 +---- src/Event/PreUploadEvent.php | 35 +---- src/Event/ValidationEvent.php | 35 +---- src/Routing/RouteLoader.php | 21 +-- src/Templating/Helper/UploaderHelper.php | 21 +-- src/Twig/Extension/UploaderExtension.php | 13 +- src/Uploader/Chunk/ChunkManager.php | 20 +-- src/Uploader/Chunk/ChunkManagerInterface.php | 18 +-- .../Chunk/Storage/ChunkStorageInterface.php | 19 +-- .../Chunk/Storage/FilesystemStorage.php | 8 +- .../Chunk/Storage/FlysystemStorage.php | 37 +---- .../Chunk/Storage/GaufretteStorage.php | 20 +-- .../ErrorHandler/BlueimpErrorHandler.php | 11 +- .../ErrorHandler/DropzoneErrorHandler.php | 3 +- .../ErrorHandler/ErrorHandlerInterface.php | 3 +- .../ErrorHandler/NoopErrorHandler.php | 3 +- .../ErrorHandler/PluploadErrorHandler.php | 3 +- src/Uploader/File/FileInterface.php | 9 +- src/Uploader/File/FilesystemFile.php | 2 +- src/Uploader/File/FlysystemFile.php | 14 +- src/Uploader/File/GaufretteFile.php | 13 +- src/Uploader/Orphanage/OrphanageManager.php | 14 +- src/Uploader/Response/AbstractResponse.php | 26 +--- .../Response/FineUploaderResponse.php | 17 +- src/Uploader/Response/MooUploadResponse.php | 55 ++----- .../Storage/FilesystemOrphanageStorage.php | 36 +---- src/Uploader/Storage/FilesystemStorage.php | 8 +- .../Storage/FlysystemOrphanageStorage.php | 27 +--- src/Uploader/Storage/FlysystemStorage.php | 24 +-- .../Storage/GaufretteOrphanageStorage.php | 27 +--- src/Uploader/Storage/GaufretteStorage.php | 10 +- tests/App/Kernel.php | 2 - tests/App/config/config.yml | 2 - tests/Controller/AbstractUploadTest.php | 5 +- tests/Controller/AbstractValidationTest.php | 31 ++-- tests/Controller/BlueimpTest.php | 2 + tests/Controller/BlueimpValidationTest.php | 44 +++--- tests/Controller/DropzoneValidationTest.php | 8 +- .../Controller/FancyUploadValidationTest.php | 8 +- tests/Controller/FileBagExtractorTest.php | 5 +- .../Controller/FineUploaderValidationTest.php | 8 +- tests/Controller/PluploadValidationTest.php | 8 +- tests/Controller/UploadifyValidationTest.php | 8 +- .../OneupUploaderExtensionTest.php | 4 +- tests/Templating/TemplateHelperTest.php | 2 + .../Chunk/Storage/FlysystemStorageTest.php | 1 + tests/Uploader/File/FilesystemFileTest.php | 2 +- tests/Uploader/File/GaufretteFileTest.php | 2 +- tests/Uploader/Naming/UrlSafeNamerTest.php | 2 +- .../Storage/FlysystemOrphanageStorageTest.php | 2 +- .../Storage/GaufretteAmazonS3StorageTest.php | 6 +- .../Storage/GaufretteOrphanageStorageTest.php | 4 +- tests/bootstrap.php | 14 +- 69 files changed, 365 insertions(+), 859 deletions(-) rename .php_cs.dist => .php-cs-fixer.dist.php (84%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b04960fa..c78c8b71 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,80 +1,93 @@ name: CI on: - pull_request: ~ - push: - branches: - - master - tags: - - '*' + pull_request: ~ + push: + branches: + - master + tags: + - '*' jobs: - coding-style: - name: Coding Style - runs-on: ubuntu-latest - steps: - - name: Setup PHP - uses: shivammathur/setup-php@2.9.0 - with: - php-version: 7.4 - extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo, zlib - coverage: none + coding-style: + name: Coding Style + runs-on: ubuntu-latest + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.0 + extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo, zlib + coverage: none - - name: Checkout - uses: actions/checkout@v2 + - name: Checkout + uses: actions/checkout@v3 - - name: Install the dependencies - run: composer install --no-interaction --no-suggest - - name: Check the coding style - run: vendor/bin/php-cs-fixer fix --diff --dry-run - - name: Analyze the code - run: vendor/bin/phpstan analyze src/ tests/ --level=max + - name: Install the dependencies + run: composer install --no-interaction - tests: - name: PHP ${{ matrix.php }} / SF ^${{ matrix.symfony }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - php: [7.4, 8.0] - symfony: [4.4, 5.4, 6.0] - exclude: - # Symfony 6.0 does not supports php <8.0 - - php: 7.4 - symfony: 6.0 - steps: - - name: Setup PHP - uses: shivammathur/setup-php@2.9.0 - with: - php-version: ${{ matrix.php }} - extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib - coverage: none + - name: Check the coding style + run: vendor/bin/php-cs-fixer fix --diff --dry-run - - name: Checkout - uses: actions/checkout@v2 + - name: Analyze the code + run: vendor/bin/phpstan analyze - - name: Install the dependencies - run: | - composer require symfony/framework-bundle:^${{ matrix.symfony }} symfony/http-foundation:^${{ matrix.symfony }} - composer install --no-interaction --no-suggest - - name: Run the unit tests - run: vendor/bin/phpunit --colors=always + tests: + name: PHP ${{ matrix.php }} / SF ^${{ matrix.symfony }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: [8.0, 8.1, 8.2] + symfony: [5.4, 6.0, 6.1, 6.2, 6.3, 6.4, 7.0] + exclude: + - php: 8.0 + symfony: 6.1 + - php: 8.0 + symfony: 6.2 + - php: 8.0 + symfony: 6.3 + - php: 8.0 + symfony: 6.4 + - php: 8.0 + symfony: 7.0 + - php: 8.1 + symfony: 7.0 + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib + coverage: none - prefer-lowest: - name: Prefer Lowest - runs-on: ubuntu-latest - steps: - - name: Setup PHP - uses: shivammathur/setup-php@2.7.0 - with: - php-version: 7.4 - extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib - coverage: none + - name: Checkout + uses: actions/checkout@v3 - - name: Checkout - uses: actions/checkout@v2 + - name: Install the dependencies + run: | + composer require symfony/framework-bundle:^${{ matrix.symfony }} symfony/http-foundation:^${{ matrix.symfony }} symfony/yaml:^${{ matrix.symfony }} + composer install --no-interaction --no-suggest - - name: Install the dependencies - run: composer update --prefer-lowest --prefer-stable --no-interaction --no-suggest - - name: Run the unit tests - run: vendor/bin/phpunit --colors=always + - name: Run the unit tests + run: vendor/bin/phpunit --colors=always + + prefer-lowest: + name: Prefer Lowest + runs-on: ubuntu-latest + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.0 + extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib + coverage: none + + - name: Checkout + uses: actions/checkout@v3 + + - name: Install the dependencies + run: composer update --prefer-lowest --prefer-stable --no-interaction + + - name: Run the unit tests + run: vendor/bin/phpunit --colors=always diff --git a/.php_cs.dist b/.php-cs-fixer.dist.php similarity index 84% rename from .php_cs.dist rename to .php-cs-fixer.dist.php index 428e683f..9b9b5f77 100644 --- a/.php_cs.dist +++ b/.php-cs-fixer.dist.php @@ -1,17 +1,19 @@ in([__DIR__ . '/src', __DIR__ . '/tests']) ->exclude(['App/cache', 'App/var']) ; -return PhpCsFixer\Config::create() +$config = new Config(); +return $config ->setRules([ '@DoctrineAnnotation' => true, '@Symfony' => true, '@Symfony:risky' => true, - '@PHP71Migration' => true, - '@PHP71Migration:risky' => true, + '@PHP80Migration' => true, + '@PHP80Migration:risky' => true, '@PHPUnit60Migration:risky' => true, '@PHPUnit75Migration:risky' => true, 'align_multiline_comment' => true, @@ -21,11 +23,7 @@ ], 'combine_consecutive_issets' => true, 'combine_consecutive_unsets' => true, - 'general_phpdoc_annotation_remove' => [ - 'author', - 'expectedException', - 'expectedExceptionMessage', - ], + 'general_phpdoc_annotation_remove' => true, 'heredoc_to_nowdoc' => true, 'linebreak_after_opening_tag' => true, 'list_syntax' => ['syntax' => 'short'], diff --git a/composer.json b/composer.json index f170b073..89249510 100644 --- a/composer.json +++ b/composer.json @@ -32,33 +32,32 @@ } ], "require": { - "php": "^7.4 || ^8.0", - "symfony/asset": "^4.4 || ^5.4 || ^6.0", + "php": "^8.0", + "symfony/asset": "^5.4 || ^6.0 || ^7.0", "symfony/event-dispatcher-contracts": "^1.0 || ^2.0 || ^3.0", - "symfony/finder": "^4.4 || ^5.4 || ^6.0", - "symfony/framework-bundle": "^4.4 || ^5.4 || ^6.0", - "symfony/mime": "^4.4 || ^5.4 || ^6.0", - "symfony/templating": "^4.4 || ^5.4 || ^6.0", - "symfony/translation": "^4.4 || ^5.4 || ^6.0", + "symfony/finder": "^5.4 || ^6.0 || ^7.0", + "symfony/framework-bundle": "^5.4 || ^6.0 || ^7.0", + "symfony/mime": "^5.4 || ^6.0 || ^7.0", + "symfony/templating": "^5.4 || ^6.0 || ^7.0", + "symfony/translation": "^5.4 || ^6.0 || ^7.0", "symfony/translation-contracts": "^1.0 || ^2.0 || ^3.0", - "symfony/yaml": "^4.4 || ^5.4 || ^6.0", + "symfony/yaml": "^5.4 || ^6.0 || ^7.0", "twig/twig": "^2.4 || ^3.0" }, "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", "doctrine/common": "^2.12 || ^3.0", "doctrine/doctrine-bundle": "^2.4", - "friendsofphp/php-cs-fixer": "^2.16", + "friendsofphp/php-cs-fixer": "^3.40", "knplabs/gaufrette": "^0.9", + "m2mtech/flysystem-stream-wrapper": "^1.0", "oneup/flysystem-bundle": "^4.1", - "phpstan/phpstan": "^0.12.10", + "phpstan/phpstan": "^1.8", "phpunit/phpunit": "^9.5", - "sensio/framework-extra-bundle": "^5.0 || ^6.0", - "m2mtech/flysystem-stream-wrapper": "^1.0", - "symfony/browser-kit": "^4.4 || ^5.4 || ^6.0", - "symfony/phpunit-bridge": "^5.4", - "symfony/security-bundle": "^4.4 || ^5.4 || ^6.0", - "symfony/var-dumper": "^4.4 || ^5.4 || ^6.0", + "symfony/browser-kit": "^5.4 || ^6.0 || ^7.0", + "symfony/phpunit-bridge": "^6.0.17 || ^7.0", + "symfony/security-bundle": "^5.4 || ^6.0 || ^7.0", + "symfony/var-dumper": "^5.4 || ^6.0 || ^7.0", "twistor/flysystem-stream-wrapper": "^1.0" }, "suggest": { diff --git a/doc/custom_uploader.md b/doc/custom_uploader.md index 5e267f58..93a3a16f 100644 --- a/doc/custom_uploader.md +++ b/doc/custom_uploader.md @@ -33,14 +33,18 @@ namespace Acme\DemoBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\JsonResponse; use Oneup\UploaderBundle\Controller\UploaderController; -use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse;use Symfony\Component\HttpFoundation\RequestStack; class CustomUploader extends UploaderController { + + public function __construct(protected RequestStack $requestStack) { + } + public function upload() { // get some basic stuff together - $request = $this->container->get('request_stack')->getMasterRequest(); + $request = $this->requestStack->getMainRequest(); $response = new EmptyResponse(); // get file from request (your own logic) @@ -100,7 +104,7 @@ class FineUploaderResponse extends AbstractResponse public function assemble() { // explicitly overwrite success and error key - // as these keys are used internaly by the + // as these keys are used internally by the // frontend uploader $data = $this->data; $data['success'] = $this->success; diff --git a/phpstan.neon b/phpstan.neon index b9453756..db97df9c 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,21 +1,44 @@ parameters: - bootstrapFiles: - - %rootDir%/../../../vendor/autoload.php - - excludes_analyse: + level: 9 + paths: + - src + - tests + excludePaths: - src/DependencyInjection/Configuration.php - tests/App/cache - tests/App/logs - tests/App/var - var - vendor - checkGenericClassInNonGenericObjectType: false checkMissingIterableValueType: false reportUnmatchedIgnoredErrors: false ignoreErrors: + - '#Cannot cast mixed to int\.#' + - '#Cannot call method addListener\(\) on mixed\.#' + - '#Cannot call method getSize\(\) on mixed\.#' + - '#Cannot call method maxSize\(\) on mixed\.#' + - '#Cannot call method getPathname\(\) on mixed\.#' + - '#Cannot call method getPath\(\) on mixed\.#' + - '#Cannot call method getRealPath\(\) on mixed\.#' + - '#Cannot call method getBasename\(\) on mixed\.#' - '#Method Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface::dispatch\(\) invoked with 2 parameters, 1 required\.#' + - + message: '#Cannot use array destructuring on array\|false\.#' + path: '%currentWorkingDirectory%/src/Controller/BlueimpController.php' + - + message: '#Binary operation "/" between string and int results in an error\.#' + path: '%currentWorkingDirectory%/src/Controller/BlueimpController.php' + - + message: '#Dead catch - Gaufrette\\Exception\\FileNotFound is never thrown in the try block\.#' + path: '%currentWorkingDirectory%/src/Uploader/Chunk/Storage/GaufretteStorage.php' + - + message: '#Parameter \#1 \$finfo of function finfo_file|finfo_close expects finfo, resource given\.#' + path: '%currentWorkingDirectory%/src/Uploader/File/GaufretteFile.php' + - + message: '#Parameter \#2 ...\$values of function sprintf expects bool\|float\|int\|string\|null, mixed given\.#' + path: '%currentWorkingDirectory%/src/Controller/PluploadController.php' - message: '#Parameter \#1 \$parameters of class Symfony\\Component\\HttpFoundation\\FileBag constructor expects array, array given\.#' path: '%currentWorkingDirectory%/tests/Controller/FileBagExtractorTest.php' diff --git a/src/Command/ClearChunkCommand.php b/src/Command/ClearChunkCommand.php index 4385071e..eda3ee69 100644 --- a/src/Command/ClearChunkCommand.php +++ b/src/Command/ClearChunkCommand.php @@ -5,14 +5,16 @@ namespace Oneup\UploaderBundle\Command; use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +#[AsCommand( + name: 'oneup:uploader:clear-chunks' +)] class ClearChunkCommand extends Command { - protected static $defaultName = 'oneup:uploader:clear-chunks'; // Make command lazy load - /** * @var ChunkManager */ diff --git a/src/Command/ClearOrphansCommand.php b/src/Command/ClearOrphansCommand.php index 80b78141..717c59fc 100644 --- a/src/Command/ClearOrphansCommand.php +++ b/src/Command/ClearOrphansCommand.php @@ -5,10 +5,14 @@ namespace Oneup\UploaderBundle\Command; use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +#[AsCommand( + name: 'oneup:uploader:clear-orphans' +)] class ClearOrphansCommand extends Command { protected static $defaultName = 'oneup:uploader:clear-orphans'; diff --git a/src/Controller/AbstractChunkedController.php b/src/Controller/AbstractChunkedController.php index 20234f67..c1699154 100644 --- a/src/Controller/AbstractChunkedController.php +++ b/src/Controller/AbstractChunkedController.php @@ -7,6 +7,7 @@ use Oneup\UploaderBundle\Event\PostChunkUploadEvent; use Oneup\UploaderBundle\Uploader\Chunk\ChunkManagerInterface; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; @@ -70,7 +71,10 @@ protected function handleChunkedUpload(UploadedFile $file, ResponseInterface $re // with reassembling the parts if ($last) { $path = $assembled->getPath(); - $this->handleUpload($assembled, $response, $request); + if ($assembled instanceof File) { + $this->handleUpload($assembled, $response, $request); + } + // @todo $assembled is of type mixed, so would error without check $chunkManager->cleanup($path); } diff --git a/src/Controller/AbstractController.php b/src/Controller/AbstractController.php index 8d77b507..76ba0424 100644 --- a/src/Controller/AbstractController.php +++ b/src/Controller/AbstractController.php @@ -15,6 +15,7 @@ use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\FileBag; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; @@ -24,38 +25,8 @@ abstract class AbstractController { - /** - * @var ErrorHandlerInterface - */ - protected $errorHandler; - - /** - * @var ContainerInterface - */ - protected $container; - - /** - * @var StorageInterface - */ - protected $storage; - - /** - * @var array - */ - protected $config; - - /** - * @var string - */ - protected $type; - - public function __construct(ContainerInterface $container, StorageInterface $storage, ErrorHandlerInterface $errorHandler, array $config, string $type) + public function __construct(protected ContainerInterface $container, protected StorageInterface $storage, protected ErrorHandlerInterface $errorHandler, protected array $config, protected string $type) { - $this->errorHandler = $errorHandler; - $this->container = $container; - $this->storage = $storage; - $this->config = $config; - $this->type = $type; } abstract public function upload(): JsonResponse; @@ -66,12 +37,13 @@ public function progress(): JsonResponse $session = $request->getSession(); - $prefix = (string) ini_get('session.upload_progress.prefix'); - $name = (string) ini_get('session.upload_progress.name'); - + $prefix = (string) \ini_get('session.upload_progress.prefix'); + $name = (string) \ini_get('session.upload_progress.name'); + /** @var string $value */ + $value = $request->get($name); // assemble session key // ref: http://php.net/manual/en/session.upload-progress.php - $key = sprintf('%s.%s', $prefix, $request->get($name)); + $key = sprintf('%s.%s', $prefix, $value); $value = $session->get($key); return new JsonResponse($value); @@ -83,11 +55,13 @@ public function cancel(): JsonResponse $session = $request->getSession(); - $prefix = (string) ini_get('session.upload_progress.prefix'); - $name = (string) ini_get('session.upload_progress.name'); - - $key = sprintf('%s.%s', $prefix, $request->get($name)); + $prefix = (string) \ini_get('session.upload_progress.prefix'); + $name = (string) \ini_get('session.upload_progress.name'); + /** @var string $value */ + $value = $request->get($name); + $key = sprintf('%s.%s', $prefix, $value); + /** @var array $progress */ $progress = $session->get($key); $progress['cancel_upload'] = false; @@ -127,9 +101,9 @@ protected function getFiles(FileBag $bag): array * * Note: The return value differs when * - * @param mixed $file The file to upload + * @param File $file The file to upload */ - protected function handleUpload($file, ResponseInterface $response, Request $request): void + protected function handleUpload(File $file, ResponseInterface $response, Request $request): void { // wrap the file if it is not done yet which can only happen // if it wasn't a chunked upload, in which case it is definitely @@ -148,6 +122,7 @@ protected function handleUpload($file, ResponseInterface $response, Request $req $name = $namer->name($file); // perform the real upload + /** @var File $uploaded */ $uploaded = $this->storage->upload($file, $name); $this->dispatchPostEvents($uploaded, $response, $request); @@ -156,9 +131,9 @@ protected function handleUpload($file, ResponseInterface $response, Request $req /** * This function is a helper function which dispatches pre upload event. * - * @param FileInterface $uploaded the uploaded file - * @param ResponseInterface $response a response object - * @param Request $request the request object + * @param FileInterface $uploaded the uploaded file + * @param ResponseInterface $response a response object + * @param Request $request the request object */ protected function dispatchPreUploadEvent(FileInterface $uploaded, ResponseInterface $response, Request $request): void { @@ -172,9 +147,9 @@ protected function dispatchPreUploadEvent(FileInterface $uploaded, ResponseInter * This function is a helper function which dispatches post upload * and post persist events. * - * @param mixed $uploaded the uploaded file + * @param File $uploaded the uploaded file */ - protected function dispatchPostEvents($uploaded, ResponseInterface $response, Request $request): void + protected function dispatchPostEvents(File $uploaded, ResponseInterface $response, Request $request): void { // dispatch post upload event (both the specific and the general) $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config); @@ -201,10 +176,8 @@ protected function validate(FileInterface $file, Request $request, ResponseInter * * On top of that, if the client does not support the application/json type, * then the content type of the response will be set to text/plain instead. - * - * @param mixed $data */ - protected function createSupportedJsonResponse($data, int $statusCode = 200): JsonResponse + protected function createSupportedJsonResponse(mixed $data, int $statusCode = 200): JsonResponse { $request = $this->getRequest(); $response = new JsonResponse($data, $statusCode); @@ -223,9 +196,7 @@ protected function getRequest(): Request $requestStack = $this->container->get('request_stack'); /** @var Request $request */ - $request = method_exists($requestStack, 'getMainRequest') - ? $requestStack->getMainRequest() - : $requestStack->getMasterRequest(); + $request = $requestStack->getMainRequest(); return $request; } diff --git a/src/Controller/BlueimpController.php b/src/Controller/BlueimpController.php index aa1c7783..d2cf2d97 100644 --- a/src/Controller/BlueimpController.php +++ b/src/Controller/BlueimpController.php @@ -39,11 +39,14 @@ public function progress(): JsonResponse $session = $request->getSession(); - $prefix = (string) ini_get('session.upload_progress.prefix'); - $name = (string) ini_get('session.upload_progress.name'); + $prefix = (string) \ini_get('session.upload_progress.prefix'); + $name = (string) \ini_get('session.upload_progress.name'); + /** @var string $value */ + $value = $request->get($name); // ref: https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress - $key = sprintf('%s.%s', $prefix, $request->get($name)); + $key = sprintf('%s.%s', $prefix, $value); + /** @var array $value */ $value = $session->get($key); $progress = [ diff --git a/src/Controller/DropzoneController.php b/src/Controller/DropzoneController.php index 3b642f81..ccc5fd62 100644 --- a/src/Controller/DropzoneController.php +++ b/src/Controller/DropzoneController.php @@ -29,7 +29,7 @@ public function upload(): JsonResponse $this->handleUpload($file, $response, $request) ; } catch (UploadException $e) { - $statusCode = 500; //Dropzone displays error if HTTP response is 40x or 50x + $statusCode = 500; // Dropzone displays error if HTTP response is 40x or 50x $this->errorHandler->addException($response, $e); /** @var TranslatorInterface $translator */ @@ -53,10 +53,11 @@ protected function parseChunkedRequest(Request $request): array $uuid = $request->get('dzuuid'); /** - * @var UploadedFile + * @var UploadedFile $file */ - $file = $request->files->get('file')->getClientOriginalName(); - $orig = $file; + $file = $request->files->get('file'); + $fileName = $file->getClientOriginalName(); + $orig = $fileName; return [$last, $uuid, $index, $orig]; } diff --git a/src/Controller/MooUploadController.php b/src/Controller/MooUploadController.php index 59abc918..176729db 100644 --- a/src/Controller/MooUploadController.php +++ b/src/Controller/MooUploadController.php @@ -74,7 +74,9 @@ protected function parseChunkedRequest(Request $request): array try { // loop through every file that has been uploaded before - foreach ($chunkManager->getChunks((string) $uuid) as $file) { + /** @var iterable $chunks */ + $chunks = $chunkManager->getChunks((string) $uuid); + foreach ($chunks as $file) { $size += $file->getSize(); } } catch (\InvalidArgumentException $e) { diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index ae0ac4ac..e8fff458 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -106,9 +106,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->prototype('scalar') ->beforeNormalization() ->ifString() - ->then(function ($v) { - return strtolower($v); - }) + ->then(fn ($v) => strtolower($v)) ->end() ->end() ->end() diff --git a/src/DependencyInjection/OneupUploaderExtension.php b/src/DependencyInjection/OneupUploaderExtension.php index 56195e54..af237477 100644 --- a/src/DependencyInjection/OneupUploaderExtension.php +++ b/src/DependencyInjection/OneupUploaderExtension.php @@ -108,12 +108,12 @@ protected function createController(string $key, array $config): string } else { $customFrontend = $config['custom_frontend']; - $controllerName = sprintf('oneup_uploader.controller.%s', $customFrontend['name']); - $controllerType = $customFrontend['class']; - - if (empty($controllerName) || empty($controllerType)) { + if (empty($customFrontend['name']) || empty($customFrontend['class'])) { throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); } + + $controllerName = sprintf('oneup_uploader.controller.%s', $customFrontend['name']); + $controllerType = $customFrontend['class']; } $errorHandler = $this->createErrorHandler($config); @@ -271,7 +271,7 @@ protected function registerFilesystem(string $type, string $key, string $class, break; } - if (\strlen($filesystem) <= 0) { + if ('' === $filesystem) { throw new ServiceNotFoundException('Empty service name'); } @@ -285,14 +285,11 @@ protected function registerFilesystem(string $type, string $key, string $class, ->addArgument($prefix); } - /** - * @param mixed $input - */ - protected function getMaxUploadSize($input): int + protected function getMaxUploadSize(mixed $input): int { $input = $this->getValueInBytes($input); - $maxPost = $this->getValueInBytes(ini_get('upload_max_filesize')); - $maxFile = $this->getValueInBytes(ini_get('post_max_size')); + $maxPost = $this->getValueInBytes(\ini_get('upload_max_filesize')); + $maxFile = $this->getValueInBytes(\ini_get('post_max_size')); if ($input < 0) { return min($maxPost, $maxFile); @@ -301,24 +298,25 @@ protected function getMaxUploadSize($input): int return min(min($input, $maxPost), $maxFile); } - /** - * @param mixed $input - */ - protected function getValueInBytes($input): int + protected function getValueInBytes(mixed $input): int { // see: http://www.php.net/manual/en/function.ini-get.php + if (!\is_scalar($input)) { + return -1; + } + $input = trim((string) $input); $last = strtolower($input[\strlen($input) - 1]); $numericInput = (float) substr($input, 0, -1); switch ($last) { case 'g': $numericInput *= 1024; - // no break + // no break case 'm': $numericInput *= 1024; - // no break + // no break case 'k': $numericInput *= 1024; - return (int) $numericInput; + return (int) $numericInput; } return (int) $input; diff --git a/src/Event/PostChunkUploadEvent.php b/src/Event/PostChunkUploadEvent.php index 83f9292f..fe2014e9 100644 --- a/src/Event/PostChunkUploadEvent.php +++ b/src/Event/PostChunkUploadEvent.php @@ -13,53 +13,11 @@ class PostChunkUploadEvent extends Event { public const NAME = UploadEvents::POST_CHUNK_UPLOAD; - /** - * @var mixed - */ - protected $chunk; - - /** - * @var Request - */ - protected $request; - - /** - * @var string - */ - protected $type; - - /** - * @var ResponseInterface - */ - protected $response; - - /** - * @var array - */ - protected $config; - - /** - * @var bool - */ - protected $isLast; - - /** - * @param mixed $chunk - */ - public function __construct($chunk, ResponseInterface $response, Request $request, bool $isLast, string $type, array $config) + public function __construct(protected mixed $chunk, protected ResponseInterface $response, protected Request $request, protected bool $isLast, protected string $type, protected array $config) { - $this->chunk = $chunk; - $this->request = $request; - $this->response = $response; - $this->isLast = $isLast; - $this->type = $type; - $this->config = $config; } - /** - * @return mixed - */ - public function getChunk() + public function getChunk(): mixed { return $this->chunk; } diff --git a/src/Event/PostPersistEvent.php b/src/Event/PostPersistEvent.php index d5db86c6..5cc6b60b 100644 --- a/src/Event/PostPersistEvent.php +++ b/src/Event/PostPersistEvent.php @@ -15,41 +15,8 @@ class PostPersistEvent extends Event { public const NAME = UploadEvents::POST_PERSIST; - /** - * @var FileInterface|File - */ - protected $file; - - /** - * @var Request - */ - protected $request; - - /** - * @var string - */ - protected $type; - - /** - * @var ResponseInterface - */ - protected $response; - - /** - * @var array - */ - protected $config; - - /** - * @param FileInterface|File $file - */ - public function __construct($file, ResponseInterface $response, Request $request, string $type, array $config) + public function __construct(protected FileInterface|File $file, protected ResponseInterface $response, protected Request $request, protected string $type, protected array $config) { - $this->file = $file; - $this->request = $request; - $this->response = $response; - $this->type = $type; - $this->config = $config; } /** diff --git a/src/Event/PostUploadEvent.php b/src/Event/PostUploadEvent.php index 31495474..f1b575c7 100644 --- a/src/Event/PostUploadEvent.php +++ b/src/Event/PostUploadEvent.php @@ -15,41 +15,8 @@ class PostUploadEvent extends Event { public const NAME = UploadEvents::POST_UPLOAD; - /** - * @var FileInterface|File - */ - protected $file; - - /** - * @var Request - */ - protected $request; - - /** - * @var string - */ - protected $type; - - /** - * @var ResponseInterface - */ - protected $response; - - /** - * @var array - */ - protected $config; - - /** - * @param FileInterface|File $file - */ - public function __construct($file, ResponseInterface $response, Request $request, string $type, array $config) + public function __construct(protected FileInterface|File $file, protected ResponseInterface $response, protected Request $request, protected string $type, protected array $config) { - $this->file = $file; - $this->request = $request; - $this->response = $response; - $this->type = $type; - $this->config = $config; } /** diff --git a/src/Event/PreUploadEvent.php b/src/Event/PreUploadEvent.php index 9398907f..158be01a 100644 --- a/src/Event/PreUploadEvent.php +++ b/src/Event/PreUploadEvent.php @@ -15,41 +15,8 @@ class PreUploadEvent extends Event { public const NAME = UploadEvents::PRE_UPLOAD; - /** - * @var FileInterface|File - */ - protected $file; - - /** - * @var Request - */ - protected $request; - - /** - * @var string - */ - protected $type; - - /** - * @var ResponseInterface - */ - protected $response; - - /** - * @var array - */ - protected $config; - - /** - * @param FileInterface|File $file - */ - public function __construct($file, ResponseInterface $response, Request $request, string $type, array $config) + public function __construct(protected File|FileInterface $file, protected ResponseInterface $response, protected Request $request, protected string $type, protected array $config) { - $this->file = $file; - $this->request = $request; - $this->response = $response; - $this->type = $type; - $this->config = $config; } /** diff --git a/src/Event/ValidationEvent.php b/src/Event/ValidationEvent.php index 1481b00a..d41a05b1 100644 --- a/src/Event/ValidationEvent.php +++ b/src/Event/ValidationEvent.php @@ -15,41 +15,8 @@ class ValidationEvent extends Event { public const NAME = UploadEvents::VALIDATION; - /** - * @var FileInterface|File - */ - protected $file; - - /** - * @var array - */ - protected $config; - - /** - * @var string - */ - protected $type; - - /** - * @var Request - */ - protected $request; - - /** - * @var ResponseInterface|null - */ - protected $response; - - /** - * @param FileInterface|File $file - */ - public function __construct($file, Request $request, array $config, string $type, ResponseInterface $response = null) + public function __construct(protected FileInterface|File $file, protected Request $request, protected array $config, protected string $type, protected ?ResponseInterface $response = null) { - $this->file = $file; - $this->config = $config; - $this->type = $type; - $this->request = $request; - $this->response = $response; } /** diff --git a/src/Routing/RouteLoader.php b/src/Routing/RouteLoader.php index 0f388439..39279c08 100644 --- a/src/Routing/RouteLoader.php +++ b/src/Routing/RouteLoader.php @@ -10,30 +10,17 @@ class RouteLoader extends Loader { - /** - * @var array - */ - protected $controllers; - - public function __construct(array $controllers) + public function __construct(protected array $controllers) { - $this->controllers = $controllers; + parent::__construct(); } - /** - * @param mixed $resource - * @param string|null $type - */ - public function supports($resource, $type = null): bool + public function supports(mixed $resource, string $type = null): bool { return 'uploader' === $type; } - /** - * @param mixed $resource - * @param string|null $type - */ - public function load($resource, $type = null): RouteCollection + public function load(mixed $resource, string $type = null): RouteCollection { $routes = new RouteCollection(); $separator = '::'; diff --git a/src/Templating/Helper/UploaderHelper.php b/src/Templating/Helper/UploaderHelper.php index 6fb06644..70e89ae9 100644 --- a/src/Templating/Helper/UploaderHelper.php +++ b/src/Templating/Helper/UploaderHelper.php @@ -9,20 +9,8 @@ class UploaderHelper extends Helper { - /** - * @var RouterInterface - */ - protected $router; - - /** - * @var array - */ - protected $maxsize; - - public function __construct(RouterInterface $router, array $maxsize) + public function __construct(protected RouterInterface $router, protected array $maxsize) { - $this->router = $router; - $this->maxsize = $maxsize; } public function getName(): string @@ -47,13 +35,10 @@ public function cancel(string $key): string public function uploadKey(): string { - return (string) ini_get('session.upload_progress.name'); + return (string) \ini_get('session.upload_progress.name'); } - /** - * @return mixed - */ - public function maxSize(string $key) + public function maxSize(string $key): int { if (!\array_key_exists($key, $this->maxsize)) { throw new \InvalidArgumentException('No such mapping found to get maxsize for.'); diff --git a/src/Twig/Extension/UploaderExtension.php b/src/Twig/Extension/UploaderExtension.php index 6e291e60..ec62cc10 100644 --- a/src/Twig/Extension/UploaderExtension.php +++ b/src/Twig/Extension/UploaderExtension.php @@ -10,14 +10,8 @@ class UploaderExtension extends AbstractExtension { - /** - * @var UploaderHelper - */ - protected $helper; - - public function __construct(UploaderHelper $helper) + public function __construct(protected UploaderHelper $helper) { - $this->helper = $helper; } public function getName(): string @@ -56,10 +50,7 @@ public function uploadKey(): string return $this->helper->uploadKey(); } - /** - * @return mixed - */ - public function maxSize(string $key) + public function maxSize(string $key): int { return $this->helper->maxSize($key); } diff --git a/src/Uploader/Chunk/ChunkManager.php b/src/Uploader/Chunk/ChunkManager.php index 9d52e139..989f8a08 100644 --- a/src/Uploader/Chunk/ChunkManager.php +++ b/src/Uploader/Chunk/ChunkManager.php @@ -9,20 +9,8 @@ class ChunkManager implements ChunkManagerInterface { - /** - * @var array - */ - protected $configuration; - - /** - * @var ChunkStorageInterface - */ - protected $storage; - - public function __construct(array $configuration, ChunkStorageInterface $storage) + public function __construct(protected array $configuration, protected ChunkStorageInterface $storage) { - $this->configuration = $configuration; - $this->storage = $storage; } public function clear(): void @@ -30,12 +18,12 @@ public function clear(): void $this->storage->clear($this->configuration['maxage']); } - public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original) + public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): mixed { return $this->storage->addChunk($uuid, $index, $chunk, $original); } - public function assembleChunks($chunks, $removeChunk = true, $renameChunk = false) + public function assembleChunks(mixed $chunks, bool $removeChunk = true, bool $renameChunk = false): mixed { return $this->storage->assembleChunks($chunks, $removeChunk, $renameChunk); } @@ -45,7 +33,7 @@ public function cleanup(string $path): void $this->storage->cleanup($path); } - public function getChunks(string $uuid) + public function getChunks(string $uuid): mixed { return $this->storage->getChunks($uuid); } diff --git a/src/Uploader/Chunk/ChunkManagerInterface.php b/src/Uploader/Chunk/ChunkManagerInterface.php index 579d4065..f4aac047 100644 --- a/src/Uploader/Chunk/ChunkManagerInterface.php +++ b/src/Uploader/Chunk/ChunkManagerInterface.php @@ -4,35 +4,27 @@ namespace Oneup\UploaderBundle\Uploader\Chunk; -use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; interface ChunkManagerInterface { /** * Adds a new Chunk to a given uuid. - * - * @return mixed */ - public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original); + public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): mixed; /** * Assembles the given chunks and return the resulting file. * - * @param mixed $chunks - * @param bool $removeChunk remove the chunk file once its assembled - * @param bool $renameChunk rename the chunk file once its assembled - * - * @return mixed + * @param bool $removeChunk remove the chunk file once its assembled + * @param bool $renameChunk rename the chunk file once its assembled */ - public function assembleChunks($chunks, $removeChunk = true, $renameChunk = false); + public function assembleChunks(mixed $chunks, bool $removeChunk = true, bool $renameChunk = false): mixed; /** * Get chunks associated with the given uuid. - * - * @return mixed */ - public function getChunks(string $uuid); + public function getChunks(string $uuid): mixed; /** * Clean a given path. diff --git a/src/Uploader/Chunk/Storage/ChunkStorageInterface.php b/src/Uploader/Chunk/Storage/ChunkStorageInterface.php index 5d4bfc3e..11f82250 100644 --- a/src/Uploader/Chunk/Storage/ChunkStorageInterface.php +++ b/src/Uploader/Chunk/Storage/ChunkStorageInterface.php @@ -10,22 +10,11 @@ interface ChunkStorageInterface { public function clear(int $maxAge): void; - /** - * @return mixed - */ - public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original); - - /** - * @param mixed $chunks - * - * @return mixed - */ - public function assembleChunks($chunks, bool $removeChunk, bool $renameChunk); + public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): mixed; + + public function assembleChunks(mixed $chunks, bool $removeChunk, bool $renameChunk): mixed; public function cleanup(string $path): void; - /** - * @return mixed - */ - public function getChunks(string $uuid); + public function getChunks(string $uuid): mixed; } diff --git a/src/Uploader/Chunk/Storage/FilesystemStorage.php b/src/Uploader/Chunk/Storage/FilesystemStorage.php index 760084d5..4262bf34 100644 --- a/src/Uploader/Chunk/Storage/FilesystemStorage.php +++ b/src/Uploader/Chunk/Storage/FilesystemStorage.php @@ -12,14 +12,8 @@ class FilesystemStorage implements ChunkStorageInterface { - /** - * @var string - */ - protected $directory; - - public function __construct(string $directory) + public function __construct(protected string $directory) { - $this->directory = $directory; } public function clear(int $maxAge): void diff --git a/src/Uploader/Chunk/Storage/FlysystemStorage.php b/src/Uploader/Chunk/Storage/FlysystemStorage.php index 9b3a6421..f28bd0c0 100644 --- a/src/Uploader/Chunk/Storage/FlysystemStorage.php +++ b/src/Uploader/Chunk/Storage/FlysystemStorage.php @@ -13,40 +13,13 @@ class FlysystemStorage implements ChunkStorageInterface { - /** - * @var int - */ - public $bufferSize; - - /** - * @var array - */ - protected $unhandledChunk; - - /** - * @var string - */ - protected $prefix; + protected array $unhandledChunk = []; - /** - * @var string - */ - protected $streamWrapperPrefix; - - /** - * @var FilesystemOperator - */ - private $filesystem; - - public function __construct(Filesystem $filesystem, int $bufferSize, string $streamWrapperPrefix, string $prefix) + public function __construct(protected Filesystem $filesystem, public int $bufferSize, protected string $streamWrapperPrefix, protected string $prefix) { - $this->filesystem = $filesystem; - $this->bufferSize = $bufferSize; - $this->prefix = $prefix; - $this->streamWrapperPrefix = $streamWrapperPrefix; } - public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): void + public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): mixed { // Prevent path traversal attacks $uuid = basename($uuid); @@ -57,6 +30,8 @@ public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $ 'chunk' => $chunk, 'original' => $original, ]; + + return null; } /** @@ -168,7 +143,7 @@ public function getChunks(string $uuid): array $uuid = basename($uuid); return $this->filesystem->listContents($this->prefix . '/' . $uuid) - ->filter(function (StorageAttributes $attributes) { return $attributes->isFile(); }) + ->filter(fn (StorageAttributes $attributes) => $attributes->isFile()) ->sortByPath() ->map(function (StorageAttributes $attributes) { return [ diff --git a/src/Uploader/Chunk/Storage/GaufretteStorage.php b/src/Uploader/Chunk/Storage/GaufretteStorage.php index 581adeac..345f0288 100644 --- a/src/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/src/Uploader/Chunk/Storage/GaufretteStorage.php @@ -20,24 +20,14 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface */ protected $unhandledChunk; - /** - * @var string - */ - protected $prefix; - - /** - * @var string|null - */ - protected $streamWrapperPrefix; - - public function __construct(FilesystemInterface $filesystem, int $bufferSize, ?string $streamWrapperPrefix, string $prefix) + public function __construct(FilesystemInterface $filesystem, int $bufferSize, protected ?string $streamWrapperPrefix, protected string $prefix) { $base = interface_exists(FilesystemInterface::class) ? FilesystemInterface::class : Filesystem::class; if (!$filesystem instanceof $base) { - throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, \get_class($filesystem))); + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, $filesystem::class)); } if ($filesystem instanceof Filesystem && !($filesystem->getAdapter() instanceof StreamFactory)) { @@ -45,8 +35,6 @@ public function __construct(FilesystemInterface $filesystem, int $bufferSize, ?s } $this->filesystem = $filesystem; $this->buffersize = $bufferSize; - $this->prefix = $prefix; - $this->streamWrapperPrefix = $streamWrapperPrefix; } /** @@ -105,7 +93,7 @@ public function clear(int $maxAge, string $prefix = null): void * for gaufrette based chunk storage therefore assembleChunks will * be called in the same request. */ - public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): void + public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $original): mixed { // Prevent path traversal attacks $uuid = basename($uuid); @@ -116,6 +104,8 @@ public function addChunk(string $uuid, int $index, UploadedFile $chunk, string $ 'chunk' => $chunk, 'original' => $original, ]; + + return null; } /** diff --git a/src/Uploader/ErrorHandler/BlueimpErrorHandler.php b/src/Uploader/ErrorHandler/BlueimpErrorHandler.php index 2af40b46..3fd3f407 100644 --- a/src/Uploader/ErrorHandler/BlueimpErrorHandler.php +++ b/src/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -4,23 +4,16 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Exception; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; use Symfony\Contracts\Translation\TranslatorInterface; class BlueimpErrorHandler implements ErrorHandlerInterface { - /** - * @var TranslatorInterface - */ - private $translator; - - public function __construct(TranslatorInterface $translator) + public function __construct(private TranslatorInterface $translator) { - $this->translator = $translator; } - public function addException(AbstractResponse $response, Exception $exception): void + public function addException(AbstractResponse $response, \Exception $exception): void { $message = $this->translator->trans($exception->getMessage(), [], 'OneupUploaderBundle'); $response->addToOffset(['error' => $message], ['files']); diff --git a/src/Uploader/ErrorHandler/DropzoneErrorHandler.php b/src/Uploader/ErrorHandler/DropzoneErrorHandler.php index f1d578dc..3430f1f1 100755 --- a/src/Uploader/ErrorHandler/DropzoneErrorHandler.php +++ b/src/Uploader/ErrorHandler/DropzoneErrorHandler.php @@ -4,12 +4,11 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Exception; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; class DropzoneErrorHandler implements ErrorHandlerInterface { - public function addException(AbstractResponse $response, Exception $exception): void + public function addException(AbstractResponse $response, \Exception $exception): void { $errors[] = $exception; $message = $exception->getMessage(); diff --git a/src/Uploader/ErrorHandler/ErrorHandlerInterface.php b/src/Uploader/ErrorHandler/ErrorHandlerInterface.php index a1b3571a..28875e4d 100644 --- a/src/Uploader/ErrorHandler/ErrorHandlerInterface.php +++ b/src/Uploader/ErrorHandler/ErrorHandlerInterface.php @@ -4,10 +4,9 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Exception; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; interface ErrorHandlerInterface { - public function addException(AbstractResponse $response, Exception $exception): void; + public function addException(AbstractResponse $response, \Exception $exception): void; } diff --git a/src/Uploader/ErrorHandler/NoopErrorHandler.php b/src/Uploader/ErrorHandler/NoopErrorHandler.php index 71826d3b..57dea366 100644 --- a/src/Uploader/ErrorHandler/NoopErrorHandler.php +++ b/src/Uploader/ErrorHandler/NoopErrorHandler.php @@ -4,12 +4,11 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Exception; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; class NoopErrorHandler implements ErrorHandlerInterface { - public function addException(AbstractResponse $response, Exception $exception): void + public function addException(AbstractResponse $response, \Exception $exception): void { // noop } diff --git a/src/Uploader/ErrorHandler/PluploadErrorHandler.php b/src/Uploader/ErrorHandler/PluploadErrorHandler.php index 6d4c0d7a..1ad33e79 100644 --- a/src/Uploader/ErrorHandler/PluploadErrorHandler.php +++ b/src/Uploader/ErrorHandler/PluploadErrorHandler.php @@ -4,12 +4,11 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Exception; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; class PluploadErrorHandler implements ErrorHandlerInterface { - public function addException(AbstractResponse $response, Exception $exception): void + public function addException(AbstractResponse $response, \Exception $exception): void { /* Plupload only needs an error message so it can be handled client side */ $message = $exception->getMessage(); diff --git a/src/Uploader/File/FileInterface.php b/src/Uploader/File/FileInterface.php index cea4878d..d69b13e9 100644 --- a/src/Uploader/File/FileInterface.php +++ b/src/Uploader/File/FileInterface.php @@ -4,8 +4,6 @@ namespace Oneup\UploaderBundle\Uploader\File; -use Symfony\Component\HttpFoundation\File\File; - /** * Every function in this interface should be considered unsafe. * They are only meant to abstract away some basic file functionality. @@ -39,7 +37,7 @@ public function getPath(); /** * Returns the guessed mime type of the file. * - * @return string + * @return string|null */ public function getMimeType(); @@ -55,8 +53,5 @@ public function getBasename(); */ public function getExtension(): string; - /** - * @return mixed - */ - public function getFileSystem(); + public function getFileSystem(): mixed; } diff --git a/src/Uploader/File/FilesystemFile.php b/src/Uploader/File/FilesystemFile.php index 5e353566..e63f00c5 100644 --- a/src/Uploader/File/FilesystemFile.php +++ b/src/Uploader/File/FilesystemFile.php @@ -23,7 +23,7 @@ public function getExtension(): string return $this->getClientOriginalExtension(); } - public function getFileSystem() + public function getFileSystem(): mixed { return null; } diff --git a/src/Uploader/File/FlysystemFile.php b/src/Uploader/File/FlysystemFile.php index ab179a95..a0bd1668 100644 --- a/src/Uploader/File/FlysystemFile.php +++ b/src/Uploader/File/FlysystemFile.php @@ -9,22 +9,14 @@ class FlysystemFile implements FileInterface { - /** @var string */ - private $pathname; - - /** @var FilesystemOperator */ - private $filesystem; - - public function __construct(string $pathname, FilesystemOperator $filesystem) + public function __construct(private string $pathname, private FilesystemOperator $filesystem) { - $this->pathname = $pathname; - $this->filesystem = $filesystem; } /** * @throws FilesystemException */ - public function getSize(): int + public function getSize() { return $this->filesystem->fileSize($this->pathname); } @@ -42,7 +34,7 @@ public function getPath(): string /** * @throws FilesystemException */ - public function getMimeType(): string + public function getMimeType() { return $this->filesystem->mimeType($this->pathname); } diff --git a/src/Uploader/File/GaufretteFile.php b/src/Uploader/File/GaufretteFile.php index 82c76645..f7e24db6 100644 --- a/src/Uploader/File/GaufretteFile.php +++ b/src/Uploader/File/GaufretteFile.php @@ -11,21 +11,14 @@ class GaufretteFile extends File implements FileInterface { - /** - * @var string|null - */ - protected $streamWrapperPrefix; - /** * @var string */ protected $mimeType; - public function __construct(File $file, FilesystemInterface $filesystem, string $streamWrapperPrefix = null) + public function __construct(File $file, FilesystemInterface $filesystem, protected ?string $streamWrapperPrefix = null) { parent::__construct($file->getKey(), $filesystem); - - $this->streamWrapperPrefix = $streamWrapperPrefix; } /** @@ -38,7 +31,7 @@ public function __construct(File $file, FilesystemInterface $filesystem, string * and will have heavy performance footprint. * !! ------- !! */ - public function getSize(): int + public function getSize() { // This can only work on streamable files, so basically local files, // still only perform it once even on local files to avoid bothering the filesystem.php g @@ -74,7 +67,7 @@ public function getBasename(): string return pathinfo($this->getKey(), \PATHINFO_BASENAME); } - public function getMimeType(): string + public function getMimeType() { // This can only work on streamable files, so basically local files, // still only perform it once even on local files to avoid bothering the filesystem. diff --git a/src/Uploader/Orphanage/OrphanageManager.php b/src/Uploader/Orphanage/OrphanageManager.php index 8a15620d..500e6f16 100644 --- a/src/Uploader/Orphanage/OrphanageManager.php +++ b/src/Uploader/Orphanage/OrphanageManager.php @@ -12,20 +12,8 @@ class OrphanageManager { - /** - * @var ContainerInterface - */ - protected $container; - - /** - * @var array - */ - protected $config; - - public function __construct(ContainerInterface $container, array $config) + public function __construct(protected ContainerInterface $container, protected array $config) { - $this->container = $container; - $this->config = $config; } public function has(string $key): bool diff --git a/src/Uploader/Response/AbstractResponse.php b/src/Uploader/Response/AbstractResponse.php index e2507e05..38e66289 100644 --- a/src/Uploader/Response/AbstractResponse.php +++ b/src/Uploader/Response/AbstractResponse.php @@ -6,44 +6,26 @@ abstract class AbstractResponse implements \ArrayAccess, ResponseInterface { - /** - * @var array - */ - protected $data; - - public function __construct() + public function __construct(protected array $data = []) { - $this->data = []; } - /** - * @param mixed $offset - * @param mixed $value - */ public function offsetSet($offset, $value): void { null === $offset ? $this->data[] = $value : $this->data[$offset] = $value; } - /** - * @param mixed $offset - */ public function offsetExists($offset): bool { return isset($this->data[$offset]); } - /** - * @param mixed $offset - */ public function offsetUnset($offset): void { unset($this->data[$offset]); } /** - * @param mixed $offset - * * @return mixed|null */ #[\ReturnTypeWillChange] @@ -53,14 +35,12 @@ public function offsetGet($offset) } /** - * The \ArrayAccess interface does not support multi-dimensional array syntax such as $array["foo"][] = bar + * The \ArrayAccess interface does not support multidimensional array syntax such as $array["foo"][] = bar * This function will take a path of arrays and add a new element to it, creating the path if needed. * - * @param mixed $value - * * @throws \InvalidArgumentException if the path contains non-array items */ - public function addToOffset($value, array $offsets): void + public function addToOffset(array $value, array $offsets): void { $element = &$this->data; foreach ($offsets as $offset) { diff --git a/src/Uploader/Response/FineUploaderResponse.php b/src/Uploader/Response/FineUploaderResponse.php index 907a7bca..b37b3101 100644 --- a/src/Uploader/Response/FineUploaderResponse.php +++ b/src/Uploader/Response/FineUploaderResponse.php @@ -6,28 +6,15 @@ class FineUploaderResponse extends AbstractResponse { - /** - * @var bool - */ - protected $success; - - /** - * @var string|null - */ - protected $error; - - public function __construct() + public function __construct(protected bool $success = true, protected ?string $error = null) { - $this->success = true; - $this->error = null; - parent::__construct(); } public function assemble(): array { // explicitly overwrite success and error key - // as these keys are used internaly by the + // as these keys are used internally by the // frontend uploader $data = $this->data; $data['success'] = $this->success; diff --git a/src/Uploader/Response/MooUploadResponse.php b/src/Uploader/Response/MooUploadResponse.php index f566c9ca..3a5cad90 100644 --- a/src/Uploader/Response/MooUploadResponse.php +++ b/src/Uploader/Response/MooUploadResponse.php @@ -6,41 +6,13 @@ class MooUploadResponse extends AbstractResponse { - /** - * @var int|string - */ - protected $id; - - /** - * @var string|null - */ - protected $name; - - /** - * @var int - */ - protected $size; - - /** - * @var int - */ - protected $error; - - /** - * @var bool - */ - protected $finish; - - /** - * @var string - */ - protected $uploadedName; - - public function __construct() - { - $this->finish = true; - $this->error = 0; + protected int|string|null $id; + protected ?string $name; + protected int $size; + protected string $uploadedName; + public function __construct(protected bool $finish = true, protected int $error = 0) + { parent::__construct(); } @@ -58,20 +30,14 @@ public function assemble(): array return $data; } - /** - * @param mixed $id - */ - public function setId($id): self + public function setId(int|string|null $id): self { $this->id = $id; return $this; } - /** - * @return mixed - */ - public function getId() + public function getId(): int|string|null { return $this->id; } @@ -88,10 +54,7 @@ public function getName(): ?string return $this->name; } - /** - * @param mixed $size - */ - public function setSize($size): self + public function setSize(mixed $size): self { $this->size = (int) $size; diff --git a/src/Uploader/Storage/FilesystemOrphanageStorage.php b/src/Uploader/Storage/FilesystemOrphanageStorage.php index 7ed19a37..83cfaa1a 100644 --- a/src/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/src/Uploader/Storage/FilesystemOrphanageStorage.php @@ -15,43 +15,18 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageStorageInterface { - /** - * @var StorageInterface - */ - protected $storage; - /** * @var SessionInterface */ protected $session; - /** - * @var ChunkStorage - */ - protected $chunkStorage; - - /** - * @var array - */ - protected $config; - - /** - * @var string - */ - protected $type; - - public function __construct(StorageInterface $storage, RequestStack $requestStack, ChunkStorage $chunkStorage, array $config, string $type) + public function __construct(protected StorageInterface $storage, RequestStack $requestStack, protected ChunkStorage $chunkStorage, protected array $config, protected string $type) { parent::__construct($config['directory']); /** @var Request $request */ $request = $requestStack->getCurrentRequest(); - - $this->storage = $storage; $this->session = $request->getSession(); - $this->chunkStorage = $chunkStorage; - $this->config = $config; - $this->type = $type; } /** @@ -80,7 +55,8 @@ public function uploadFiles(array $files = null): array foreach ($files as $file) { $return[] = $this->storage->upload( new FilesystemFile(new File($file->getPathname())), - ltrim(str_replace($this->getFindPath(), '', (string) $file), '/')); + ltrim(str_replace($this->getFindPath(), '', (string) $file), '/') + ); } return $return; @@ -96,10 +72,10 @@ public function getFiles(): Finder try { $finder->in($this->getFindPath())->files(); } catch (\InvalidArgumentException $e) { - //catch non-existing directory exception. - //This can happen if getFiles is called and no file has yet been uploaded + // catch non-existing directory exception. + // This can happen if getFiles is called and no file has yet been uploaded - //push empty array into the finder so we can emulate no files found + // push empty array into the finder so we can emulate no files found $finder->append([]); } diff --git a/src/Uploader/Storage/FilesystemStorage.php b/src/Uploader/Storage/FilesystemStorage.php index 3bcd28c9..a67f7a20 100644 --- a/src/Uploader/Storage/FilesystemStorage.php +++ b/src/Uploader/Storage/FilesystemStorage.php @@ -10,14 +10,8 @@ class FilesystemStorage implements StorageInterface { - /** - * @var string - */ - protected $directory; - - public function __construct(string $directory) + public function __construct(protected string $directory) { - $this->directory = $directory; } /** diff --git a/src/Uploader/Storage/FlysystemOrphanageStorage.php b/src/Uploader/Storage/FlysystemOrphanageStorage.php index 49307c88..9f51f63d 100644 --- a/src/Uploader/Storage/FlysystemOrphanageStorage.php +++ b/src/Uploader/Storage/FlysystemOrphanageStorage.php @@ -16,32 +16,12 @@ class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageStorageInterface { - /** - * @var StorageInterface - */ - protected $storage; - /** * @var SessionInterface */ protected $session; - /** - * @var ChunkStorage - */ - protected $chunkStorage; - - /** - * @var array - */ - protected $config; - - /** - * @var string - */ - protected $type; - - public function __construct(StorageInterface $storage, RequestStack $requestStack, ChunkStorage $chunkStorage, array $config, string $type) + public function __construct(protected StorageInterface $storage, RequestStack $requestStack, protected ChunkStorage $chunkStorage, protected array $config, protected string $type) { /* * initiate the storage on the chunk storage's filesystem @@ -51,12 +31,7 @@ public function __construct(StorageInterface $storage, RequestStack $requestStac /** @var Request $request */ $request = $requestStack->getCurrentRequest(); - - $this->storage = $storage; - $this->chunkStorage = $chunkStorage; $this->session = $request->getSession(); - $this->config = $config; - $this->type = $type; } /** diff --git a/src/Uploader/Storage/FlysystemStorage.php b/src/Uploader/Storage/FlysystemStorage.php index 854757dd..c6895875 100644 --- a/src/Uploader/Storage/FlysystemStorage.php +++ b/src/Uploader/Storage/FlysystemStorage.php @@ -14,26 +14,8 @@ class FlysystemStorage implements StorageInterface { - /** - * @var string|null - */ - protected $streamWrapperPrefix; - - /** - * @var int - */ - protected $bufferSize; - - /** - * @var FilesystemOperator - */ - private $filesystem; - - public function __construct(FilesystemOperator $filesystem, int $bufferSize, ?string $streamWrapperPrefix = null) + public function __construct(private FilesystemOperator $filesystem, protected int $bufferSize, protected ?string $streamWrapperPrefix = null) { - $this->filesystem = $filesystem; - $this->bufferSize = $bufferSize; - $this->streamWrapperPrefix = $streamWrapperPrefix; } /** @@ -73,8 +55,10 @@ public function upload($file, string $name, string $path = null) } if ($file instanceof FileInterface) { + /** @var FilesystemOperator $filesystem */ + $filesystem = $file->getFilesystem(); $manager = new MountManager([ - 'chunks' => $file->getFilesystem(), + 'chunks' => $filesystem, 'dest' => $this->filesystem, ]); diff --git a/src/Uploader/Storage/GaufretteOrphanageStorage.php b/src/Uploader/Storage/GaufretteOrphanageStorage.php index cfab590b..bac1a926 100644 --- a/src/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/src/Uploader/Storage/GaufretteOrphanageStorage.php @@ -14,32 +14,12 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageStorageInterface { - /** - * @var StorageInterface - */ - protected $storage; - /** * @var SessionInterface */ protected $session; - /** - * @var GaufretteChunkStorage - */ - protected $chunkStorage; - - /** - * @var array - */ - protected $config; - - /** - * @var string - */ - protected $type; - - public function __construct(StorageInterface $storage, RequestStack $requestStack, GaufretteChunkStorage $chunkStorage, array $config, string $type) + public function __construct(protected StorageInterface $storage, RequestStack $requestStack, protected GaufretteChunkStorage $chunkStorage, protected array $config, protected string $type) { /* * initiate the storage on the chunk storage's filesystem @@ -49,12 +29,7 @@ public function __construct(StorageInterface $storage, RequestStack $requestStac /** @var Request $request */ $request = $requestStack->getCurrentRequest(); - - $this->storage = $storage; - $this->chunkStorage = $chunkStorage; $this->session = $request->getSession(); - $this->config = $config; - $this->type = $type; } /** diff --git a/src/Uploader/Storage/GaufretteStorage.php b/src/Uploader/Storage/GaufretteStorage.php index 98e02671..ea2cd830 100644 --- a/src/Uploader/Storage/GaufretteStorage.php +++ b/src/Uploader/Storage/GaufretteStorage.php @@ -14,24 +14,18 @@ class GaufretteStorage extends StreamManager implements StorageInterface { - /** - * @var string|null - */ - protected $streamWrapperPrefix; - - public function __construct(FilesystemInterface $filesystem, int $bufferSize, ?string $streamWrapperPrefix = null) + public function __construct(FilesystemInterface $filesystem, int $bufferSize, protected ?string $streamWrapperPrefix = null) { $base = interface_exists(FilesystemInterface::class) ? FilesystemInterface::class : Filesystem::class; if (!$filesystem instanceof $base) { - throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, \get_class($filesystem))); + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, $filesystem::class)); } $this->filesystem = $filesystem; $this->buffersize = $bufferSize; - $this->streamWrapperPrefix = $streamWrapperPrefix; } /** diff --git a/tests/App/Kernel.php b/tests/App/Kernel.php index 1a15234d..fec971fe 100644 --- a/tests/App/Kernel.php +++ b/tests/App/Kernel.php @@ -3,7 +3,6 @@ declare(strict_types=1); use Oneup\UploaderBundle\OneupUploaderBundle; -use Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\SecurityBundle\SecurityBundle; use Symfony\Component\Config\Loader\LoaderInterface; @@ -16,7 +15,6 @@ public function registerBundles(): iterable $bundles = [ new FrameworkBundle(), new SecurityBundle(), - new SensioFrameworkExtraBundle(), // bundle to test new OneupUploaderBundle(), diff --git a/tests/App/config/config.yml b/tests/App/config/config.yml index 3eda25a1..7203fccd 100644 --- a/tests/App/config/config.yml +++ b/tests/App/config/config.yml @@ -1,6 +1,4 @@ framework: - annotations: - enabled: true translator: { fallback: en } secret: secret router: diff --git a/tests/Controller/AbstractUploadTest.php b/tests/Controller/AbstractUploadTest.php index aef114ab..b8494500 100644 --- a/tests/Controller/AbstractUploadTest.php +++ b/tests/Controller/AbstractUploadTest.php @@ -87,8 +87,5 @@ public function testEvents(): void abstract protected function getRequestParameters(): array; - /** - * @return mixed - */ - abstract protected function getRequestFile(); + abstract protected function getRequestFile(): mixed; } diff --git a/tests/Controller/AbstractValidationTest.php b/tests/Controller/AbstractValidationTest.php index 8b9803a7..16c2f60c 100644 --- a/tests/Controller/AbstractValidationTest.php +++ b/tests/Controller/AbstractValidationTest.php @@ -6,6 +6,7 @@ use Oneup\UploaderBundle\Event\ValidationEvent; use Psr\Container\ContainerInterface; +use Symfony\Component\HttpFoundation\File\UploadedFile; abstract class AbstractValidationTest extends AbstractControllerTest { @@ -18,7 +19,7 @@ public function testAgainstMaxSize(): void $client->request('POST', $endpoint, $this->getRequestParameters(), [$this->getOversizedFile()], $this->requestHeaders); $response = $client->getResponse(); - //$this->assertTrue($response->isNotSuccessful()); + // $this->assertTrue($response->isNotSuccessful()); $this->assertSame($response->headers->get('Content-Type'), 'application/json'); $this->assertCount(0, $this->getUploadedFiles()); } @@ -113,30 +114,18 @@ public function testAgainstIncorrectMimeType(): void $client->request('POST', $endpoint, $this->getRequestParameters(), [$this->getFileWithIncorrectMimeType()], $this->requestHeaders); $response = $client->getResponse(); - //$this->assertTrue($response->isNotSuccessful()); + // $this->assertTrue($response->isNotSuccessful()); $this->assertSame($response->headers->get('Content-Type'), 'application/json'); $this->assertCount(0, $this->getUploadedFiles()); } - /** - * @return mixed - */ - abstract protected function getFileWithCorrectMimeType(); - - /** - * @return mixed - */ - abstract protected function getFileWithCorrectMimeTypeAndIncorrectExtension(); - - /** - * @return mixed - */ - abstract protected function getFileWithIncorrectMimeType(); - - /** - * @return mixed - */ - abstract protected function getOversizedFile(); + abstract protected function getFileWithCorrectMimeType(): UploadedFile; + + abstract protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile; + + abstract protected function getFileWithIncorrectMimeType(): UploadedFile; + + abstract protected function getOversizedFile(): UploadedFile; abstract protected function getRequestParameters(): array; } diff --git a/tests/Controller/BlueimpTest.php b/tests/Controller/BlueimpTest.php index 9d0f5b15..73c58e4c 100644 --- a/tests/Controller/BlueimpTest.php +++ b/tests/Controller/BlueimpTest.php @@ -7,6 +7,7 @@ use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Event\PreUploadEvent; use Psr\Container\ContainerInterface; +use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -53,6 +54,7 @@ public function testEvents(): void $container = $client->getContainer(); $endpoint = $this->helper->endpoint($this->getConfigKey()); + /** @var EventDispatcher $dispatcher */ $dispatcher = $container->get('event_dispatcher'); // event data diff --git a/tests/Controller/BlueimpValidationTest.php b/tests/Controller/BlueimpValidationTest.php index eb68247e..0722c0a4 100644 --- a/tests/Controller/BlueimpValidationTest.php +++ b/tests/Controller/BlueimpValidationTest.php @@ -17,11 +17,11 @@ public function testAgainstMaxSize(): void /** @var KernelBrowser $client */ $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile(), $this->requestHeaders); + $file = ['files' => [$this->getOversizedFile()]]; + $client->request('POST', $endpoint, $this->getRequestParameters(), $file, $this->requestHeaders); $response = $client->getResponse(); - //$this->assertTrue($response->isNotSuccessful()); + // $this->assertTrue($response->isNotSuccessful()); $this->assertSame($response->headers->get('Content-Type'), 'application/json'); $this->assertCount(0, $this->getUploadedFiles()); $this->assertFalse(strpos((string) $response->getContent(), 'error.maxsize'), 'Failed to translate error id into lang'); @@ -43,8 +43,8 @@ public function testEvents(): void $dispatcher->addListener(ValidationEvent::NAME, static function () use (&$validationCount): void { ++$validationCount; }); - - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType(), $this->requestHeaders); + $file = ['files' => [$this->getFileWithCorrectMimeType()]]; + $client->request('POST', $endpoint, $this->getRequestParameters(), $file, $this->requestHeaders); $this->assertSame(1, $validationCount); } @@ -54,8 +54,8 @@ public function testAgainstCorrectMimeType(): void // assemble a request $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType(), $this->requestHeaders); + $file = ['files' => [$this->getFileWithCorrectMimeType()]]; + $client->request('POST', $endpoint, $this->getRequestParameters(), $file, $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -74,11 +74,11 @@ public function testAgainstIncorrectMimeType(): void // assemble a request $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType(), $this->requestHeaders); + $file = [$this->getFileWithIncorrectMimeType()]; + $client->request('POST', $endpoint, $this->getRequestParameters(), $file, $this->requestHeaders); $response = $client->getResponse(); - //$this->assertTrue($response->isNotSuccessful()); + // $this->assertTrue($response->isNotSuccessful()); $this->assertSame($response->headers->get('Content-Type'), 'application/json'); $this->assertCount(0, $this->getUploadedFiles()); } @@ -93,39 +93,39 @@ protected function getRequestParameters(): array return []; } - protected function getOversizedFile(): array + protected function getOversizedFile(): UploadedFile { - return ['files' => [new UploadedFile( + return new UploadedFile( $this->createTempFile(512), 'cat.ok', 'text/plain' - )]]; + ); } - protected function getFileWithCorrectMimeType(): array + protected function getFileWithCorrectMimeType(): UploadedFile { - return ['files' => [new UploadedFile( + return new UploadedFile( $this->createTempFile(128), 'cat.txt', 'text/plain' - )]]; + ); } - protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): array + protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile { - return ['files' => [new UploadedFile( + return new UploadedFile( $this->createTempFile(128), 'cat.txxt', 'text/plain' - )]]; + ); } - protected function getFileWithIncorrectMimeType(): array + protected function getFileWithIncorrectMimeType(): UploadedFile { - return [new UploadedFile( + return new UploadedFile( $this->createTempFile(128), 'cat.ok', 'image/gif' - )]; + ); } } diff --git a/tests/Controller/DropzoneValidationTest.php b/tests/Controller/DropzoneValidationTest.php index 3d0b2f9c..0d6f0bf4 100644 --- a/tests/Controller/DropzoneValidationTest.php +++ b/tests/Controller/DropzoneValidationTest.php @@ -18,7 +18,7 @@ protected function getRequestParameters(): array return []; } - protected function getOversizedFile() + protected function getOversizedFile(): UploadedFile { return new UploadedFile( $this->createTempFile(512), @@ -27,7 +27,7 @@ protected function getOversizedFile() ); } - protected function getFileWithCorrectMimeType() + protected function getFileWithCorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -36,7 +36,7 @@ protected function getFileWithCorrectMimeType() ); } - protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -45,7 +45,7 @@ protected function getFileWithCorrectMimeTypeAndIncorrectExtension() ); } - protected function getFileWithIncorrectMimeType() + protected function getFileWithIncorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), diff --git a/tests/Controller/FancyUploadValidationTest.php b/tests/Controller/FancyUploadValidationTest.php index 218aa77a..89afc185 100644 --- a/tests/Controller/FancyUploadValidationTest.php +++ b/tests/Controller/FancyUploadValidationTest.php @@ -18,7 +18,7 @@ protected function getRequestParameters(): array return []; } - protected function getOversizedFile() + protected function getOversizedFile(): UploadedFile { return new UploadedFile( $this->createTempFile(512), @@ -27,7 +27,7 @@ protected function getOversizedFile() ); } - protected function getFileWithCorrectMimeType() + protected function getFileWithCorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -36,7 +36,7 @@ protected function getFileWithCorrectMimeType() ); } - protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -45,7 +45,7 @@ protected function getFileWithCorrectMimeTypeAndIncorrectExtension() ); } - protected function getFileWithIncorrectMimeType() + protected function getFileWithIncorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), diff --git a/tests/Controller/FileBagExtractorTest.php b/tests/Controller/FileBagExtractorTest.php index 6b3d9d75..660a9ffb 100644 --- a/tests/Controller/FileBagExtractorTest.php +++ b/tests/Controller/FileBagExtractorTest.php @@ -83,10 +83,7 @@ public function testWithMultipleFiles(): void $this->assertCount(3, $result); } - /** - * @return mixed - */ - protected function invoke(FileBag $bag) + protected function invoke(FileBag $bag): mixed { return $this->method->invoke($this->mock, $bag); } diff --git a/tests/Controller/FineUploaderValidationTest.php b/tests/Controller/FineUploaderValidationTest.php index e3b17d42..842b83bd 100644 --- a/tests/Controller/FineUploaderValidationTest.php +++ b/tests/Controller/FineUploaderValidationTest.php @@ -18,7 +18,7 @@ protected function getRequestParameters(): array return []; } - protected function getOversizedFile() + protected function getOversizedFile(): UploadedFile { return new UploadedFile( $this->createTempFile(512), @@ -27,7 +27,7 @@ protected function getOversizedFile() ); } - protected function getFileWithCorrectMimeType() + protected function getFileWithCorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -36,7 +36,7 @@ protected function getFileWithCorrectMimeType() ); } - protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -45,7 +45,7 @@ protected function getFileWithCorrectMimeTypeAndIncorrectExtension() ); } - protected function getFileWithIncorrectMimeType() + protected function getFileWithIncorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), diff --git a/tests/Controller/PluploadValidationTest.php b/tests/Controller/PluploadValidationTest.php index 95968590..0e8745a6 100644 --- a/tests/Controller/PluploadValidationTest.php +++ b/tests/Controller/PluploadValidationTest.php @@ -18,7 +18,7 @@ protected function getRequestParameters(): array return []; } - protected function getOversizedFile() + protected function getOversizedFile(): UploadedFile { return new UploadedFile( $this->createTempFile(512), @@ -27,7 +27,7 @@ protected function getOversizedFile() ); } - protected function getFileWithCorrectMimeType() + protected function getFileWithCorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -36,7 +36,7 @@ protected function getFileWithCorrectMimeType() ); } - protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -45,7 +45,7 @@ protected function getFileWithCorrectMimeTypeAndIncorrectExtension() ); } - protected function getFileWithIncorrectMimeType() + protected function getFileWithIncorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), diff --git a/tests/Controller/UploadifyValidationTest.php b/tests/Controller/UploadifyValidationTest.php index 29f5a2d5..e1587cbb 100644 --- a/tests/Controller/UploadifyValidationTest.php +++ b/tests/Controller/UploadifyValidationTest.php @@ -18,7 +18,7 @@ protected function getRequestParameters(): array return []; } - protected function getOversizedFile() + protected function getOversizedFile(): UploadedFile { return new UploadedFile( $this->createTempFile(512), @@ -27,7 +27,7 @@ protected function getOversizedFile() ); } - protected function getFileWithCorrectMimeType() + protected function getFileWithCorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -36,7 +36,7 @@ protected function getFileWithCorrectMimeType() ); } - protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + protected function getFileWithCorrectMimeTypeAndIncorrectExtension(): UploadedFile { return new UploadedFile( $this->createTempFile(128), @@ -45,7 +45,7 @@ protected function getFileWithCorrectMimeTypeAndIncorrectExtension() ); } - protected function getFileWithIncorrectMimeType() + protected function getFileWithIncorrectMimeType(): UploadedFile { return new UploadedFile( $this->createTempFile(128), diff --git a/tests/DependencyInjection/OneupUploaderExtensionTest.php b/tests/DependencyInjection/OneupUploaderExtensionTest.php index 2b8a0b0a..86fc33fc 100644 --- a/tests/DependencyInjection/OneupUploaderExtensionTest.php +++ b/tests/DependencyInjection/OneupUploaderExtensionTest.php @@ -76,8 +76,8 @@ public function testGetMaxUploadSize(): void $getValueInBytes->setAccessible(true); $store = [ - $getValueInBytes->invoke($mock, ini_get('upload_max_filesize')), - $getValueInBytes->invoke($mock, ini_get('post_max_size')), + $getValueInBytes->invoke($mock, \ini_get('upload_max_filesize')), + $getValueInBytes->invoke($mock, \ini_get('post_max_size')), ]; $min = min($store); diff --git a/tests/Templating/TemplateHelperTest.php b/tests/Templating/TemplateHelperTest.php index a0abf716..51a3ec89 100644 --- a/tests/Templating/TemplateHelperTest.php +++ b/tests/Templating/TemplateHelperTest.php @@ -4,6 +4,7 @@ namespace Oneup\UploaderBundle\Tests\Templating; +use Oneup\UploaderBundle\Templating\Helper\UploaderHelper; use Psr\Container\ContainerInterface; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; @@ -20,6 +21,7 @@ public function testName(): void /** @var ContainerInterface $container */ $container = $client->getContainer(); + /** @var UploaderHelper $helper */ $helper = $container->get('oneup_uploader.templating.uploader_helper'); // this is for code coverage diff --git a/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php b/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php index a3ba11cd..e9b7c453 100644 --- a/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php +++ b/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php @@ -74,6 +74,7 @@ public function testGetChunks(): void $system->dumpFile($dir . '/chunk3', 'test'); $timeTo = time(); + /** @var array $files */ $files = $this->storage->getChunks($uuid); $this->assertCount(3, $files); $file = $files[0]; diff --git a/tests/Uploader/File/FilesystemFileTest.php b/tests/Uploader/File/FilesystemFileTest.php index d73ac35d..a8a369cd 100644 --- a/tests/Uploader/File/FilesystemFileTest.php +++ b/tests/Uploader/File/FilesystemFileTest.php @@ -20,7 +20,7 @@ protected function setUp(): void $this->basename = 'test_file.txt'; $this->pathname = $this->path . '/' . $this->basename; $this->extension = 'txt'; - $this->size = 9; //something = 9 bytes + $this->size = 9; // something = 9 bytes $this->mimeType = 'text/plain'; file_put_contents($this->pathname, 'something'); diff --git a/tests/Uploader/File/GaufretteFileTest.php b/tests/Uploader/File/GaufretteFileTest.php index 45bd080f..1febc13e 100644 --- a/tests/Uploader/File/GaufretteFileTest.php +++ b/tests/Uploader/File/GaufretteFileTest.php @@ -31,7 +31,7 @@ protected function setUp(): void $this->basename = 'test_file.txt'; $this->pathname = $this->path . '/' . $this->basename; $this->extension = 'txt'; - $this->size = 9; //something = 9 bytes + $this->size = 9; // something = 9 bytes $this->mimeType = 'text/plain'; file_put_contents(sys_get_temp_dir() . '/' . $this->pathname, 'something'); diff --git a/tests/Uploader/Naming/UrlSafeNamerTest.php b/tests/Uploader/Naming/UrlSafeNamerTest.php index 275ddd00..ae435387 100644 --- a/tests/Uploader/Naming/UrlSafeNamerTest.php +++ b/tests/Uploader/Naming/UrlSafeNamerTest.php @@ -22,7 +22,7 @@ protected function setUp(): void $this->basename = 'test_file.txt'; $this->pathname = $this->path . '/' . $this->basename; $this->extension = 'txt'; - $this->size = 9; //something = 9 bytes + $this->size = 9; // something = 9 bytes $this->mimeType = 'text/plain'; file_put_contents($this->pathname, 'something'); diff --git a/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index 764d9433..3dc7b020 100644 --- a/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -81,7 +81,7 @@ protected function setUp(): void fwrite($pointer, str_repeat('A', 1024), 1024); fclose($pointer); - //file key needs to be relative to the root of the flysystem filesystem + // file key needs to be relative to the root of the flysystem filesystem // It seems that tempnam on OS X prepends 'private' to chunkDirectory, so strip that off as well $fileKey = str_replace([$this->realDirectory, '/private'], '', $file); diff --git a/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php b/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php index 46cc9d19..3a6c06e3 100644 --- a/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php +++ b/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php @@ -42,9 +42,9 @@ class GaufretteAmazonS3StorageTest extends TestCase protected function setUp(): void { if ( - false === getenv('AWS_ACCESS_KEY_ID') || - false === getenv('AWS_SECRET_ACCESS_KEY') || - false === getenv('AWS_BUCKET') + false === getenv('AWS_ACCESS_KEY_ID') + || false === getenv('AWS_SECRET_ACCESS_KEY') + || false === getenv('AWS_BUCKET') ) { $this->markTestSkipped('Missing AWS_* ENV variables.'); } diff --git a/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php b/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php index a1fde8e6..e1235211 100644 --- a/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php +++ b/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php @@ -81,7 +81,7 @@ protected function setUp(): void fwrite($pointer, str_repeat('A', 1024), 1024); fclose($pointer); - //gaufrette needs the key relative to it's root + // gaufrette needs the key relative to it's root $fileKey = str_replace($this->realDirectory, '', $file); $this->payloads[] = new GaufretteFile(new File($fileKey, $filesystem), $filesystem); @@ -134,6 +134,6 @@ public function testUploadAndFetching(): void public function checkIfTempnameMatchesAfterCreation(): bool { - return 0 === strpos((string) @tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory); + return str_starts_with((string) @tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index f10afb32..b12496a5 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -4,12 +4,12 @@ if (!($loader = @include __DIR__ . '/../vendor/autoload.php')) { echo <<<'EOT' -You need to install the project dependencies using Composer: -$ wget http://getcomposer.org/composer.phar -OR -$ curl -s https://getcomposer.org/installer | php -$ php composer.phar install --dev -$ phpunit -EOT; + You need to install the project dependencies using Composer: + $ wget https://getcomposer.org/composer.phar + OR + $ curl -s https://getcomposer.org/installer | php + $ php composer.phar install --dev + $ phpunit + EOT; exit(1); }