From 6a355b289f7f65033057ea154a551127f1c8ef87 Mon Sep 17 00:00:00 2001 From: Freek Van der Herten Date: Fri, 14 Jan 2022 15:09:04 +0100 Subject: [PATCH] v10 (#2723) * wip * wip * Fix styling * wip * Fix styling * wip * Fix styling * wip * wip * wip * PHPUnit to Pest Converter (#2724) * Add Pest dependencies * Add base Pest file * Convert test cases * Remove non-compound imports * Adopt expectation API * Optimize uses * Set return type of base TestCase methods From the [PHPUnit 8 release notes][1], the `TestCase` methods below now declare a `void` return type: - `setUpBeforeClass()` - `setUp()` - `assertPreConditions()` - `assertPostConditions()` - `tearDown()` - `tearDownAfterClass()` - `onNotSuccessfulTest()` [1]: https://phpunit.de/announcements/phpunit-8.html * Use Pest test runner * Shift cleanup * Fix styling * wip * wip * wip * wip * wip * Fix styling Co-authored-by: Shift Co-authored-by: freekmurze * wip * Fix styling * wip * wip * wip * Fix styling * wip * wip * wip * wip * wip * Fix styling * test fix (#2726) * wip * wip * wip * wip * Fix styling * wip * wip * wip * wip * Fix styling * wip * wip Co-authored-by: freekmurze Co-authored-by: Shift Co-authored-by: Fabio Ivona --- .github/workflows/phpstan.yml | 31 + .github/workflows/run-tests.yml | 14 +- .gitignore | 1 + UPGRADING.md | 4 + composer.json | 51 +- .../installation.md | 2 +- docs/requirements.md | 4 +- phpstan-baseline.neon | 1582 +++++++++++++++++ phpstan.neon.dist | 14 + src/Conversions/Conversion.php | 9 +- .../Events/ConversionHasBeenCompleted.php | 9 +- .../Events/ConversionWillStart.php | 13 +- src/Conversions/ImageGenerators/Pdf.php | 4 +- src/Conversions/ImageGenerators/Svg.php | 2 +- .../Jobs/PerformConversionsJob.php | 13 +- src/HasMedia.php | 52 +- src/InteractsWithMedia.php | 51 +- .../Commands/CleanCommand.php | 4 +- .../Events/CollectionHasBeenCleared.php | 9 +- .../Events/MediaHasBeenAdded.php | 5 +- .../FileUnacceptableForCollection.php | 2 +- .../Exceptions/MediaCannotBeDeleted.php | 2 +- src/MediaCollections/File.php | 22 +- src/MediaCollections/FileAdder.php | 15 +- src/MediaCollections/FileAdderFactory.php | 9 +- src/MediaCollections/FileTest.php | 27 - src/MediaCollections/Filesystem.php | 15 +- src/MediaCollections/HtmlableMedia.php | 12 +- src/MediaCollections/MediaCollection.php | 9 +- src/MediaCollections/MediaRepository.php | 24 +- src/MediaCollections/Models/Media.php | 4 +- .../Models/Observers/MediaObserver.php | 2 +- .../Events/ResponsiveImagesGenerated.php | 5 +- .../Jobs/GenerateResponsiveImagesJob.php | 5 +- .../RegisteredResponsiveImages.php | 6 +- src/ResponsiveImages/ResponsiveImage.php | 9 +- .../ResponsiveImageGenerator.php | 18 +- src/Support/MediaLibraryPro.php | 2 +- src/Support/MediaStream.php | 10 +- src/Support/RemoteFile.php | 9 +- src/Support/UrlGenerator/BaseUrlGenerator.php | 9 +- .../UrlGenerator/DefaultUrlGenerator.php | 27 +- src/Support/UrlGenerator/UrlGenerator.php | 6 + .../CleanResponsiveImagesTest.php | 59 +- .../Commands/CleanConversionsTest.php | 295 ++- .../Conversions/Commands/ClearCommandTest.php | 165 +- .../Commands/RegenerateCommandTest.php | 572 +++--- .../Conversions/ConversionCollectionTest.php | 156 +- .../ConversionFileExtensionTest.php | 56 +- tests/Conversions/ConversionFileNamerTest.php | 32 +- tests/Conversions/ConversionTest.php | 372 ++-- tests/Conversions/EventTest.php | 69 +- tests/Conversions/FileManipulatorTest.php | 42 +- .../ImageGenerators/DualTypeCheckingTest.php | 94 +- .../Conversions/ImageGenerators/ImageTest.php | 24 +- tests/Conversions/ImageGenerators/PdfTest.php | 28 +- tests/Conversions/ImageGenerators/SvgTest.php | 28 +- .../TestImageGeneratorWithConfigTest.php | 50 +- .../Conversions/ImageGenerators/VideoTest.php | 30 +- .../Conversions/ImageGenerators/WebpTest.php | 28 +- .../Feature/FileAdder/ConversionsDiskTest.php | 147 +- tests/Feature/FileAdder/IntegrationTest.php | 992 +++++------ .../MediaConversions/AddMediaTest.php | 270 ++- .../MediaConversions/DeleteMediaTest.php | 187 +- .../MediaConversions/MediaCollectionTest.php | 506 +++--- tests/Feature/FileAdder/MultipleDiskTest.php | 136 +- .../InteractsWithMedia/DeleteMediaTest.php | 154 +- .../InteractsWithMedia/GetMediaTest.php | 652 ++++--- .../InteractsWithMedia/HasMediaTest.php | 83 +- .../InteractsWithMedia/UpdateMediaTest.php | 110 +- tests/Feature/Media/CopyTest.php | 224 ++- tests/Feature/Media/CustomHeadersTest.php | 45 +- tests/Feature/Media/CustomPropertyTest.php | 107 +- tests/Feature/Media/DeleteTest.php | 167 +- .../Feature/Media/GetMediaConversionsTest.php | 31 +- .../Media/GetOriginalUrlAttributeTest.php | 25 +- tests/Feature/Media/GetPathTest.php | 82 +- .../Media/GetPreviewUrlAttributeTest.php | 27 +- tests/Feature/Media/GetTypeTest.php | 15 +- tests/Feature/Media/GetUrlTest.php | 75 +- tests/Feature/Media/HasConversionTest.php | 17 +- tests/Feature/Media/MediaRepositoryTest.php | 29 +- tests/Feature/Media/MoveTest.php | 88 +- tests/Feature/Media/RenameTest.php | 73 +- tests/Feature/Media/ResponsableTest.php | 59 +- tests/Feature/Media/ToHtmlTest.php | 262 ++- tests/Feature/Media/ToResponseTest.php | 52 +- .../Feature/Media/UpdateManipulationsTest.php | 110 +- ...responsive_images_and_a_placeholder__1.php | 2 +- tests/Feature/Performance/PerformanceTest.php | 36 +- .../S3Integration/S3IntegrationTest.php | 583 ++---- .../S3Integration/S3TestPathGenerator.php | 2 +- tests/Image/ImageFactoryTest.php | 27 +- tests/MediaCollections/EventTest.php | 23 +- .../FileSystem/FileSystemTest.php | 113 +- .../MediaCollections/MediaCollectionTest.php | 168 +- tests/Pest.php | 52 + .../FileSizeOptimizedWidthCalculatorTest.php | 148 +- .../RegisteredResponsiveImagesTest.php | 60 +- .../ResponsiveImageFileNamerTest.php | 18 +- .../ResponsiveImageGeneratorFileNamerTest.php | 16 +- .../ResponsiveImageGeneratorTest.php | 178 +- .../ResponsiveImages/ResponsiveImageTest.php | 241 ++- tests/Support/FileTest.php | 17 + tests/Support/MediaStreamTest.php | 225 ++- .../PathGenerator/BasePathGeneratorTest.php | 69 +- .../UrlGenerator/BaseUrlGeneratorTest.php | 104 +- tests/TestCase.php | 18 +- .../TestImageGeneratorWithConfig.php | 13 +- 109 files changed, 5629 insertions(+), 5432 deletions(-) create mode 100644 .github/workflows/phpstan.yml create mode 100644 phpstan-baseline.neon create mode 100644 phpstan.neon.dist delete mode 100644 src/MediaCollections/FileTest.php create mode 100644 tests/Pest.php create mode 100644 tests/Support/FileTest.php diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml new file mode 100644 index 000000000..5e06f4a4f --- /dev/null +++ b/.github/workflows/phpstan.yml @@ -0,0 +1,31 @@ +name: PHPStan + +on: + push: + paths: + - '**.php' + - 'phpstan.neon.dist' + pull_request: + paths: + - '**.php' + - 'phpstan.neon.dist' + + +jobs: + phpstan: + name: phpstan + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.1' + coverage: none + + - name: Install composer dependencies + uses: ramsey/composer-install@v1 + + - name: Run PHPStan + run: ./vendor/bin/phpstan --error-format=github diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index f6e07c22a..2fcbded09 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -5,8 +5,6 @@ on: branches: [main] pull_request: branches: [main] - schedule: - - cron: '0 0 * * *' jobs: run-tests: @@ -14,12 +12,12 @@ jobs: strategy: fail-fast: false matrix: - php: [7.4, 8.0, 8.1] - laravel: [8.*] + php: [8.1, 8.0] + laravel: [9.*] dependency-version: [prefer-lowest, prefer-stable] include: - - laravel: 8.* - testbench: ^6.23 + - laravel: 9.* + testbench: ^7.0 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} @@ -54,10 +52,10 @@ jobs: - name: Install dependencies run: | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update - composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest + composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction - name: Execute tests - run: vendor/bin/phpunit + run: vendor/bin/pest env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} diff --git a/.gitignore b/.gitignore index 739d4f091..7edc9dd5f 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ phpunit.xml .env .phpunit.result.cache .php-cs-fixer.cache +phpstan.neon diff --git a/UPGRADING.md b/UPGRADING.md index b4a92cdd8..4cda6dcf4 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -2,6 +2,10 @@ Because there are many breaking changes an upgrade is not that easy. There are many edge cases this guide does not cover. We accept PRs to improve this guide. +## From v9 to v10 + +Upgrading from v9 to v10 is straightforward. The biggest change is that we dropped support for PHP 7, and are using PHP 8 features. + ## From v8 to v9 - add a `json` column `generated_conversions` to the `media` table (take a look at the default migration for the exact definition). You should copy the values you now have in the `generated_conversions` key of the `custom_properties` column to `generated_conversions` diff --git a/composer.json b/composer.json index efc73cc29..ae3a66990 100644 --- a/composer.json +++ b/composer.json @@ -22,36 +22,38 @@ } ], "require": { - "php": "^7.4|^8.0", + "php": "^8.0", "ext-exif": "*", "ext-fileinfo": "*", "ext-json": "*", - "illuminate/bus": "^8.71", - "illuminate/console": "^8.71", - "illuminate/database": "^8.71", - "illuminate/pipeline": "^8.71", - "illuminate/support": "^8.71", + "illuminate/bus": "^9.0", + "illuminate/console": "^9.0", + "illuminate/database": "^9.0", + "illuminate/pipeline": "^9.0", + "illuminate/support": "^9.0", "intervention/image": "^2.7", - "league/flysystem": "^1.0.64", - "league/glide": "^1.7", - "maennchen/zipstream-php": "^1.0|^2.0", - "spatie/image": "^1.10.5", - "spatie/temporary-directory": "^1.1|^2.0", - "symfony/console": "^4.4|^5.0" + "laravel/framework": "9.*", + "maennchen/zipstream-php": "^2.0", + "nunomaduro/larastan": "^1.0", + "orchestra/testbench": "7.*", + "phpstan/extension-installer": "^1.1", + "spatie/image": "^2.2", + "spatie/temporary-directory": "^2.0", + "symfony/console": "^6.0" }, "require-dev": { "ext-pdo_sqlite": "*", "ext-zip": "*", + "ext-imagick": "*", "aws/aws-sdk-php": "^3.133.11", - "doctrine/dbal": "^2.12", - "guzzlehttp/guzzle": "^7.0", - "league/flysystem-aws-s3-v3": "^1.0.23", + "doctrine/dbal": "^2.13", + "guzzlehttp/guzzle": "^7.4", + "league/flysystem-aws-s3-v3": "^2.1", "mockery/mockery": "^1.4", - "orchestra/testbench": "^5.20|^6.23", - "phpunit/phpunit": "^9.3", - "spatie/laravel-ray": "^1.24", + "spatie/laravel-ray": "^1.28", "spatie/pdf-to-image": "^2.1", - "spatie/phpunit-snapshot-assertions": "^4.0" + "spatie/phpunit-snapshot-assertions": "^4.2", + "pestphp/pest": "^1.20" }, "conflict": { "php-ffmpeg/php-ffmpeg": "<0.6.1" @@ -67,8 +69,9 @@ } }, "scripts": { + "analyse": "vendor/bin/phpstan analyse", "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes", - "test": "vendor/bin/phpunit" + "test": "vendor/bin/pest" }, "autoload-dev": { "psr-4": { @@ -83,8 +86,12 @@ } }, "config": { - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true, + "phpstan/extension-installer": true + } }, - "minimum-stability": "stable", + "minimum-stability": "dev", "prefer-stable": true } diff --git a/docs/handling-uploads-with-media-library-pro/installation.md b/docs/handling-uploads-with-media-library-pro/installation.md index 15f48329e..5fe82cb62 100644 --- a/docs/handling-uploads-with-media-library-pro/installation.md +++ b/docs/handling-uploads-with-media-library-pro/installation.md @@ -48,7 +48,7 @@ This is the content you should put in `auth.json`: With the configuration above in place, you'll be able to install the Media Library Pro into your project using this command: ```bash -composer require "spatie/laravel-medialibrary-pro:^1.0.0" +composer require "spatie/laravel-medialibrary-pro:^2.0.0" ``` ## Prepare the database diff --git a/docs/requirements.md b/docs/requirements.md index ae7d1f548..658db3816 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -3,9 +3,7 @@ title: Requirements weight: 5 --- -Laravel Media Library requires **PHP 7.4+** and **Laravel 7+**. - -This package uses `json` columns. MySQL 5.7 or higher is required. +Laravel Media Library requires **PHP 8+** and **Laravel 9+**. The [exif extension](http://php.net/manual/en/exif.installation.php) is required (on most systems it will be installed by default). To create derived images **[GD](http://php.net/manual/en/book.image.php)** needs to be installed on your server. diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon new file mode 100644 index 000000000..c9f35c3d5 --- /dev/null +++ b/phpstan-baseline.neon @@ -0,0 +1,1582 @@ +parameters: + ignoreErrors: + - + message: "#^Class Spatie\\\\MediaLibraryPro\\\\Models\\\\TemporaryUpload not found\\.$#" + count: 1 + path: config/media-library.php + + - + message: "#^Cannot call method convert\\(\\) on Spatie\\\\MediaLibrary\\\\Conversions\\\\ImageGenerators\\\\ImageGenerator\\|null\\.$#" + count: 1 + path: src/Conversions/Actions/PerformConversionAction.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Actions\\\\PerformConversionAction\\:\\:execute\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/Actions/PerformConversionAction.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Commands\\\\RegenerateCommand\\:\\:getMediaIds\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Commands\\\\RegenerateCommand\\:\\:handle\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Parameter \\#1 \\$modelType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelType\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Parameter \\#2 \\$excludeStartingId of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByIdGreaterThan\\(\\) expects bool, array\\|bool\\|string given\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Parameter \\#2 \\$string of function explode expects string, bool\\|string\\|null given\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Parameter \\#3 \\$modelType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByIdGreaterThan\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Parameter \\#3 \\$onlyMissing of method Spatie\\\\MediaLibrary\\\\Conversions\\\\FileManipulator\\:\\:createDerivedFiles\\(\\) expects bool, array\\|bool\\|string\\|null given\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Parameter \\#4 \\$withResponsiveImages of method Spatie\\\\MediaLibrary\\\\Conversions\\\\FileManipulator\\:\\:createDerivedFiles\\(\\) expects bool, array\\|bool\\|string\\|null given\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\Conversions\\\\Commands\\\\RegenerateCommand\\:\\:\\$errorMessages type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/Conversions/Commands/RegenerateCommand.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 2 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:__call\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:__call\\(\\) has parameter \\$arguments with no type specified\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:__call\\(\\) has parameter \\$name with no type specified\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:create\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:getPerformOnCollections\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:performOnCollections\\(\\) has parameter \\$collectionNames with no type specified\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:setManipulations\\(\\) has parameter \\$manipulations with no type specified\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:\\$performOnCollections type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/Conversions/Conversion.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\HasMedia\\:\\:\\$registerMediaConversionsUsingModelInstance\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$collection_name\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$manipulations\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$model_type\\.$#" + count: 2 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Access to an undefined property mixed\\:\\:\\$mediaConversions\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:addManipulationToConversion\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:addManipulationsFromDb\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:createForMedia\\(\\) return type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:getConversions\\(\\) return type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:getConversions\\(\\) should return Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection but returns Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\), mixed\\>\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:getConversionsFiles\\(\\) return type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:getConversionsFiles\\(\\) should return Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection but returns Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\), string\\>\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\:\\:setMedia\\(\\) return type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:each\\(\\) expects callable\\(mixed, \\(int\\|string\\)\\)\\: bool\\|void, Closure\\(Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\)\\: Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion given\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/Conversions/ConversionCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$collection_name\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$disk\\.$#" + count: 2 + path: src/Conversions/FileManipulator.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$responsive_images\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Call to an undefined method object\\:\\:onQueue\\(\\)\\.$#" + count: 2 + path: src/Conversions/FileManipulator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\FileManipulator\\:\\:createDerivedFiles\\(\\) has parameter \\$onlyConversionNames with no value type specified in iterable type array\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\FileManipulator\\:\\:dispatchQueuedConversions\\(\\) has parameter \\$conversions with no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\FileManipulator\\:\\:generateResponsiveImages\\(\\) has no return type specified\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\FileManipulator\\:\\:performConversions\\(\\) has parameter \\$conversions with no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:reject\\(\\) expects bool\\|\\(callable\\(\\(int\\|string\\)\\)\\: bool\\), Closure\\(Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\)\\: bool given\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\\\:\\:each\\(\\) expects callable\\(\\(int\\|string\\), TKey of \\(int\\|string\\)\\)\\: bool\\|void, Closure\\(Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\)\\: void given\\.$#" + count: 1 + path: src/Conversions/FileManipulator.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$mime_type\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGenerator.php + + - + message: "#^Anonymous function with return type void returns \\*NEVER\\* but should not return anything\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Parameter \\#1 \\$mime of method Spatie\\\\MediaLibrary\\\\Conversions\\\\ImageGenerators\\\\ImageGenerator\\:\\:canHandleMime\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Parameter \\#1 \\$string of function strtolower expects string, string\\|null given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Return type of call to method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:map\\(\\) contains unresolvable type\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Unable to resolve the template type TReturn in call to method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:map\\(\\)$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/Conversions/ImageGenerators/ImageGeneratorFactory.php + + - + message: "#^Parameter \\#1 \\$value of function collect expects Illuminate\\\\Contracts\\\\Support\\\\Arrayable\\<\\(int\\|string\\), mixed\\>\\|iterable\\<\\(int\\|string\\), mixed\\>\\|null, 'pdf' given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Pdf.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/Conversions/ImageGenerators/Pdf.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/Conversions/ImageGenerators/Pdf.php + + - + message: "#^Parameter \\#1 \\$value of function collect expects Illuminate\\\\Contracts\\\\Support\\\\Arrayable\\<\\(int\\|string\\), mixed\\>\\|iterable\\<\\(int\\|string\\), mixed\\>\\|null, 'image/svg\\+xml' given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Svg.php + + - + message: "#^Parameter \\#1 \\$value of function collect expects Illuminate\\\\Contracts\\\\Support\\\\Arrayable\\<\\(int\\|string\\), mixed\\>\\|iterable\\<\\(int\\|string\\), mixed\\>\\|null, 'svg' given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Svg.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 2 + path: src/Conversions/ImageGenerators/Svg.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 2 + path: src/Conversions/ImageGenerators/Svg.php + + - + message: "#^Call to static method create\\(\\) on an unknown class FFMpeg\\\\FFMpeg\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Video.php + + - + message: "#^Call to static method fromSeconds\\(\\) on an unknown class FFMpeg\\\\Coordinate\\\\TimeCode\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Video.php + + - + message: "#^Parameter \\#1 \\$image of function imagedestroy expects GdImage, GdImage\\|false given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Webp.php + + - + message: "#^Parameter \\#1 \\$image of function imagepng expects GdImage, GdImage\\|false given\\.$#" + count: 1 + path: src/Conversions/ImageGenerators/Webp.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Conversions\\\\Jobs\\\\PerformConversionsJob\\:\\:__construct\\(\\) has parameter \\$conversions with no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/Jobs/PerformConversionsJob.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\Conversions\\\\Jobs\\\\PerformConversionsJob\\:\\:\\$conversions type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\Conversions\\\\ConversionCollection\\.$#" + count: 1 + path: src/Conversions/Jobs/PerformConversionsJob.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\Conversions\\\\Jobs\\\\PerformConversionsJob\\:\\:\\$deleteWhenMissingModels has no type specified\\.$#" + count: 1 + path: src/Conversions/Jobs/PerformConversionsJob.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Downloaders\\\\DefaultDownloader\\:\\:getTempFile\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/Downloaders/DefaultDownloader.php + + - + message: "#^Parameter \\#1 \\$filename of function file_put_contents expects string, string\\|false given\\.$#" + count: 1 + path: src/Downloaders/DefaultDownloader.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\HasMedia\\:\\:clearMediaCollectionExcept\\(\\) has parameter \\$excludedMedia with no value type specified in iterable type array\\.$#" + count: 1 + path: src/HasMedia.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\HasMedia\\:\\:clearMediaCollectionExcept\\(\\) has parameter \\$excludedMedia with no value type specified in iterable type array\\|Illuminate\\\\Support\\\\Collection\\.$#" + count: 1 + path: src/HasMedia.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\HasMedia\\:\\:getMedia\\(\\) has parameter \\$filters with no value type specified in iterable type array\\.$#" + count: 1 + path: src/HasMedia.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\HasMedia\\:\\:loadMedia\\(\\) has no return type specified\\.$#" + count: 1 + path: src/HasMedia.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$collection_name\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$disk\\.$#" + count: 2 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$responsive_images\\.$#" + count: 2 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Call to an undefined method object\\:\\:getKeyName\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Commands\\\\CleanCommand\\:\\:handle\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:each\\(\\) expects callable\\(mixed, \\(int\\|string\\)\\)\\: bool\\|void, Closure\\(bool, string\\)\\: Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:filter\\(\\) expects \\(callable\\(mixed\\)\\: bool\\)\\|null, Closure\\(bool, string\\)\\: bool given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\\\:\\:each\\(\\) expects callable\\(int, TKey of \\(int\\|string\\)\\)\\: bool\\|void, Closure\\(Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\RegisteredResponsiveImages\\)\\: void given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\\\:\\:reject\\(\\) expects bool\\|\\(callable\\(int\\)\\: bool\\), Closure\\(Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\RegisteredResponsiveImages\\)\\: bool given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\\\:\\:map\\(\\) expects callable\\(int\\|string, int\\)\\: Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\RegisteredResponsiveImages, Closure\\(string\\)\\: Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\RegisteredResponsiveImages given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$collectionName of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByCollectionName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$microseconds of function usleep expects int, float\\|int\\\\|int\\<1000000, max\\> given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$microseconds of function usleep expects int, float\\|int\\\\|int\\<2000000, max\\> given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$modelType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelType\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#1 \\$modelType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelTypeAndCollectionName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Parameter \\#2 \\$collectionName of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelTypeAndCollectionName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Commands\\\\CleanCommand\\:\\:\\$isDryRun \\(bool\\) does not accept array\\|bool\\|string\\|null\\.$#" + count: 1 + path: src/MediaCollections/Commands/CleanCommand.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Commands\\\\ClearCommand\\:\\:handle\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Commands/ClearCommand.php + + - + message: "#^Parameter \\#1 \\$collectionName of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByCollectionName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/ClearCommand.php + + - + message: "#^Parameter \\#1 \\$modelType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelType\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/ClearCommand.php + + - + message: "#^Parameter \\#1 \\$modelType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelTypeAndCollectionName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/ClearCommand.php + + - + message: "#^Parameter \\#2 \\$collectionName of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByModelTypeAndCollectionName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/MediaCollections/Commands/ClearCommand.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/DiskDoesNotExist.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FileDoesNotExist.php + + - + message: "#^Parameter \\#1 \\$sizeInBytes of static method Spatie\\\\MediaLibrary\\\\Support\\\\File\\:\\:getHumanReadableSize\\(\\) expects int, int\\|false given\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FileIsTooBig.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FileIsTooBig.php + + - + message: "#^Call to an undefined method Spatie\\\\MediaLibrary\\\\HasMedia\\:\\:getKey\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FileUnacceptableForCollection.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FileUnacceptableForCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Exceptions\\\\FunctionalityNotAvailable\\:\\:mediaLibraryProRequired\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FunctionalityNotAvailable.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/FunctionalityNotAvailable.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/InvalidBase64Data.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/InvalidConversion.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 2 + path: src/MediaCollections/Exceptions/InvalidPathGenerator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Exceptions\\\\InvalidUrl\\:\\:doesNotStartWithProtocol\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/InvalidUrl.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/InvalidUrl.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 2 + path: src/MediaCollections/Exceptions/InvalidUrlGenerator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Exceptions\\\\MediaCannotBeDeleted\\:\\:doesNotBelongToModel\\(\\) has parameter \\$mediaId with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/MediaCannotBeDeleted.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/MediaCannotBeDeleted.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/MediaCannotBeUpdated.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Exceptions\\\\MimeTypeNotAllowed\\:\\:create\\(\\) has parameter \\$allowedMimeTypes with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/MimeTypeNotAllowed.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/MimeTypeNotAllowed.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/RequestDoesNotHaveFile.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/UnknownType.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Exceptions/UnreachableUrl.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\File\\:\\:createFromMedia\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/File.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\File\\:\\:createFromMedia\\(\\) has parameter \\$media with no type specified\\.$#" + count: 1 + path: src/MediaCollections/File.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/File.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$collection_name\\.$#" + count: 7 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$conversions_disk\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$custom_properties\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$disk\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$generated_conversions\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$manipulations\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$mime_type\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$name\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$order_column\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$responsive_images\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$size\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Call to an undefined method object\\:\\:onQueue\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Call to method getFirstMedia\\(\\) on an unknown class Spatie\\\\MediaLibraryPro\\\\Models\\\\TemporaryUpload\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Call to method moveMedia\\(\\) on an unknown class Spatie\\\\MediaLibraryPro\\\\Models\\\\TemporaryUpload\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot access constant class on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot access property \\$exists on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot access property \\$mediaCollections on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method add\\(\\) on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method addCustomRemoteHeaders\\(\\) on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method addRemote\\(\\) on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method fresh\\(\\) on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method getDisk\\(\\) on string\\|Symfony\\\\Component\\\\HttpFoundation\\\\File\\\\UploadedFile\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method getMedia\\(\\) on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method prepareToAttachMedia\\(\\) on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Cannot call method registerMediaCollections\\(\\) on Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Class Spatie\\\\MediaLibraryPro\\\\Models\\\\TemporaryUpload not found\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Instanceof between string\\|Symfony\\\\Component\\\\HttpFoundation\\\\File\\\\UploadedFile and Spatie\\\\MediaLibrary\\\\Support\\\\RemoteFile will always evaluate to false\\.$#" + count: 3 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:addCustomHeaders\\(\\) has parameter \\$customRemoteHeaders with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:attachMedia\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:checkGenerateResponsiveImages\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:ensureDiskExists\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:guardAgainstDisallowedFileAdditions\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:processMediaItem\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:setFile\\(\\) has parameter \\$file with no type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:withAttributes\\(\\) has parameter \\$properties with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:withCustomProperties\\(\\) has parameter \\$customProperties with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:withManipulations\\(\\) has parameter \\$manipulations with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:withProperties\\(\\) has parameter \\$properties with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:withResponsiveImagesIf\\(\\) has parameter \\$condition with no type specified\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^PHPDoc tag @var for variable \\$temporaryUpload contains unknown class Spatie\\\\MediaLibraryPro\\\\Models\\\\TemporaryUpload\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Parameter \\#1 \\$model of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:processMediaItem\\(\\) expects Spatie\\\\MediaLibrary\\\\HasMedia, Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null given\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Parameter \\#3 \\$hasMedia of static method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Exceptions\\\\FileUnacceptableForCollection\\:\\:create\\(\\) expects Spatie\\\\MediaLibrary\\\\HasMedia, Illuminate\\\\Database\\\\Eloquent\\\\Model\\|null given\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:\\$customHeaders type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:\\$customProperties type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:\\$fileNameSanitizer \\(Closure\\|null\\) does not accept callable\\(\\)\\: mixed\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:\\$manipulations type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdder\\:\\:\\$properties type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Trying to invoke Closure\\|null but it might not be a callable\\.$#" + count: 2 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/MediaCollections/FileAdder.php + + - + message: "#^Access to property \\$name on an unknown class Spatie\\\\MediaLibraryPro\\\\Dto\\\\PendingMediaItem\\.$#" + count: 1 + path: src/MediaCollections/FileAdderFactory.php + + - + message: "#^Access to property \\$order on an unknown class Spatie\\\\MediaLibraryPro\\\\Dto\\\\PendingMediaItem\\.$#" + count: 1 + path: src/MediaCollections/FileAdderFactory.php + + - + message: "#^Access to property \\$temporaryUpload on an unknown class Spatie\\\\MediaLibraryPro\\\\Dto\\\\PendingMediaItem\\.$#" + count: 1 + path: src/MediaCollections/FileAdderFactory.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdderFactory\\:\\:createMultipleFromRequest\\(\\) has parameter \\$keys with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/FileAdderFactory.php + + - + message: "#^Parameter \\#2 \\$file of static method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdderFactory\\:\\:create\\(\\) expects string\\|Symfony\\\\Component\\\\HttpFoundation\\\\File\\\\UploadedFile, Illuminate\\\\Http\\\\UploadedFile\\|null given\\.$#" + count: 1 + path: src/MediaCollections/FileAdderFactory.php + + - + message: "#^Parameter \\$pendingMedia of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\FileAdderFactory\\:\\:createForPendingMedia\\(\\) has invalid type Spatie\\\\MediaLibraryPro\\\\Dto\\\\PendingMediaItem\\.$#" + count: 1 + path: src/MediaCollections/FileAdderFactory.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$conversions_disk\\.$#" + count: 5 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$disk\\.$#" + count: 13 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 2 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:addCustomRemoteHeaders\\(\\) has parameter \\$customRemoteHeaders with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:copyToMediaLibrary\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:getMediaDirectory\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:getRemoteHeadersForFile\\(\\) has parameter \\$mediaCustomHeaders with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:getRemoteHeadersForFile\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:getStream\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:streamFileToDisk\\(\\) has parameter \\$headers with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:streamFileToDisk\\(\\) has parameter \\$stream with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Parameter \\#1 \\$path of method Illuminate\\\\Contracts\\\\Filesystem\\\\Filesystem\\:\\:makeDirectory\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Parameter \\#1 \\$stream of function fclose expects resource, resource\\|false given\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Parameter \\#2 \\$contents of method Illuminate\\\\Contracts\\\\Filesystem\\\\Filesystem\\:\\:put\\(\\) expects resource\\|string, resource\\|false given\\.$#" + count: 2 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Parameter \\#3 \\$mimeType of method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:getRemoteHeadersForFile\\(\\) expects string\\|null, string\\|false given\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Filesystem\\:\\:\\$customRemoteHeaders type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Filesystem.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$mime_type\\.$#" + count: 1 + path: src/MediaCollections/HtmlableMedia.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\HtmlableMedia\\:\\:attributes\\(\\) has parameter \\$attributes with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/HtmlableMedia.php + + - + message: "#^Parameter \\#1 \\$view of function view expects view\\-string\\|null, string given\\.$#" + count: 1 + path: src/MediaCollections/HtmlableMedia.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\HtmlableMedia\\:\\:\\$extraAttributes type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/HtmlableMedia.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaCollection\\:\\:acceptsMimeTypes\\(\\) has parameter \\$mimeTypes with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaCollection\\:\\:create\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaCollection\\:\\:create\\(\\) has parameter \\$name with no type specified\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaCollection\\:\\:registerMediaConversions\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaCollection\\:\\:withResponsiveImagesIf\\(\\) has parameter \\$condition with no type specified\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaCollection\\:\\:\\$acceptsMimeTypes type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/MediaCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$custom_properties\\.$#" + count: 2 + path: src/MediaCollections/MediaRepository.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:applyFilterToMediaCollection\\(\\) has parameter \\$filter with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/MediaRepository.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getByIds\\(\\) has parameter \\$ids with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/MediaRepository.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getCollection\\(\\) has parameter \\$filter with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/MediaRepository.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository\\:\\:getDefaultFilterFunction\\(\\) has parameter \\$filters with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/MediaRepository.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$custom_properties\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$name\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$order_column\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$size\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$uuid\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Collections\\\\MediaCollection\\:\\:collectionName\\(\\) return type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Collections\\\\MediaCollection\\.$#" + count: 1 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Collections\\\\MediaCollection\\:\\:formFieldName\\(\\) return type has no value type specified in iterable type Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Collections\\\\MediaCollection\\.$#" + count: 1 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Parameter \\#1 \\$value of function e expects Illuminate\\\\Contracts\\\\Support\\\\DeferringDisplayableValue\\|Illuminate\\\\Contracts\\\\Support\\\\Htmlable\\|string\\|null, string\\|false given\\.$#" + count: 1 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Return type of call to method Illuminate\\\\Database\\\\Eloquent\\\\Collection\\\\:\\:map\\(\\) contains unresolvable type\\.$#" + count: 2 + path: src/MediaCollections/Models/Collections/MediaCollection.php + + - + message: "#^Access to an undefined property Illuminate\\\\Database\\\\Eloquent\\\\Model\\:\\:\\$uuid\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$conversions_disk\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$custom_properties\\.$#" + count: 7 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$disk\\.$#" + count: 2 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 3 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$generated_conversions\\.$#" + count: 5 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$mime_type\\.$#" + count: 2 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$name\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$order_column\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$size\\.$#" + count: 2 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$sortable\\.$#" + count: 2 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Cannot call method determineOrderColumnName\\(\\) on Illuminate\\\\Database\\\\Eloquent\\\\Collection\\\\|Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Cannot call method save\\(\\) on Illuminate\\\\Database\\\\Eloquent\\\\Collection\\\\|Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Class Spatie\\\\MediaLibraryPro\\\\Models\\\\TemporaryUpload not found\\.$#" + count: 2 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:__invoke\\(\\) has parameter \\$arguments with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:bootHasUuid\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:buildResponse\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:buildResponse\\(\\) has parameter \\$request with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:copy\\(\\) has parameter \\$collectionName with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:findWithTemporaryUploadInCurrentSession\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:findWithTemporaryUploadInCurrentSession\\(\\) has parameter \\$uuids with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:getCustomHeaders\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:getMediaConversionNames\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:getOriginalUrlAttribute\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:getPreviewUrlAttribute\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:getResponsiveImageUrls\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:getTemporaryUrl\\(\\) has parameter \\$options with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:img\\(\\) has parameter \\$extraAttributes with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:move\\(\\) has parameter \\$collectionName with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:newCollection\\(\\) has parameter \\$models with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:setCustomHeaders\\(\\) has parameter \\$customHeaders with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:setNewOrder\\(\\) has parameter \\$ids with no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:stream\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:toInlineResponse\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:toInlineResponse\\(\\) has parameter \\$request with no type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Property 'uuid' does not exist in Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media model\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$appends type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$casts type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Return type of call to function collect contains unresolvable type\\.$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/MediaCollections/Models/Media.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$manipulations\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$order_column\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Call to an undefined method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:isForceDeleting\\(\\)\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Class Laravel\\\\Lumen\\\\Application not found\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^If condition is always true\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Observers\\\\MediaObserver\\:\\:creating\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Observers\\\\MediaObserver\\:\\:deleted\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Observers\\\\MediaObserver\\:\\:updated\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Observers\\\\MediaObserver\\:\\:updating\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Strict comparison using \\=\\=\\= between '9\\.x\\-dev' and '7\\.x\\-dev' will always evaluate to false\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/MediaCollections/Models/Observers/MediaObserver.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\MediaLibraryServiceProvider\\:\\:boot\\(\\) has no return type specified\\.$#" + count: 1 + path: src/MediaLibraryServiceProvider.php + + - + message: "#^Parameter \\#1 \\$model of class Spatie\\\\MediaLibrary\\\\MediaCollections\\\\MediaRepository constructor expects Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media, object given\\.$#" + count: 1 + path: src/MediaLibraryServiceProvider.php + + - + message: "#^Unsafe usage of new static\\(\\)\\.$#" + count: 2 + path: src/ResponsiveImages/Exceptions/InvalidTinyJpg.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$responsive_images\\.$#" + count: 4 + path: src/ResponsiveImages/RegisteredResponsiveImages.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\RegisteredResponsiveImages\\:\\:delete\\(\\) has no return type specified\\.$#" + count: 1 + path: src/ResponsiveImages/RegisteredResponsiveImages.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\RegisteredResponsiveImages\\:\\:getUrls\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/ResponsiveImages/RegisteredResponsiveImages.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/ResponsiveImages/RegisteredResponsiveImages.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/ResponsiveImages/RegisteredResponsiveImages.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$responsive_images\\.$#" + count: 6 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\ResponsiveImage\\:\\:getPropertyParts\\(\\) return type has no value type specified in iterable type array\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\ResponsiveImage\\:\\:register\\(\\) has no return type specified\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\ResponsiveImage\\:\\:register\\(\\) has parameter \\$conversionName with no type specified\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\ResponsiveImage\\:\\:register\\(\\) has parameter \\$fileName with no type specified\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\ResponsiveImage\\:\\:registerTinySvg\\(\\) has no return type specified\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\ResponsiveImage\\:\\:stringBetween\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Parameter \\#2 \\$offset of function substr expects int, int\\|false given\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImage.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$responsive_images\\.$#" + count: 2 + path: src/ResponsiveImages/ResponsiveImageGenerator.php + + - + message: "#^Call to an undefined method Spatie\\\\Image\\\\Manipulations\\:\\:save\\(\\)\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImageGenerator.php + + - + message: "#^Parameter \\#1 \\$string of function base64_encode expects string, string\\|false given\\.$#" + count: 1 + path: src/ResponsiveImages/ResponsiveImageGenerator.php + + - + message: "#^Call to an undefined method Spatie\\\\Image\\\\Manipulations\\:\\:save\\(\\)\\.$#" + count: 1 + path: src/ResponsiveImages/TinyPlaceholderGenerator/Blurred.php + + - + message: "#^Parameter \\#1 \\$fileSize of method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\WidthCalculator\\\\FileSizeOptimizedWidthCalculator\\:\\:calculateWidths\\(\\) expects int, int\\<0, max\\>\\|false given\\.$#" + count: 1 + path: src/ResponsiveImages/WidthCalculator/FileSizeOptimizedWidthCalculator.php + + - + message: "#^Parameter \\#1 \\$predictedFileSize of method Spatie\\\\MediaLibrary\\\\ResponsiveImages\\\\WidthCalculator\\\\FileSizeOptimizedWidthCalculator\\:\\:finishedCalculating\\(\\) expects int, float given\\.$#" + count: 1 + path: src/ResponsiveImages/WidthCalculator/FileSizeOptimizedWidthCalculator.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/ResponsiveImages/WidthCalculator/FileSizeOptimizedWidthCalculator.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/ResponsiveImages/WidthCalculator/FileSizeOptimizedWidthCalculator.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Support\\\\File\\:\\:getMimeType\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/Support/File.php + + - + message: "#^Access to an undefined property Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\:\\:\\$file_name\\.$#" + count: 1 + path: src/Support/FileNamer/FileNamer.php + + - + message: "#^Method Spatie\\\\MediaLibrary\\\\Support\\\\MediaStream\\:\\:addMedia\\(\\) has parameter \\$mediaItems with no type specified\\.$#" + count: 1 + path: src/Support/MediaStream.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\<\\(int\\|string\\),mixed\\>\\:\\:reduce\\(\\) expects callable\\(array, \\(int\\|string\\)\\)\\: non\\-empty\\-array, Closure\\(array, Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\)\\: non\\-empty\\-array given\\.$#" + count: 1 + path: src/Support/MediaStream.php + + - + message: "#^Parameter \\#1 \\$callback of method Illuminate\\\\Support\\\\Collection\\\\:\\:each\\(\\) expects callable\\(mixed, int\\|string\\)\\: bool\\|void, Closure\\(Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\)\\: Illuminate\\\\Support\\\\Collection given\\.$#" + count: 1 + path: src/Support/MediaStream.php + + - + message: "#^Unable to resolve the template type TKey in call to function collect$#" + count: 1 + path: src/Support/MediaStream.php + + - + message: "#^Unable to resolve the template type TReturn in call to method Illuminate\\\\Support\\\\Collection\\\\:\\:flatMap\\(\\)$#" + count: 1 + path: src/Support/MediaStream.php + + - + message: "#^Unable to resolve the template type TValue in call to function collect$#" + count: 1 + path: src/Support/MediaStream.php + + - + message: "#^Cannot access property \\$conversions_disk on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Cannot access property \\$disk on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Cannot access property \\$file_name on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Cannot access property \\$updated_at on Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Cannot call method getPath\\(\\) on Spatie\\\\MediaLibrary\\\\Support\\\\PathGenerator\\\\PathGenerator\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Cannot call method getPathForConversions\\(\\) on Spatie\\\\MediaLibrary\\\\Support\\\\PathGenerator\\\\PathGenerator\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Parameter \\#1 \\$media of method Spatie\\\\MediaLibrary\\\\Conversions\\\\Conversion\\:\\:getConversionFile\\(\\) expects Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media, Spatie\\\\MediaLibrary\\\\MediaCollections\\\\Models\\\\Media\\|null given\\.$#" + count: 1 + path: src/Support/UrlGenerator/BaseUrlGenerator.php + + - + message: "#^Cannot call method getPathForResponsiveImages\\(\\) on Spatie\\\\MediaLibrary\\\\Support\\\\PathGenerator\\\\PathGenerator\\|null\\.$#" + count: 1 + path: src/Support/UrlGenerator/DefaultUrlGenerator.php + diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 000000000..22c943799 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,14 @@ +includes: + - phpstan-baseline.neon + +parameters: + level: 8 + paths: + - src + - config + - database + tmpDir: build/phpstan + checkOctaneCompatibility: true + checkModelProperties: true + checkMissingIterableValueType: true + diff --git a/src/Conversions/Conversion.php b/src/Conversions/Conversion.php index 888cd1ff8..ba4145f26 100644 --- a/src/Conversions/Conversion.php +++ b/src/Conversions/Conversion.php @@ -10,8 +10,6 @@ /** @mixin \Spatie\Image\Manipulations */ class Conversion { - protected string $name = ''; - protected FileNamer $fileNamer; protected float $extractVideoFrameAtSecond = 0; @@ -30,10 +28,9 @@ class Conversion protected int $pdfPageNumber = 1; - public function __construct(string $name) - { - $this->name = $name; - + public function __construct( + protected string $name + ) { $this->manipulations = (new Manipulations()) ->optimize(config('media-library.image_optimizers')) ->format(Manipulations::FORMAT_JPG); diff --git a/src/Conversions/Events/ConversionHasBeenCompleted.php b/src/Conversions/Events/ConversionHasBeenCompleted.php index 9df54cde6..20a8da06d 100644 --- a/src/Conversions/Events/ConversionHasBeenCompleted.php +++ b/src/Conversions/Events/ConversionHasBeenCompleted.php @@ -10,14 +10,7 @@ class ConversionHasBeenCompleted { use SerializesModels; - public Media $media; - - public Conversion $conversion; - - public function __construct(Media $media, Conversion $conversion) + public function __construct(public Media $media, public Conversion $conversion) { - $this->media = $media; - - $this->conversion = $conversion; } } diff --git a/src/Conversions/Events/ConversionWillStart.php b/src/Conversions/Events/ConversionWillStart.php index 864b6366a..99292d677 100644 --- a/src/Conversions/Events/ConversionWillStart.php +++ b/src/Conversions/Events/ConversionWillStart.php @@ -10,18 +10,7 @@ class ConversionWillStart { use SerializesModels; - public Media $media; - - public Conversion $conversion; - - public string $copiedOriginalFile; - - public function __construct(Media $media, Conversion $conversion, string $copiedOriginalFile) + public function __construct(public Media $media, public Conversion $conversion, public string $copiedOriginalFile) { - $this->media = $media; - - $this->conversion = $conversion; - - $this->copiedOriginalFile = $copiedOriginalFile; } } diff --git a/src/Conversions/ImageGenerators/Pdf.php b/src/Conversions/ImageGenerators/Pdf.php index 7b8e85bba..199120b33 100644 --- a/src/Conversions/ImageGenerators/Pdf.php +++ b/src/Conversions/ImageGenerators/Pdf.php @@ -20,11 +20,11 @@ public function convert(string $file, Conversion $conversion = null): string public function requirementsAreInstalled(): bool { - if (! class_exists('Imagick')) { + if (! class_exists(\Imagick::class)) { return false; } - if (! class_exists('\\Spatie\\PdfToImage\\Pdf')) { + if (! class_exists(\Spatie\PdfToImage\Pdf::class)) { return false; } diff --git a/src/Conversions/ImageGenerators/Svg.php b/src/Conversions/ImageGenerators/Svg.php index e0af5b41f..f1c966ed6 100644 --- a/src/Conversions/ImageGenerators/Svg.php +++ b/src/Conversions/ImageGenerators/Svg.php @@ -25,7 +25,7 @@ public function convert(string $file, Conversion $conversion = null): string public function requirementsAreInstalled(): bool { - return class_exists('Imagick'); + return class_exists(\Imagick::class); } public function supportedExtensions(): Collection diff --git a/src/Conversions/Jobs/PerformConversionsJob.php b/src/Conversions/Jobs/PerformConversionsJob.php index 12ef21491..7f45fda8d 100644 --- a/src/Conversions/Jobs/PerformConversionsJob.php +++ b/src/Conversions/Jobs/PerformConversionsJob.php @@ -18,19 +18,8 @@ class PerformConversionsJob implements ShouldQueue public $deleteWhenMissingModels = true; - protected ConversionCollection $conversions; - - protected Media $media; - - protected bool $onlyMissing; - - public function __construct(ConversionCollection $conversions, Media $media, bool $onlyMissing = false) + public function __construct(protected ConversionCollection $conversions, protected Media $media, protected bool $onlyMissing = false) { - $this->conversions = $conversions; - - $this->media = $media; - - $this->onlyMissing = $onlyMissing; } public function handle(FileManipulator $fileManipulator): bool diff --git a/src/HasMedia.php b/src/HasMedia.php index 0e2df1252..2ec637db8 100644 --- a/src/HasMedia.php +++ b/src/HasMedia.php @@ -7,68 +7,26 @@ use Spatie\MediaLibrary\Conversions\Conversion; use Spatie\MediaLibrary\MediaCollections\FileAdder; use Spatie\MediaLibrary\MediaCollections\Models\Media; +use Symfony\Component\HttpFoundation\File\UploadedFile; interface HasMedia { public function media(): MorphMany; - /** - * Move a file to the media library. - * - * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file - * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder - */ - public function addMedia($file): FileAdder; + public function addMedia(string|UploadedFile $file): FileAdder; - /** - * Copy a file to the media library. - * - * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file - * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder - */ - public function copyMedia($file): FileAdder; + public function copyMedia(string|UploadedFile $file): FileAdder; public function hasMedia(string $collectionName = ''): bool; - /** - * Get media collection by its collectionName. - * - * @param string $collectionName - * @param array|callable $filters - * - * @return \Illuminate\Support\Collection - */ - public function getMedia(string $collectionName = 'default', $filters = []): Collection; + public function getMedia(string $collectionName = 'default', array|callable $filters = []): Collection; public function clearMediaCollection(string $collectionName = 'default'): HasMedia; - /** - * Remove all media in the given collection except some. - * - * @param string $collectionName - * @param \Spatie\MediaLibrary\MediaCollections\Models\Media[]|\Illuminate\Support\Collection $excludedMedia - * - * @return $this - */ - public function clearMediaCollectionExcept(string $collectionName = 'default', $excludedMedia = []): HasMedia; + public function clearMediaCollectionExcept(string $collectionName = 'default', array|Collection $excludedMedia = []): HasMedia; - /** - * Determines if the media files should be preserved when the media object gets deleted. - * - * @return bool - */ public function shouldDeletePreservingMedia(): bool; - /** - * Cache the media on the object. - * - * @param string $collectionName - * - * @return mixed - * - */ public function loadMedia(string $collectionName); public function addMediaConversion(string $name): Conversion; diff --git a/src/InteractsWithMedia.php b/src/InteractsWithMedia.php index 9928bbe3e..718b7ffbb 100644 --- a/src/InteractsWithMedia.php +++ b/src/InteractsWithMedia.php @@ -64,11 +64,9 @@ public function media(): MorphMany /** * Add a file to the media library. * - * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder */ - public function addMedia($file): FileAdder + public function addMedia(string|\Symfony\Component\HttpFoundation\File\UploadedFile $file): FileAdder { return app(FileAdderFactory::class)->create($this, $file); } @@ -81,10 +79,7 @@ public function addMediaFromRequest(string $key): FileAdder /** * Add a file from the given disk. * - * @param string $key - * @param string $disk * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder */ public function addMediaFromDisk(string $key, string $disk = null): FileAdder { @@ -138,14 +133,11 @@ public function addAllMediaFromRequest(): Collection /** * Add a remote file to the media library. * - * @param string $url - * @param string|array ...$allowedMimeTypes * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder * * @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\FileCannotBeAdded */ - public function addMediaFromUrl(string $url, ...$allowedMimeTypes): FileAdder + public function addMediaFromUrl(string $url, array|string ...$allowedMimeTypes): FileAdder { if (! Str::startsWith($url, ['http://', 'https://'])) { throw InvalidUrl::doesNotStartWithProtocol($url); @@ -178,8 +170,6 @@ public function addMediaFromUrl(string $url, ...$allowedMimeTypes): FileAdder * Add a file to the media library that contains the given string. * * @param string string - * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder */ public function addMediaFromString(string $text): FileAdder { @@ -197,18 +187,15 @@ public function addMediaFromString(string $text): FileAdder /** * Add a base64 encoded file to the media library. * - * @param string $base64data - * @param string|array ...$allowedMimeTypes * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder * @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\FileCannotBeAdded * * @throws InvalidBase64Data */ - public function addMediaFromBase64(string $base64data, ...$allowedMimeTypes): FileAdder + public function addMediaFromBase64(string $base64data, array|string ...$allowedMimeTypes): FileAdder { // strip out data uri scheme information (see RFC 2397) - if (strpos($base64data, ';base64') !== false) { + if (str_contains($base64data, ';base64')) { [$_, $base64data] = explode(';', $base64data); [$_, $base64data] = explode(',', $base64data); } @@ -240,8 +227,6 @@ public function addMediaFromBase64(string $base64data, ...$allowedMimeTypes): Fi * Add a file to the media library from a stream. * * @param $stream - * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder */ public function addMediaFromStream($stream): FileAdder { @@ -259,11 +244,9 @@ public function addMediaFromStream($stream): FileAdder /** * Copy a file to the media library. * - * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder */ - public function copyMedia($file): FileAdder + public function copyMedia(string|\Symfony\Component\HttpFoundation\File\UploadedFile $file): FileAdder { return $this->addMedia($file)->preservingOriginal(); } @@ -279,12 +262,10 @@ public function hasMedia(string $collectionName = 'default', array $filters = [] /** * Get media collection by its collectionName. * - * @param string $collectionName * @param array|callable $filters * - * @return MediaCollections\Models\Collections\MediaCollection */ - public function getMedia(string $collectionName = 'default', $filters = []): MediaCollections\Models\Collections\MediaCollection + public function getMedia(string $collectionName = 'default', array|callable $filters = []): MediaCollections\Models\Collections\MediaCollection { return $this->getMediaRepository() ->getCollection($this, $collectionName, $filters) @@ -459,16 +440,10 @@ public function clearMediaCollection(string $collectionName = 'default'): HasMed return $this; } - /** - * Remove all media in the given collection except some. - * - * @param string $collectionName - * @param \Spatie\MediaLibrary\MediaCollections\Models\Media[]|\Illuminate\Support\Collection $excludedMedia - * - * @return $this - */ - public function clearMediaCollectionExcept(string $collectionName = 'default', $excludedMedia = []): HasMedia - { + public function clearMediaCollectionExcept( + string $collectionName = 'default', + array|Collection|Media $excludedMedia = [] + ): HasMedia { if ($excludedMedia instanceof Media) { $excludedMedia = collect()->push($excludedMedia); } @@ -499,11 +474,10 @@ public function clearMediaCollectionExcept(string $collectionName = 'default', $ * Delete the associated media with the given id. * You may also pass a media object. * - * @param int|\Spatie\MediaLibrary\MediaCollections\Models\Media $mediaId * * @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\MediaCannotBeDeleted */ - public function deleteMedia($mediaId): void + public function deleteMedia(int|Media $mediaId): void { if ($mediaId instanceof Media) { $mediaId = $mediaId->getKey(); @@ -553,9 +527,6 @@ protected function mediaIsPreloaded(): bool return $this->relationLoaded('media'); } - /* - * Cache the media on the object. - */ public function loadMedia(string $collectionName): Collection { $collection = $this->exists diff --git a/src/MediaCollections/Commands/CleanCommand.php b/src/MediaCollections/Commands/CleanCommand.php index d761981c6..0b0c8c472 100644 --- a/src/MediaCollections/Commands/CleanCommand.php +++ b/src/MediaCollections/Commands/CleanCommand.php @@ -100,7 +100,7 @@ protected function deleteFilesGeneratedForDeprecatedConversions(): void } if ($this->rateLimit) { - usleep((1 / $this->rateLimit) * 1000000 * 2); + usleep((1 / $this->rateLimit) * 1_000_000 * 2); } }); } @@ -164,7 +164,7 @@ protected function deleteOrphanedDirectories(): void } if ($this->rateLimit) { - usleep((1 / $this->rateLimit) * 1000000); + usleep((1 / $this->rateLimit) * 1_000_000); } $this->info("Orphaned media directory `{$directory}` ".($this->isDryRun ? 'found' : 'has been removed')); diff --git a/src/MediaCollections/Events/CollectionHasBeenCleared.php b/src/MediaCollections/Events/CollectionHasBeenCleared.php index 9153d7100..203947592 100644 --- a/src/MediaCollections/Events/CollectionHasBeenCleared.php +++ b/src/MediaCollections/Events/CollectionHasBeenCleared.php @@ -9,14 +9,7 @@ class CollectionHasBeenCleared { use SerializesModels; - public HasMedia $model; - - public string $collectionName; - - public function __construct(HasMedia $model, string $collectionName) + public function __construct(public HasMedia $model, public string $collectionName) { - $this->model = $model; - - $this->collectionName = $collectionName; } } diff --git a/src/MediaCollections/Events/MediaHasBeenAdded.php b/src/MediaCollections/Events/MediaHasBeenAdded.php index 6b1266d03..3c816ac07 100644 --- a/src/MediaCollections/Events/MediaHasBeenAdded.php +++ b/src/MediaCollections/Events/MediaHasBeenAdded.php @@ -9,10 +9,7 @@ class MediaHasBeenAdded { use SerializesModels; - public Media $media; - - public function __construct(Media $media) + public function __construct(public Media $media) { - $this->media = $media; } } diff --git a/src/MediaCollections/Exceptions/FileUnacceptableForCollection.php b/src/MediaCollections/Exceptions/FileUnacceptableForCollection.php index 0099a698d..45a2f0d63 100644 --- a/src/MediaCollections/Exceptions/FileUnacceptableForCollection.php +++ b/src/MediaCollections/Exceptions/FileUnacceptableForCollection.php @@ -10,7 +10,7 @@ class FileUnacceptableForCollection extends FileCannotBeAdded { public static function create(File $file, MediaCollection $mediaCollection, HasMedia $hasMedia): self { - $modelType = get_class($hasMedia); + $modelType = $hasMedia::class; return new static("The file with properties `{$file}` was not accepted into the collection named `{$mediaCollection->name}` of model `{$modelType}` with id `{$hasMedia->getKey()}`"); } diff --git a/src/MediaCollections/Exceptions/MediaCannotBeDeleted.php b/src/MediaCollections/Exceptions/MediaCannotBeDeleted.php index 2b6f8e7a4..76974e547 100644 --- a/src/MediaCollections/Exceptions/MediaCannotBeDeleted.php +++ b/src/MediaCollections/Exceptions/MediaCannotBeDeleted.php @@ -9,7 +9,7 @@ class MediaCannotBeDeleted extends Exception { public static function doesNotBelongToModel($mediaId, Model $model): self { - $modelClass = get_class($model); + $modelClass = $model::class; return new static("Media with id `{$mediaId}` cannot be deleted because it does not exist or does not belong to model {$modelClass} with id {$model->getKey()}"); } diff --git a/src/MediaCollections/File.php b/src/MediaCollections/File.php index 4d3e5920c..3f9abb49a 100644 --- a/src/MediaCollections/File.php +++ b/src/MediaCollections/File.php @@ -2,29 +2,21 @@ namespace Spatie\MediaLibrary\MediaCollections; -class File +class File implements \Stringable { - public string $name; - - public int $size; - - public string $mimeType; - public static function createFromMedia($media) { return new static($media->file_name, $media->size, $media->mime_type); } - public function __construct(string $name, int $size, string $mimeType) - { - $this->name = $name; - - $this->size = $size; - - $this->mimeType = $mimeType; + public function __construct( + public string $name, + public int $size, + public string $mimeType + ) { } - public function __toString() + public function __toString(): string { return "name: {$this->name}, size: {$this->size}, mime: {$this->mimeType}"; } diff --git a/src/MediaCollections/FileAdder.php b/src/MediaCollections/FileAdder.php index b0a239b23..be7820986 100644 --- a/src/MediaCollections/FileAdder.php +++ b/src/MediaCollections/FileAdder.php @@ -26,9 +26,7 @@ class FileAdder { use Macroable; - protected ?Model $subject; - - protected ?Filesystem $filesystem; + protected ?Model $subject = null; protected bool $preserveOriginal = false; @@ -59,10 +57,9 @@ class FileAdder public ?int $order = null; - public function __construct(Filesystem $fileSystem) - { - $this->filesystem = $fileSystem; - + public function __construct( + protected ?Filesystem $filesystem + ) { $this->fileNameSanitizer = fn ($fileName) => $this->defaultSanitizer($fileName); } @@ -399,7 +396,7 @@ protected function attachMedia(Media $media) if (! $this->subject->exists) { $this->subject->prepareToAttachMedia($media, $this); - $class = get_class($this->subject); + $class = $this->subject::class; $class::created(function ($model) { $model->processUnattachedMedia(function (Media $media, self $fileAdder) use ($model) { @@ -415,7 +412,7 @@ protected function attachMedia(Media $media) protected function processMediaItem(HasMedia $model, Media $media, self $fileAdder) { - $this->guardAgainstDisallowedFileAdditions($media, $model); + $this->guardAgainstDisallowedFileAdditions($media); $this->checkGenerateResponsiveImages($media); diff --git a/src/MediaCollections/FileAdderFactory.php b/src/MediaCollections/FileAdderFactory.php index 37306565f..e3083fd4f 100644 --- a/src/MediaCollections/FileAdderFactory.php +++ b/src/MediaCollections/FileAdderFactory.php @@ -7,16 +7,11 @@ use Spatie\MediaLibrary\MediaCollections\Exceptions\RequestDoesNotHaveFile; use Spatie\MediaLibrary\Support\RemoteFile; use Spatie\MediaLibraryPro\Dto\PendingMediaItem; +use Symfony\Component\HttpFoundation\File\UploadedFile; class FileAdderFactory { - /** - * @param \Illuminate\Database\Eloquent\Model $subject - * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file - * - * @return \Spatie\MediaLibrary\MediaCollections\FileAdder - */ - public static function create(Model $subject, $file): FileAdder + public static function create(Model $subject, string|UploadedFile $file): FileAdder { /** @var \Spatie\MediaLibrary\MediaCollections\FileAdder $fileAdder */ $fileAdder = app(FileAdder::class); diff --git a/src/MediaCollections/FileTest.php b/src/MediaCollections/FileTest.php deleted file mode 100644 index 8b54c8fba..000000000 --- a/src/MediaCollections/FileTest.php +++ /dev/null @@ -1,27 +0,0 @@ -assertEquals('10 B', File::getHumanReadableSize(10)); - $this->assertEquals('100 B', File::getHumanReadableSize(100)); - $this->assertEquals('1000 B', File::getHumanReadableSize(1000)); - $this->assertEquals('9.77 KB', File::getHumanReadableSize(10000)); - $this->assertEquals('976.56 KB', File::getHumanReadableSize(1000000)); - $this->assertEquals('9.54 MB', File::getHumanReadableSize(10000000)); - $this->assertEquals('9.31 GB', File::getHumanReadableSize(10000000000)); - } - - /** @test */ - public function it_can_determine_the_mime_type_of_a_file() - { - $this->assertEquals('text/x-php', File::getMimeType(__FILE__)); - } -} diff --git a/src/MediaCollections/Filesystem.php b/src/MediaCollections/Filesystem.php index 9727421d3..dde4fc46e 100644 --- a/src/MediaCollections/Filesystem.php +++ b/src/MediaCollections/Filesystem.php @@ -16,13 +16,11 @@ class Filesystem { - protected Factory $filesystem; - protected array $customRemoteHeaders = []; - public function __construct(Factory $filesystem) - { - $this->filesystem = $filesystem; + public function __construct( + protected Factory $filesystem + ) { } public function add(string $file, Media $media, ?string $targetFileName = null): void @@ -91,7 +89,7 @@ protected function shouldCopyFileOnDisk(RemoteFile $file, Media $media, string $ return false; } - if (count(config('media-library.remote.extra_headers')) > 0) { + if ((is_countable(config('media-library.remote.extra_headers')) ? count(config('media-library.remote.extra_headers')) : 0) > 0) { return false; } @@ -204,9 +202,7 @@ public function removeAllFiles(Media $media): void collect([$mediaDirectory, $conversionsDirectory, $responsiveImagesDirectory]) ->each(function (string $directory) use ($media) { try { - if ($this->filesystem->disk($media->conversions_disk)->exists($directory)) { - $this->filesystem->disk($media->conversions_disk)->deleteDirectory($directory); - } + $this->filesystem->disk($media->conversions_disk)->deleteDirectory($directory); } catch (Exception $exception) { report($exception); } @@ -294,6 +290,7 @@ protected function renameConversionFiles(Media $media): void public function getMediaDirectory(Media $media, ?string $type = null): string { + $directory = null; $pathGenerator = PathGeneratorFactory::create(); if (! $type) { diff --git a/src/MediaCollections/HtmlableMedia.php b/src/MediaCollections/HtmlableMedia.php index ddfd7eb6e..07d6abcd2 100644 --- a/src/MediaCollections/HtmlableMedia.php +++ b/src/MediaCollections/HtmlableMedia.php @@ -7,19 +7,17 @@ use Spatie\MediaLibrary\Conversions\ImageGenerators\Image; use Spatie\MediaLibrary\MediaCollections\Models\Media; -class HtmlableMedia implements Htmlable +class HtmlableMedia implements Htmlable, \Stringable { - protected Media $media; - protected string $conversionName = ''; protected array $extraAttributes = []; protected string $loadingAttributeValue = ''; - public function __construct(Media $media) - { - $this->media = $media; + public function __construct( + protected Media $media + ) { } public function attributes(array $attributes): self @@ -96,7 +94,7 @@ public function toHtml() ))->render(); } - public function __toString() + public function __toString(): string { return $this->toHtml(); } diff --git a/src/MediaCollections/MediaCollection.php b/src/MediaCollections/MediaCollection.php index 3f28da5a2..1190a44bd 100644 --- a/src/MediaCollections/MediaCollection.php +++ b/src/MediaCollections/MediaCollection.php @@ -9,8 +9,6 @@ class MediaCollection { use Macroable; - public string $name = ''; - public string $diskName = ''; public string $conversionsDiskName = ''; @@ -34,10 +32,9 @@ class MediaCollection public string $fallbackPath = ''; - public function __construct(string $name) - { - $this->name = $name; - + public function __construct( + public string $name + ) { $this->mediaConversionRegistrations = function () { }; diff --git a/src/MediaCollections/MediaRepository.php b/src/MediaCollections/MediaRepository.php index a22d23c11..757ae2ca6 100644 --- a/src/MediaCollections/MediaRepository.php +++ b/src/MediaCollections/MediaRepository.php @@ -12,24 +12,22 @@ class MediaRepository { - protected Media $model; - - public function __construct(Media $model) - { - $this->model = $model; + public function __construct( + protected Media $model + ) { } /** * Get all media in the collection. * - * @param \Spatie\MediaLibrary\HasMedia $model - * @param string $collectionName * @param array|callable $filter * - * @return \Illuminate\Support\Collection */ - public function getCollection(HasMedia $model, string $collectionName, $filter = []): Collection - { + public function getCollection( + HasMedia $model, + string $collectionName, + array|callable $filter = [] + ): Collection { return $this->applyFilterToMediaCollection($model->loadMedia($collectionName), $filter); } @@ -41,8 +39,10 @@ public function getCollection(HasMedia $model, string $collectionName, $filter = * * @return \Illuminate\Support\Collection */ - protected function applyFilterToMediaCollection(Collection $media, $filter): Collection - { + protected function applyFilterToMediaCollection( + Collection $media, + array|callable $filter + ): Collection { if (is_array($filter)) { $filter = $this->getDefaultFilterFunction($filter); } diff --git a/src/MediaCollections/Models/Media.php b/src/MediaCollections/Models/Media.php index e176454f2..22ba6fac8 100644 --- a/src/MediaCollections/Models/Media.php +++ b/src/MediaCollections/Models/Media.php @@ -149,15 +149,13 @@ public function hasCustomProperty(string $propertyName): bool * * @return mixed */ - public function getCustomProperty(string $propertyName, $default = null) + public function getCustomProperty(string $propertyName, $default = null): mixed { return Arr::get($this->custom_properties, $propertyName, $default); } /** - * @param string $name * @param mixed $value - * * @return $this */ public function setCustomProperty(string $name, $value): self diff --git a/src/MediaCollections/Models/Observers/MediaObserver.php b/src/MediaCollections/Models/Observers/MediaObserver.php index 1896961ff..017b64c98 100644 --- a/src/MediaCollections/Models/Observers/MediaObserver.php +++ b/src/MediaCollections/Models/Observers/MediaObserver.php @@ -43,7 +43,7 @@ public function updated(Media $media) $original = $media->getOriginal('manipulations'); if (! $this->isLumen() && ! $this->isLaravel7orHigher()) { - $original = json_decode($original, true); + $original = json_decode($original, true, 512, JSON_THROW_ON_ERROR); } if ($media->manipulations !== $original) { diff --git a/src/ResponsiveImages/Events/ResponsiveImagesGenerated.php b/src/ResponsiveImages/Events/ResponsiveImagesGenerated.php index 745ec9adb..a364dfb69 100644 --- a/src/ResponsiveImages/Events/ResponsiveImagesGenerated.php +++ b/src/ResponsiveImages/Events/ResponsiveImagesGenerated.php @@ -9,10 +9,7 @@ class ResponsiveImagesGenerated { use SerializesModels; - public Media $media; - - public function __construct(Media $media) + public function __construct(public Media $media) { - $this->media = $media; } } diff --git a/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php b/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php index 84d0c40a2..0a8c16d0c 100644 --- a/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php +++ b/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php @@ -15,11 +15,8 @@ class GenerateResponsiveImagesJob implements ShouldQueue use SerializesModels; use Queueable; - protected Media $media; - - public function __construct(Media $media) + public function __construct(protected Media $media) { - $this->media = $media; } public function handle(): bool diff --git a/src/ResponsiveImages/RegisteredResponsiveImages.php b/src/ResponsiveImages/RegisteredResponsiveImages.php index bb6503e9b..641cbefa2 100644 --- a/src/ResponsiveImages/RegisteredResponsiveImages.php +++ b/src/ResponsiveImages/RegisteredResponsiveImages.php @@ -7,16 +7,12 @@ class RegisteredResponsiveImages { - protected Media $media; - public Collection $files; public string $generatedFor; - public function __construct(Media $media, string $conversionName = '') + public function __construct(protected Media $media, string $conversionName = '') { - $this->media = $media; - $this->generatedFor = $conversionName === '' ? 'media_library_original' : $conversionName; diff --git a/src/ResponsiveImages/ResponsiveImage.php b/src/ResponsiveImages/ResponsiveImage.php index 83c6634e0..dbaa011bb 100644 --- a/src/ResponsiveImages/ResponsiveImage.php +++ b/src/ResponsiveImages/ResponsiveImage.php @@ -9,10 +9,6 @@ class ResponsiveImage { - public string $fileName = ''; - - public Media $media; - public static function register(Media $media, $fileName, $conversionName) { $responsiveImages = $media->responsive_images; @@ -35,11 +31,8 @@ public static function registerTinySvg(Media $media, string $base64Svg, string $ $media->save(); } - public function __construct(string $fileName, Media $media) + public function __construct(public string $fileName, public Media $media) { - $this->fileName = $fileName; - - $this->media = $media; } public function url(): string diff --git a/src/ResponsiveImages/ResponsiveImageGenerator.php b/src/ResponsiveImages/ResponsiveImageGenerator.php index 0ca8c5465..3e092792b 100644 --- a/src/ResponsiveImages/ResponsiveImageGenerator.php +++ b/src/ResponsiveImages/ResponsiveImageGenerator.php @@ -18,27 +18,15 @@ class ResponsiveImageGenerator { - protected Filesystem $filesystem; - - protected WidthCalculator $widthCalculator; - - protected TinyPlaceholderGenerator $tinyPlaceholderGenerator; - protected const DEFAULT_CONVERSION_QUALITY = 90; protected FileNamer $fileNamer; public function __construct( - Filesystem $filesystem, - WidthCalculator $widthCalculator, - TinyPlaceholderGenerator $tinyPlaceholderGenerator + protected Filesystem $filesystem, + protected WidthCalculator $widthCalculator, + protected TinyPlaceholderGenerator $tinyPlaceholderGenerator ) { - $this->filesystem = $filesystem; - - $this->widthCalculator = $widthCalculator; - - $this->tinyPlaceholderGenerator = $tinyPlaceholderGenerator; - $this->fileNamer = app(config('media-library.file_namer')); } diff --git a/src/Support/MediaLibraryPro.php b/src/Support/MediaLibraryPro.php index 1d1945d05..c14044d29 100644 --- a/src/Support/MediaLibraryPro.php +++ b/src/Support/MediaLibraryPro.php @@ -7,7 +7,7 @@ class MediaLibraryPro { - public static function ensureInstalled() + public static function ensureInstalled(): void { if (! self::isInstalled()) { throw FunctionalityNotAvailable::mediaLibraryProRequired(); diff --git a/src/Support/MediaStream.php b/src/Support/MediaStream.php index 8e42d2fea..c4a996fbb 100644 --- a/src/Support/MediaStream.php +++ b/src/Support/MediaStream.php @@ -11,21 +11,17 @@ class MediaStream implements Responsable { - protected string $zipName; - protected Collection $mediaItems; protected ArchiveOptions $zipOptions; - public static function create(string $zipName) + public static function create(string $zipName): self { - return new static($zipName); + return new self($zipName); } - public function __construct(string $zipName) + public function __construct(protected string $zipName) { - $this->zipName = $zipName; - $this->mediaItems = collect(); $this->zipOptions = new ArchiveOptions(); diff --git a/src/Support/RemoteFile.php b/src/Support/RemoteFile.php index a23e49735..3dfad0afb 100644 --- a/src/Support/RemoteFile.php +++ b/src/Support/RemoteFile.php @@ -4,15 +4,8 @@ class RemoteFile { - protected string $key; - - protected string $disk; - - public function __construct(string $key, string $disk) + public function __construct(protected string $key, protected string $disk) { - $this->key = $key; - - $this->disk = $disk; } public function getKey(): string diff --git a/src/Support/UrlGenerator/BaseUrlGenerator.php b/src/Support/UrlGenerator/BaseUrlGenerator.php index d3e23dbd1..c4c894fd4 100644 --- a/src/Support/UrlGenerator/BaseUrlGenerator.php +++ b/src/Support/UrlGenerator/BaseUrlGenerator.php @@ -11,17 +11,14 @@ abstract class BaseUrlGenerator implements UrlGenerator { - protected ?Media $media; + protected ?Media $media = null; protected ?Conversion $conversion = null; - protected ?PathGenerator $pathGenerator; + protected ?PathGenerator $pathGenerator = null; - protected Config $config; - - public function __construct(Config $config) + public function __construct(protected Config $config) { - $this->config = $config; } public function setMedia(Media $media): UrlGenerator diff --git a/src/Support/UrlGenerator/DefaultUrlGenerator.php b/src/Support/UrlGenerator/DefaultUrlGenerator.php index 0078d62da..b05840551 100644 --- a/src/Support/UrlGenerator/DefaultUrlGenerator.php +++ b/src/Support/UrlGenerator/DefaultUrlGenerator.php @@ -4,7 +4,6 @@ use DateTimeInterface; use Illuminate\Support\Str; -use League\Flysystem\Adapter\AbstractAdapter; class DefaultUrlGenerator extends BaseUrlGenerator { @@ -12,9 +11,7 @@ public function getUrl(): string { $url = $this->getDisk()->url($this->getPathRelativeToRoot()); - $url = $this->versionUrl($url); - - return $url; + return $this->versionUrl($url); } public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string @@ -22,27 +19,14 @@ public function getTemporaryUrl(DateTimeInterface $expiration, array $options = return $this->getDisk()->temporaryUrl($this->getPathRelativeToRoot(), $expiration, $options); } - public function getBaseMediaDirectoryUrl() + public function getBaseMediaDirectoryUrl(): string { return $this->getDisk()->url('/'); } public function getPath(): string { - $adapter = $this->getDisk()->getAdapter(); - - $cachedAdapter = '\League\Flysystem\Cached\CachedAdapter'; - - if ($adapter instanceof $cachedAdapter) { - $adapter = $adapter->getAdapter(); - } - - $pathPrefix = ''; - if ($adapter instanceof AbstractAdapter) { - $pathPrefix = $adapter->getPathPrefix(); - } - - return $pathPrefix.$this->getPathRelativeToRoot(); + return $this->getRootOfDisk().$this->getPathRelativeToRoot(); } public function getResponsiveImagesDirectoryUrl(): string @@ -53,4 +37,9 @@ public function getResponsiveImagesDirectoryUrl(): string return Str::finish(url($base.$path), '/'); } + + protected function getRootOfDisk(): string + { + return config("filesystems.disks.{$this->getDiskName()}.root") . '/'; + } } diff --git a/src/Support/UrlGenerator/UrlGenerator.php b/src/Support/UrlGenerator/UrlGenerator.php index 1cbb59cfe..c108e4fbf 100644 --- a/src/Support/UrlGenerator/UrlGenerator.php +++ b/src/Support/UrlGenerator/UrlGenerator.php @@ -19,6 +19,12 @@ public function setConversion(Conversion $conversion): self; public function setPathGenerator(PathGenerator $pathGenerator): self; + /** + * @param DateTimeInterface $expiration + * @param array $options + * + * @return string + */ public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string; public function getResponsiveImagesDirectoryUrl(): string; diff --git a/tests/Conversions/Commands/CleanCommandTest/CleanResponsiveImagesTest.php b/tests/Conversions/Commands/CleanCommandTest/CleanResponsiveImagesTest.php index dc84c8f14..43ba77165 100644 --- a/tests/Conversions/Commands/CleanCommandTest/CleanResponsiveImagesTest.php +++ b/tests/Conversions/Commands/CleanCommandTest/CleanResponsiveImagesTest.php @@ -1,35 +1,28 @@ testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - - $deprecatedResponsiveImageFileName = 'test___deprecatedConversion_50_41.jpg'; - $deprecatedReponsiveImagesPath = $this->getMediaDirectory("1/responsive-images/{$deprecatedResponsiveImageFileName}"); - touch($deprecatedReponsiveImagesPath); - - $originalResponsiveImagesContent = $media->responsive_images; - $newResponsiveImages = $originalResponsiveImagesContent; - $newResponsiveImages['deprecatedConversion'] = $originalResponsiveImagesContent['thumb']; - $newResponsiveImages['deprecatedConversion']['urls'][0] = $deprecatedResponsiveImageFileName; - $media->responsive_images = $newResponsiveImages; - $media->save(); - - $this->artisan('media-library:clean'); - - $media->refresh(); - - $this->assertEquals($originalResponsiveImagesContent, $media->responsive_images); - $this->assertFileDoesNotExist($deprecatedReponsiveImagesPath); - } -} + + +it('can clean responsive images', function () { + $media = $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + + $deprecatedResponsiveImageFileName = 'test___deprecatedConversion_50_41.jpg'; + $deprecatedReponsiveImagesPath = $this->getMediaDirectory("1/responsive-images/{$deprecatedResponsiveImageFileName}"); + touch($deprecatedReponsiveImagesPath); + + $originalResponsiveImagesContent = $media->responsive_images; + $newResponsiveImages = $originalResponsiveImagesContent; + $newResponsiveImages['deprecatedConversion'] = $originalResponsiveImagesContent['thumb']; + $newResponsiveImages['deprecatedConversion']['urls'][0] = $deprecatedResponsiveImageFileName; + $media->responsive_images = $newResponsiveImages; + $media->save(); + + $this->artisan('media-library:clean'); + + $media->refresh(); + + expect($media->responsive_images)->toEqual($originalResponsiveImagesContent); + $this->assertFileDoesNotExist($deprecatedReponsiveImagesPath); +}); diff --git a/tests/Conversions/Commands/CleanConversionsTest.php b/tests/Conversions/Commands/CleanConversionsTest.php index faf52bc4f..b59281ec1 100644 --- a/tests/Conversions/Commands/CleanConversionsTest.php +++ b/tests/Conversions/Commands/CleanConversionsTest.php @@ -1,201 +1,174 @@ media['model1']['collection1'] = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection1'); + + $this->media['model1']['collection2'] = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection2'); + + $this->media['model2']['collection1'] = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection1'); + + $this->media['model2']['collection2'] = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection2'); + + mkdir($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/conversions")); + mkdir($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/conversions")); + + expect($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg"))->toBeFile(); +}); + +it('can clean deprecated conversion files with none arguments given', function () { + $media = $this->media['model2']['collection1']; + $deprecatedImage = $this->getMediaDirectory("{$media->id}/conversions/test-deprecated.jpg"); + + touch($deprecatedImage); + expect($deprecatedImage)->toBeFile(); + + $this->artisan('media-library:clean'); + + $this->assertFileDoesNotExist($deprecatedImage); + expect($this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"))->toBeFile(); +}); + +test('generated conversion are cleared after cleanup', function () { + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $this->media['model2']['collection1']; + + Media::where('id', '<>', $media->id)->delete(); + + $media->markAsConversionGenerated('test-deprecated'); - public function setUp(): void - { - parent::setUp(); + $media->save(); - $this->media['model1']['collection1'] = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection1'); + expect($media->refresh()->hasGeneratedConversion('test-deprecated'))->toBeTrue(); - $this->media['model1']['collection2'] = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection2'); + $deprecatedImage = $this->getMediaDirectory("{$media->id}/conversions/test-deprecated.jpg"); - $this->media['model2']['collection1'] = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection1'); + touch($deprecatedImage); - $this->media['model2']['collection2'] = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection2'); + $this->artisan('media-library:clean'); - mkdir($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/conversions")); - mkdir($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/conversions")); + $media->refresh(); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); - } + expect($media->hasGeneratedConversion('test-deprecated'))->toBeFalse(); +}); - /** @test */ - public function it_can_clean_deprecated_conversion_files_with_none_arguments_given() - { - $media = $this->media['model2']['collection1']; - $deprecatedImage = $this->getMediaDirectory("{$media->id}/conversions/test-deprecated.jpg"); +it('can clean deprecated conversion files from a specific model type', function () { + $media1 = $this->media['model1']['collection1']; + $media2 = $this->media['model2']['collection1']; - touch($deprecatedImage); - $this->assertFileExists($deprecatedImage); + $deprecatedImage1 = $this->getMediaDirectory("{$media1->id}/conversions/deprecated.jpg"); + $deprecatedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/deprecated.jpg"); + touch($deprecatedImage1); + touch($deprecatedImage2); - $this->artisan('media-library:clean'); + $this->artisan('media-library:clean', [ + 'modelType' => TestModelWithConversion::class, + ]); - $this->assertFileDoesNotExist($deprecatedImage); - $this->assertFileExists($this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg")); - } + expect($deprecatedImage1)->toBeFile(); + $this->assertFileDoesNotExist($deprecatedImage2); +}); - /** @test */ - public function generated_conversion_are_cleared_after_cleanup() - { - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $this->media['model2']['collection1']; +it('can clean deprecated conversion files from a specific collection', function () { + $media1 = $this->media['model1']['collection1']; + $media2 = $this->media['model1']['collection2']; - Media::where('id', '<>', $media->id)->delete(); + $deprecatedImage1 = $this->getMediaDirectory("{$media1->id}/conversions/deprecated.jpg"); + $deprecatedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/deprecated.jpg"); + touch($deprecatedImage1); + touch($deprecatedImage2); - $media->markAsConversionGenerated('test-deprecated'); + $this->artisan('media-library:clean', [ + 'collectionName' => 'collection2', + ]); - $media->save(); + expect($deprecatedImage1)->toBeFile(); + $this->assertFileDoesNotExist($deprecatedImage2); +}); - $this->assertTrue($media->refresh()->hasGeneratedConversion('test-deprecated')); +it('can clean deprecated conversion files from a specific model type and collection', function () { + $media1 = $this->media['model1']['collection1']; + $media2 = $this->media['model1']['collection2']; + $media3 = $this->media['model2']['collection1']; - $deprecatedImage = $this->getMediaDirectory("{$media->id}/conversions/test-deprecated.jpg"); - - touch($deprecatedImage); - - $this->artisan('media-library:clean'); - - $media->refresh(); + $deprecatedImage1 = $this->getMediaDirectory("{$media1->id}/conversions/deprecated.jpg"); + $deprecatedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/deprecated.jpg"); + $deprecatedImage3 = $this->getMediaDirectory("{$media3->id}/conversions/deprecated.jpg"); - $this->assertFalse($media->hasGeneratedConversion('test-deprecated')); - } + touch($deprecatedImage1); + touch($deprecatedImage2); + touch($deprecatedImage3); - /** @test */ - public function it_can_clean_deprecated_conversion_files_from_a_specific_model_type() - { - $media1 = $this->media['model1']['collection1']; - $media2 = $this->media['model2']['collection1']; - - $deprecatedImage1 = $this->getMediaDirectory("{$media1->id}/conversions/deprecated.jpg"); - $deprecatedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/deprecated.jpg"); - touch($deprecatedImage1); - touch($deprecatedImage2); + $this->artisan('media-library:clean', [ + 'modelType' => TestModel::class, + 'collectionName' => 'collection1', + ]); - $this->artisan('media-library:clean', [ - 'modelType' => TestModelWithConversion::class, - ]); + $this->assertFileDoesNotExist($deprecatedImage1); + expect($deprecatedImage2)->toBeFile(); + expect($deprecatedImage3)->toBeFile(); +}); - $this->assertFileExists($deprecatedImage1); - $this->assertFileDoesNotExist($deprecatedImage2); - } +it('can clean orphan files in the media disk', function () { + // Dirty delete + DB::table('media')->delete($this->media['model1']['collection1']->id); - /** @test */ - public function it_can_clean_deprecated_conversion_files_from_a_specific_collection() - { - $media1 = $this->media['model1']['collection1']; - $media2 = $this->media['model1']['collection2']; - - $deprecatedImage1 = $this->getMediaDirectory("{$media1->id}/conversions/deprecated.jpg"); - $deprecatedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/deprecated.jpg"); - touch($deprecatedImage1); - touch($deprecatedImage2); - - $this->artisan('media-library:clean', [ - 'collectionName' => 'collection2', - ]); - - $this->assertFileExists($deprecatedImage1); - $this->assertFileDoesNotExist($deprecatedImage2); - } - - /** @test */ - public function it_can_clean_deprecated_conversion_files_from_a_specific_model_type_and_collection() - { - $media1 = $this->media['model1']['collection1']; - $media2 = $this->media['model1']['collection2']; - $media3 = $this->media['model2']['collection1']; + $this->artisan('media-library:clean'); - $deprecatedImage1 = $this->getMediaDirectory("{$media1->id}/conversions/deprecated.jpg"); - $deprecatedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/deprecated.jpg"); - $deprecatedImage3 = $this->getMediaDirectory("{$media3->id}/conversions/deprecated.jpg"); + $this->assertFileDoesNotExist($this->getMediaDirectory($this->media['model1']['collection1']->id)); + expect($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg"))->toBeFile(); +}); - touch($deprecatedImage1); - touch($deprecatedImage2); - touch($deprecatedImage3); +it('can clean responsive images', function () { + $media = $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); - $this->artisan('media-library:clean', [ - 'modelType' => TestModel::class, - 'collectionName' => 'collection1', - ]); + $deprecatedResponsiveImageFileName = 'test___deprecatedConversion_50_41.jpg'; + $deprecatedReponsiveImagesPath = $this->getMediaDirectory("5/responsive-images/{$deprecatedResponsiveImageFileName}"); + touch($deprecatedReponsiveImagesPath); - $this->assertFileDoesNotExist($deprecatedImage1); - $this->assertFileExists($deprecatedImage2); - $this->assertFileExists($deprecatedImage3); - } + $originalResponsiveImagesContent = $media->responsive_images; + $newResponsiveImages = $originalResponsiveImagesContent; + $newResponsiveImages['deprecatedConversion'] = $originalResponsiveImagesContent['thumb']; + $newResponsiveImages['deprecatedConversion']['urls'][0] = $deprecatedResponsiveImageFileName; + $media->responsive_images = $newResponsiveImages; + $media->save(); - /** @test */ - public function it_can_clean_orphan_files_in_the_media_disk() - { - // Dirty delete - DB::table('media')->delete($this->media['model1']['collection1']->id); + $this->artisan('media-library:clean'); - $this->artisan('media-library:clean'); + $media->refresh(); - $this->assertFileDoesNotExist($this->getMediaDirectory($this->media['model1']['collection1']->id)); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - } + expect($media->responsive_images)->toEqual($originalResponsiveImagesContent); + $this->assertFileDoesNotExist($deprecatedReponsiveImagesPath); +}); - /** @test */ - public function it_can_clean_responsive_images() - { - $media = $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); +it('will throw an exception when using a non existing disk', function () { + $this->expectException(DiskDoesNotExist::class); - $deprecatedResponsiveImageFileName = 'test___deprecatedConversion_50_41.jpg'; - $deprecatedReponsiveImagesPath = $this->getMediaDirectory("5/responsive-images/{$deprecatedResponsiveImageFileName}"); - touch($deprecatedReponsiveImagesPath); + config(['media-library.disk_name' => 'diskdoesnotexist']); - $originalResponsiveImagesContent = $media->responsive_images; - $newResponsiveImages = $originalResponsiveImagesContent; - $newResponsiveImages['deprecatedConversion'] = $originalResponsiveImagesContent['thumb']; - $newResponsiveImages['deprecatedConversion']['urls'][0] = $deprecatedResponsiveImageFileName; - $media->responsive_images = $newResponsiveImages; - $media->save(); - - $this->artisan('media-library:clean'); - - $media->refresh(); - - $this->assertEquals($originalResponsiveImagesContent, $media->responsive_images); - $this->assertFileDoesNotExist($deprecatedReponsiveImagesPath); - } - - /** @test */ - public function it_will_throw_an_exception_when_using_a_non_existing_disk() - { - $this->expectException(DiskDoesNotExist::class); - - config(['media-library.disk_name' => 'diskdoesnotexist']); - - $this->artisan('media-library:clean') - ->assertExitCode(1); - } -} + $this->artisan('media-library:clean') + ->assertExitCode(1); +}); diff --git a/tests/Conversions/Commands/ClearCommandTest.php b/tests/Conversions/Commands/ClearCommandTest.php index 7d72d6ac9..bd35f7434 100644 --- a/tests/Conversions/Commands/ClearCommandTest.php +++ b/tests/Conversions/Commands/ClearCommandTest.php @@ -1,96 +1,77 @@ media['model1']['collection1'] = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection1'); - - $this->media['model1']['collection2'] = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection2'); - - $this->media['model2']['collection1'] = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection1'); - - $this->media['model2']['collection2'] = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('collection2'); - - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); - } - - /** @test */ - public function it_can_clear_all_media() - { - $this->artisan('media-library:clear'); - - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); - } - - /** @test */ - public function it_can_clear_media_from_a_specific_model_type() - { - $this->artisan('media-library:clear', [ - 'modelType' => TestModel::class, - ]); - - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); - } - - /** @test */ - public function it_can_clear_media_from_a_specific_collection() - { - $this->artisan('media-library:clear', [ - 'collectionName' => 'collection2', - ]); - - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); - } - - /** @test */ - public function it_can_clear_media_from_a_specific_model_type_and_collection() - { - $this->artisan('media-library:clear', [ - 'modelType' => TestModel::class, - 'collectionName' => 'collection2', - ]); - - $this->assertFileExists($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); - - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); - $this->assertFileExists($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); - } -} +beforeEach(function () { + $this->media['model1']['collection1'] = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection1'); + + $this->media['model1']['collection2'] = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection2'); + + $this->media['model2']['collection1'] = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection1'); + + $this->media['model2']['collection2'] = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('collection2'); + + expect($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg"))->toBeFile(); +}); + +it('can clear all media', function () { + $this->artisan('media-library:clear'); + + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); + + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg")); + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); +}); + +it('can clear media from a specific model type', function () { + $this->artisan('media-library:clear', [ + 'modelType' => TestModel::class, + ]); + + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg")); + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); + + expect($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg"))->toBeFile(); +}); + +it('can clear media from a specific collection', function () { + $this->artisan('media-library:clear', [ + 'collectionName' => 'collection2', + ]); + + expect($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg"))->toBeFile(); + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); + + expect($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg"))->toBeFile(); + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg")); +}); + +it('can clear media from a specific model type and collection', function () { + $this->artisan('media-library:clear', [ + 'modelType' => TestModel::class, + 'collectionName' => 'collection2', + ]); + + expect($this->getMediaDirectory("{$this->media['model1']['collection1']->id}/test.jpg"))->toBeFile(); + $this->assertFileDoesNotExist($this->getMediaDirectory("{$this->media['model1']['collection2']->id}/test.jpg")); + + expect($this->getMediaDirectory("{$this->media['model2']['collection1']->id}/test.jpg"))->toBeFile(); + expect($this->getMediaDirectory("{$this->media['model2']['collection2']->id}/test.jpg"))->toBeFile(); +}); diff --git a/tests/Conversions/Commands/RegenerateCommandTest.php b/tests/Conversions/Commands/RegenerateCommandTest.php index dc70d31eb..4a482d098 100644 --- a/tests/Conversions/Commands/RegenerateCommandTest.php +++ b/tests/Conversions/Commands/RegenerateCommandTest.php @@ -1,383 +1,351 @@ testModelWithConversion->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection('images'); - - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $createdAt = filemtime($derivedImage); - - unlink($derivedImage); - - $this->assertFileDoesNotExist($derivedImage); - - sleep(1); - - $this->artisan('media-library:regenerate'); - - $this->assertFileExists($derivedImage); - $this->assertGreaterThan($createdAt, filemtime($derivedImage)); - } - - /** @test */ - public function it_can_regenerate_only_missing_files() - { - $mediaExists = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); - - $mediaMissing = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.png')) - ->toMediaCollection('images'); - - $derivedImageExists = $this->getMediaDirectory("{$mediaExists->id}/conversions/test-thumb.jpg"); - - $derivedMissingImage = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-thumb.jpg"); - - $existsCreatedAt = filemtime($derivedImageExists); - - $missingCreatedAt = filemtime($derivedMissingImage); +it('can regenerate all files', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection('images'); - unlink($derivedMissingImage); + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $createdAt = filemtime($derivedImage); - $this->assertFileDoesNotExist($derivedMissingImage); + unlink($derivedImage); - sleep(1); + $this->assertFileDoesNotExist($derivedImage); - $this->artisan('media-library:regenerate', [ - '--only-missing' => true, - ]); + sleep(1); - $this->assertFileExists($derivedMissingImage); + $this->artisan('media-library:regenerate'); - $this->assertSame($existsCreatedAt, filemtime($derivedImageExists)); + expect($derivedImage)->toBeFile(); + expect(filemtime($derivedImage))->toBeGreaterThan($createdAt); +}); - $this->assertGreaterThan($missingCreatedAt, filemtime($derivedMissingImage)); - } +it('can regenerate only missing files', function () { + $mediaExists = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - /** @test */ - public function it_can_regenerate_missing_files_queued() - { - $mediaExists = $this - ->testModelWithConversionQueued - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $mediaMissing = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.png')) + ->toMediaCollection('images'); - $mediaMissing = $this - ->testModelWithConversionQueued - ->addMedia($this->getTestFilesDirectory('test.png')) - ->toMediaCollection('images'); + $derivedImageExists = $this->getMediaDirectory("{$mediaExists->id}/conversions/test-thumb.jpg"); - $derivedImageExists = $this->getMediaDirectory("{$mediaExists->id}/conversions/test-thumb.jpg"); + $derivedMissingImage = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-thumb.jpg"); - $derivedMissingImage = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-thumb.jpg"); + $existsCreatedAt = filemtime($derivedImageExists); - $existsCreatedAt = filemtime($derivedImageExists); + $missingCreatedAt = filemtime($derivedMissingImage); - $missingCreatedAt = filemtime($derivedMissingImage); + unlink($derivedMissingImage); - unlink($derivedMissingImage); + $this->assertFileDoesNotExist($derivedMissingImage); - $this->assertFileDoesNotExist($derivedMissingImage); + sleep(1); - sleep(1); + $this->artisan('media-library:regenerate', [ + '--only-missing' => true, + ]); - $this->artisan('media-library:regenerate', [ - '--only-missing' => true, - ]); + expect($derivedMissingImage)->toBeFile(); - $this->assertFileExists($derivedMissingImage); + expect(filemtime($derivedImageExists))->toBe($existsCreatedAt); - $this->assertSame($existsCreatedAt, filemtime($derivedImageExists)); + expect(filemtime($derivedMissingImage))->toBeGreaterThan($missingCreatedAt); +}); - $this->assertGreaterThan($missingCreatedAt, filemtime($derivedMissingImage)); - } +it('can regenerate missing files queued', function () { + $mediaExists = $this + ->testModelWithConversionQueued + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - /** @test */ - public function it_can_regenerate_all_files_of_named_conversions() - { - $media = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $mediaMissing = $this + ->testModelWithConversionQueued + ->addMedia($this->getTestFilesDirectory('test.png')) + ->toMediaCollection('images'); - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedMissingImage = $this->getMediaDirectory("{$media->id}/conversions/test-keep_original_format.jpg"); + $derivedImageExists = $this->getMediaDirectory("{$mediaExists->id}/conversions/test-thumb.jpg"); - unlink($derivedImage); - unlink($derivedMissingImage); + $derivedMissingImage = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-thumb.jpg"); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedMissingImage); + $existsCreatedAt = filemtime($derivedImageExists); - $this->artisan('media-library:regenerate', [ - '--only' => 'thumb', - ]); + $missingCreatedAt = filemtime($derivedMissingImage); - $this->assertFileExists($derivedImage); - $this->assertFileDoesNotExist($derivedMissingImage); - } + unlink($derivedMissingImage); - /** @test */ - public function it_can_regenerate_only_missing_files_of_named_conversions() - { - $mediaExists = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $this->assertFileDoesNotExist($derivedMissingImage); - $mediaMissing = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.png')) - ->toMediaCollection('images'); + sleep(1); - $derivedImageExists = $this->getMediaDirectory("{$mediaExists->id}/conversions/test-thumb.jpg"); - $derivedMissingImage = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-thumb.jpg"); - $derivedMissingImageOriginal = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-keep_original_format.png"); + $this->artisan('media-library:regenerate', [ + '--only-missing' => true, + ]); - $existsCreatedAt = filemtime($derivedImageExists); - $missingCreatedAt = filemtime($derivedMissingImage); + expect($derivedMissingImage)->toBeFile(); - unlink($derivedMissingImage); - unlink($derivedMissingImageOriginal); + expect(filemtime($derivedImageExists))->toBe($existsCreatedAt); - $this->assertFileDoesNotExist($derivedMissingImage); - $this->assertFileDoesNotExist($derivedMissingImageOriginal); + expect(filemtime($derivedMissingImage))->toBeGreaterThan($missingCreatedAt); +}); - sleep(1); +it('can regenerate all files of named conversions', function () { + $media = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - $this->artisan('media-library:regenerate', [ - '--only-missing' => true, - '--only' => 'thumb', - ]); + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedMissingImage = $this->getMediaDirectory("{$media->id}/conversions/test-keep_original_format.jpg"); - $this->assertFileExists($derivedMissingImage); - $this->assertFileDoesNotExist($derivedMissingImageOriginal); - $this->assertSame($existsCreatedAt, filemtime($derivedImageExists)); - $this->assertGreaterThan($missingCreatedAt, filemtime($derivedMissingImage)); - } + unlink($derivedImage); + unlink($derivedMissingImage); - /** @test */ - public function it_can_regenerate_files_by_media_ids() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedMissingImage); - $media2 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $this->artisan('media-library:regenerate', [ + '--only' => 'thumb', + ]); - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + expect($derivedImage)->toBeFile(); + $this->assertFileDoesNotExist($derivedMissingImage); +}); - unlink($derivedImage); - unlink($derivedImage2); +it('can regenerate only missing files of named conversions', function () { + $mediaExists = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedImage2); - - $this->artisan('media-library:regenerate', ['--ids' => [2]]); - - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileExists($derivedImage2); - } + $mediaMissing = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.png')) + ->toMediaCollection('images'); - /** @test */ - public function it_can_regenerate_files_by_comma_separated_media_ids() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); + $derivedImageExists = $this->getMediaDirectory("{$mediaExists->id}/conversions/test-thumb.jpg"); + $derivedMissingImage = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-thumb.jpg"); + $derivedMissingImageOriginal = $this->getMediaDirectory("{$mediaMissing->id}/conversions/test-keep_original_format.png"); - $media2 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $existsCreatedAt = filemtime($derivedImageExists); + $missingCreatedAt = filemtime($derivedMissingImage); - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + unlink($derivedMissingImage); + unlink($derivedMissingImageOriginal); - unlink($derivedImage); - unlink($derivedImage2); + $this->assertFileDoesNotExist($derivedMissingImage); + $this->assertFileDoesNotExist($derivedMissingImageOriginal); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedImage2); + sleep(1); - $this->artisan('media-library:regenerate', ['--ids' => ['1,2']]); + $this->artisan('media-library:regenerate', [ + '--only-missing' => true, + '--only' => 'thumb', + ]); - $this->assertFileExists($derivedImage); - $this->assertFileExists($derivedImage2); - } + expect($derivedMissingImage)->toBeFile(); + $this->assertFileDoesNotExist($derivedMissingImageOriginal); + expect(filemtime($derivedImageExists))->toBe($existsCreatedAt); + expect(filemtime($derivedMissingImage))->toBeGreaterThan($missingCreatedAt); +}); - /** @test */ - public function it_can_regenerate_files_even_if_there_are_files_missing() - { - $media = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); +it('can regenerate files by media ids', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); - unlink($this->getMediaDirectory($media->id.'/test.jpg')); + $media2 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - $this->artisan('media-library:regenerate')->assertExitCode(0); - } + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); - /** @test */ - public function it_can_regenerate_responsive_images() - { - $media = $this - ->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->withResponsiveImages() - ->toMediaCollection(); + unlink($derivedImage); + unlink($derivedImage2); - $responsiveImages = glob($this->getMediaDirectory($media->id.'/responsive-images/*')); + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedImage2); - array_map('unlink', $responsiveImages); + $this->artisan('media-library:regenerate', ['--ids' => [2]]); - $this->artisan('media-library:regenerate', ['--with-responsive-images' => true])->assertExitCode(0); + $this->assertFileDoesNotExist($derivedImage); + expect($derivedImage2)->toBeFile(); +}); - foreach ($responsiveImages as $image) { - $this->assertFileExists($image); - } - } +it('can regenerate files by comma separated media ids', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); - /** @test */ - public function it_can_regenerate_files_by_starting_from_id() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); + $media2 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - $media2 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + unlink($derivedImage); + unlink($derivedImage2); - unlink($derivedImage); - unlink($derivedImage2); + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedImage2); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedImage2); + $this->artisan('media-library:regenerate', ['--ids' => ['1,2']]); - $this->artisan('media-library:regenerate', ['--starting-from-id' => $media2->getKey()]); + expect($derivedImage)->toBeFile(); + expect($derivedImage2)->toBeFile(); +}); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileExists($derivedImage2); - } +it('can regenerate files even if there are files missing', function () { + $media = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - /** @test */ - public function it_can_regenerate_files_starting_after_the_provided_id() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); + unlink($this->getMediaDirectory($media->id.'/test.jpg')); - $media2 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $this->artisan('media-library:regenerate')->assertExitCode(0); +}); - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); +it('can regenerate responsive images', function () { + $media = $this + ->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->withResponsiveImages() + ->toMediaCollection(); - unlink($derivedImage); - unlink($derivedImage2); + $responsiveImages = glob($this->getMediaDirectory($media->id.'/responsive-images/*')); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedImage2); + array_map('unlink', $responsiveImages); - $this->artisan('media-library:regenerate', [ - '--starting-from-id' => $media->getKey(), - '--exclude-starting-id' => true, - ]); + $this->artisan('media-library:regenerate', ['--with-responsive-images' => true])->assertExitCode(0); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileExists($derivedImage2); + foreach ($responsiveImages as $image) { + expect($image)->toBeFile(); } +}); - /** @test */ - public function it_can_regenerate_files_starting_after_the_provided_id_with_shortcut() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); +it('can regenerate files by starting from id', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); - $media2 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection('images'); + $media2 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); - unlink($derivedImage); - unlink($derivedImage2); + unlink($derivedImage); + unlink($derivedImage2); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedImage2); + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedImage2); + + $this->artisan('media-library:regenerate', ['--starting-from-id' => $media2->getKey()]); + + $this->assertFileDoesNotExist($derivedImage); + expect($derivedImage2)->toBeFile(); +}); + +it('can regenerate files starting after the provided id', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); + + $media2 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); + + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + + unlink($derivedImage); + unlink($derivedImage2); + + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedImage2); + + $this->artisan('media-library:regenerate', [ + '--starting-from-id' => $media->getKey(), + '--exclude-starting-id' => true, + ]); + + $this->assertFileDoesNotExist($derivedImage); + expect($derivedImage2)->toBeFile(); +}); + +it('can regenerate files starting after the provided id with shortcut', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); + + $media2 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection('images'); + + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + + unlink($derivedImage); + unlink($derivedImage2); + + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedImage2); + + $this->artisan('media-library:regenerate', [ + '--starting-from-id' => $media->getKey(), + '-X' => true, + ]); + + $this->assertFileDoesNotExist($derivedImage); + expect($derivedImage2)->toBeFile(); +}); + +it('can regenerate files starting from id with model type', function () { + $media = $this->testModelWithConversionsOnOtherDisk + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); + + $media2 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); + + $media3 = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.jpg')) + ->preservingOriginal() + ->toMediaCollection('images'); + + $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); + $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); + $derivedImage3 = $this->getMediaDirectory("{$media3->id}/conversions/test-thumb.jpg"); + + unlink($derivedImage); + unlink($derivedImage2); + unlink($derivedImage3); - $this->artisan('media-library:regenerate', [ - '--starting-from-id' => $media->getKey(), - '-X' => true, - ]); + $this->assertFileDoesNotExist($derivedImage); + $this->assertFileDoesNotExist($derivedImage2); + $this->assertFileDoesNotExist($derivedImage3); - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileExists($derivedImage2); - } - - /** @test */ - public function it_can_regenerate_files_starting_from_id_with_model_type() - { - $media = $this->testModelWithConversionsOnOtherDisk - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); - - $media2 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); - - $media3 = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.jpg')) - ->preservingOriginal() - ->toMediaCollection('images'); - - $derivedImage = $this->getMediaDirectory("{$media->id}/conversions/test-thumb.jpg"); - $derivedImage2 = $this->getMediaDirectory("{$media2->id}/conversions/test-thumb.jpg"); - $derivedImage3 = $this->getMediaDirectory("{$media3->id}/conversions/test-thumb.jpg"); - - unlink($derivedImage); - unlink($derivedImage2); - unlink($derivedImage3); - - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileDoesNotExist($derivedImage2); - $this->assertFileDoesNotExist($derivedImage3); - - $this->artisan('media-library:regenerate', [ - '--starting-from-id' => $media->getKey(), - 'modelType' => TestModelWithConversion::class, - ]); - - $this->assertFileDoesNotExist($derivedImage); - $this->assertFileExists($derivedImage2); - $this->assertFileExists($derivedImage3); - } -} + $this->artisan('media-library:regenerate', [ + '--starting-from-id' => $media->getKey(), + 'modelType' => TestModelWithConversion::class, + ]); + + $this->assertFileDoesNotExist($derivedImage); + expect($derivedImage2)->toBeFile(); + expect($derivedImage3)->toBeFile(); +}); diff --git a/tests/Conversions/ConversionCollectionTest.php b/tests/Conversions/ConversionCollectionTest.php index 5807fb494..755e00ca7 100644 --- a/tests/Conversions/ConversionCollectionTest.php +++ b/tests/Conversions/ConversionCollectionTest.php @@ -1,118 +1,98 @@ testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); - protected Media $secondMedia; + $media->manipulations = ['thumb' => ['filter' => 'greyscale', 'height' => 10]]; + $media->save(); - public function setUp(): void - { - parent::setUp(); + $secondMedia = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); + $secondMedia->manipulations = ['thumb' => ['filter' => 'greyscale', 'height' => 20]]; + $secondMedia->save(); - $media->manipulations = ['thumb' => ['filter' => 'greyscale', 'height' => 10]]; - $media->save(); + $this->media = $media->fresh(); + $this->secondMedia = $media->fresh(); +}); - $secondMedia = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); +it('will prepend the manipulation saved on the model and the wildmark manipulations', function () { + $this->media->manipulations = [ + '*' => ['brightness' => '-80'], + 'thumb' => ['filter' => 'greyscale', 'height' => 10], + ]; - $secondMedia->manipulations = ['thumb' => ['filter' => 'greyscale', 'height' => 20]]; - $secondMedia->save(); + $conversionCollection = ConversionCollection::createForMedia($this->media); - $this->media = $media->fresh(); - $this->secondMedia = $media->fresh(); - } + $conversion = $conversionCollection->getConversions()[0]; - /** @test */ - public function it_will_prepend_the_manipulation_saved_on_the_model_and_the_wildmark_manipulations() - { - $this->media->manipulations = [ - '*' => ['brightness' => '-80'], - 'thumb' => ['filter' => 'greyscale', 'height' => 10], - ]; + expect($conversion->getName())->toEqual('thumb'); - $conversionCollection = ConversionCollection::createForMedia($this->media); + $manipulationSequence = $conversion + ->getManipulations() + ->getManipulationSequence() + ->toArray(); - $conversion = $conversionCollection->getConversions()[0]; + $this->assertArrayHasKey('optimize', $manipulationSequence[0]); - $this->assertEquals('thumb', $conversion->getName()); + unset($manipulationSequence[0]['optimize']); - $manipulationSequence = $conversion - ->getManipulations() - ->getManipulationSequence() - ->toArray(); + $this->assertEquals([[ + 'brightness' => '-80', + 'filter' => 'greyscale', + 'height' => 10, + 'width' => 50, + 'format' => 'jpg', + ]], $manipulationSequence); +}); - $this->assertArrayHasKey('optimize', $manipulationSequence[0]); +it('will prepend the manipulation saved on the model', function () { + $conversionCollection = ConversionCollection::createForMedia($this->media); - unset($manipulationSequence[0]['optimize']); + $conversion = $conversionCollection->getConversions()[0]; - $this->assertEquals([[ - 'brightness' => '-80', - 'filter' => 'greyscale', - 'height' => 10, - 'width' => 50, - 'format' => 'jpg', - ]], $manipulationSequence); - } + expect($conversion->getName())->toEqual('thumb'); - /** @test */ - public function it_will_prepend_the_manipulation_saved_on_the_model() - { - $conversionCollection = ConversionCollection::createForMedia($this->media); + $manipulationSequence = $conversion + ->getManipulations() + ->getManipulationSequence() + ->toArray(); - $conversion = $conversionCollection->getConversions()[0]; + $this->assertArrayHasKey('optimize', $manipulationSequence[0]); + + unset($manipulationSequence[0]['optimize']); + + $this->assertEquals([[ + 'filter' => 'greyscale', + 'height' => 10, + 'width' => 50, + 'format' => 'jpg', + ]], $manipulationSequence); +}); - $this->assertEquals('thumb', $conversion->getName()); +it('will apply the manipulation on the equally named conversion of every model', function () { + $mediaItems = [$this->media, $this->secondMedia]; + $manipulations = []; + + foreach ($mediaItems as $mediaItem) { + $conversionCollection = ConversionCollection::createForMedia($mediaItem); + + $conversion = $conversionCollection->getConversions()[0]; $manipulationSequence = $conversion ->getManipulations() ->getManipulationSequence() ->toArray(); - $this->assertArrayHasKey('optimize', $manipulationSequence[0]); - - unset($manipulationSequence[0]['optimize']); - - $this->assertEquals([[ - 'filter' => 'greyscale', - 'height' => 10, - 'width' => 50, - 'format' => 'jpg', - ]], $manipulationSequence); + $manipulations[] = $manipulationSequence; } - /** @test */ - public function it_will_apply_the_manipulation_on_the_equally_named_conversion_of_every_model() - { - $mediaItems = [$this->media, $this->secondMedia]; - $manipulations = []; - - foreach ($mediaItems as $mediaItem) { - $conversionCollection = ConversionCollection::createForMedia($mediaItem); - - $conversion = $conversionCollection->getConversions()[0]; - - $manipulationSequence = $conversion - ->getManipulations() - ->getManipulationSequence() - ->toArray(); - - $manipulations[] = $manipulationSequence; - } - - $this->assertEquals($manipulations[0], $manipulations[1]); - } -} + expect($manipulations[1])->toEqual($manipulations[0]); +}); diff --git a/tests/Conversions/ConversionFileExtensionTest.php b/tests/Conversions/ConversionFileExtensionTest.php index 1e6da4aa9..7d6578937 100644 --- a/tests/Conversions/ConversionFileExtensionTest.php +++ b/tests/Conversions/ConversionFileExtensionTest.php @@ -1,48 +1,26 @@ testModelWithConversion->addMedia($this->getTestPng())->toMediaCollection(); -use Spatie\MediaLibrary\Tests\TestCase; + expect($media->getUrl('thumb'))->toHaveExtension('jpg'); +}); -class ConversionFileExtensionTest extends TestCase -{ - /** @test */ - public function it_defaults_to_jpg_when_the_original_file_is_an_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestPng())->toMediaCollection(); +it('can keep the original image format if the original file is an image', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestPng())->toMediaCollection(); - $this->assertExtensionEquals('jpg', $media->getUrl('thumb')); - } + expect($media->getUrl('keep_original_format'))->toHaveExtension('png'); +}); - /** @test */ - public function it_can_keep_the_original_image_format_if_the_original_file_is_an_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestPng())->toMediaCollection(); +it('can keep the original image format if the original file is an image with uppercase extension', function () { + $media = $this->testModelWithConversion->addMedia($this->getUppercaseExtensionTestPng())->toMediaCollection(); - $this->assertExtensionEquals('png', $media->getUrl('keep_original_format')); - } + expect($media->getUrl('keep_original_format'))->toHaveExtension('PNG'); +}); - /** @test */ - public function it_can_keep_the_original_image_format_if_the_original_file_is_an_image_with_uppercase_extension() - { - $media = $this->testModelWithConversion->addMedia($this->getUppercaseExtensionTestPng())->toMediaCollection(); +it('always defaults to jpg when the original file is not an image', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestMp4())->toMediaCollection(); - $this->assertExtensionEquals('PNG', $media->getUrl('keep_original_format')); - } - - /** @test */ - public function it_always_defaults_to_jpg_when_the_original_file_is_not_an_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestMp4())->toMediaCollection(); - - $this->assertExtensionEquals('jpg', $media->getUrl('thumb')); - $this->assertExtensionEquals('jpg', $media->getUrl('keep_original_format')); - } - - private function assertExtensionEquals(string $expectedExtension, string $file) - { - $actualExtension = pathinfo($file, PATHINFO_EXTENSION); - - $this->assertEquals($expectedExtension, $actualExtension); - } -} + expect($media->getUrl('thumb'))->toHaveExtension('jpg'); + expect($media->getUrl('keep_original_format'))->toHaveExtension('jpg'); +}); diff --git a/tests/Conversions/ConversionFileNamerTest.php b/tests/Conversions/ConversionFileNamerTest.php index 6d2d1c27a..62c0ab2c6 100644 --- a/tests/Conversions/ConversionFileNamerTest.php +++ b/tests/Conversions/ConversionFileNamerTest.php @@ -1,29 +1,21 @@ set("media-library.file_namer", TestFileNamer::class); + config()->set("media-library.file_namer", TestFileNamer::class); - $this - ->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); + $this + ->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $path = $this->testModelWithConversion->refresh()->getFirstMediaPath("default", "thumb"); + $path = $this->testModelWithConversion->refresh()->getFirstMediaPath("default", "thumb"); - $this->assertStringEndsWith("{$this->fileName}---thumb.jpg", $path); - $this->assertFileExists($path); + expect($path)->toEndWith("{$fileName}---thumb.jpg"); + expect($path)->toBeFile(); - $this->assertEquals("/media/1/conversions/{$this->fileName}---thumb.jpg", $this->testModelWithConversion->getFirstMediaUrl("default", "thumb")); - } -} + expect($this->testModelWithConversion->getFirstMediaUrl("default", "thumb"))->toEqual("/media/1/conversions/{$fileName}---thumb.jpg"); +}); diff --git a/tests/Conversions/ConversionTest.php b/tests/Conversions/ConversionTest.php index 171be0457..aff29838d 100644 --- a/tests/Conversions/ConversionTest.php +++ b/tests/Conversions/ConversionTest.php @@ -1,217 +1,165 @@ conversion = new Conversion($this->conversionName); - } - - /** @test */ - public function it_can_get_its_name() - { - $this->assertEquals($this->conversionName, $this->conversion->getName()); - } - - /** @test */ - public function it_will_add_a_format_parameter_if_it_was_not_given() - { - $this->conversion->width(10); - - $this->assertEquals('jpg', $this->conversion->getManipulations()->getManipulationArgument('format')); - } - - /** @test */ - public function it_will_use_the_format_parameter_if_it_was_given() - { - $this->conversion->format('png'); - - $this->assertEquals('png', $this->conversion->getManipulations()->getManipulationArgument('format')); - } - - /** @test */ - public function it_will_be_performed_on_the_given_collection_names() - { - $this->conversion->performOnCollections('images', 'downloads'); - $this->assertTrue($this->conversion->shouldBePerformedOn('images')); - $this->assertTrue($this->conversion->shouldBePerformedOn('downloads')); - $this->assertFalse($this->conversion->shouldBePerformedOn('unknown')); - } - - /** @test */ - public function it_will_be_performed_on_all_collections_if_not_collection_names_are_set() - { - $this->conversion->performOnCollections('*'); - $this->assertTrue($this->conversion->shouldBePerformedOn('images')); - $this->assertTrue($this->conversion->shouldBePerformedOn('downloads')); - $this->assertTrue($this->conversion->shouldBePerformedOn('unknown')); - } - - /** @test */ - public function it_will_be_performed_on_all_collections_if_not_collection_name_is_a_star() - { - $this->assertTrue($this->conversion->shouldBePerformedOn('images')); - $this->assertTrue($this->conversion->shouldBePerformedOn('downloads')); - $this->assertTrue($this->conversion->shouldBePerformedOn('unknown')); - } - - /** @test */ - public function it_will_be_queued_without_config() - { - config()->set('media-library.queue_conversions_by_default', null); - $this->assertTrue($this->conversion->shouldBeQueued()); - } - - /** @test */ - public function it_will_be_queued_by_default() - { - config()->set('media-library.queue_conversions_by_default', true); - $this->assertTrue($this->conversion->shouldBeQueued()); - } - - /** @test */ - public function it_will_be_nonQueued_by_default() - { - config()->set('media-library.queue_conversions_by_default', false); - $this->assertTrue($this->conversion->shouldBeQueued()); - } - - /** @test */ - public function it_can_be_set_to_queued() - { - config()->set('media-library.queue_conversions_by_default', false); - $this->assertTrue($this->conversion->queued()->shouldBeQueued()); - } - - /** @test */ - public function it_can_be_set_to_nonQueued() - { - config()->set('media-library.queue_conversions_by_default', true); - $this->assertFalse($this->conversion->nonQueued()->shouldBeQueued()); - } - - /** @test */ - public function it_can_determine_the_extension_of_the_result() - { - $this->conversion->width(50); - - $this->assertEquals('jpg', $this->conversion->getResultExtension()); - - $this->conversion->width(100)->format('png'); - - $this->assertEquals('png', $this->conversion->getResultExtension()); - } - - /** @test */ - public function it_can_remove_a_previously_set_manipulation() - { - $this->assertEquals('jpg', $this->conversion->getManipulations()->getManipulationArgument('format')); - - $this->conversion->removeManipulation('format'); - - $this->assertNull($this->conversion->getManipulations()->getManipulationArgument('format')); - } - - /** @test */ - public function it_can_remove_all_previously_set_manipulations() - { - $this->assertFalse($this->conversion->getManipulations()->isEmpty()); - - $this->conversion->withoutManipulations(); - - $this->assertTrue($this->conversion->getManipulations()->isEmpty()); - } - - /** @test */ - public function it_will_use_the_extract_duration_parameter_if_it_was_given() - { - $this->conversion->extractVideoFrameAtSecond(10); - - $this->assertEquals(10, $this->conversion->getExtractVideoFrameAtSecond()); - } - - /** @test */ - public function manipulations_can_be_set_using_an_instance_of_manipulations() - { - $this->conversion->setManipulations((new Manipulations())->width(10)); - - $manipulations = $this->conversion - ->getManipulations() - ->getManipulationSequence() - ->toArray(); - - $this->assertArrayHasKey('optimize', $manipulations[0]); - - unset($manipulations[0]['optimize']); - - $this->assertEquals([[ - 'width' => 10, - 'format' => 'jpg', - ]], $manipulations); - } - - /** @test */ - public function manipulations_can_be_set_using_a_closure() - { - $this->conversion->setManipulations(function (Manipulations $manipulations) { - $manipulations->width(10); - }); - - $manipulations = $this->conversion - ->getManipulations() - ->getManipulationSequence() - ->toArray(); - - $this->assertArrayHasKey('optimize', $manipulations[0]); - - unset($manipulations[0]['optimize']); - - $this->assertEquals([[ - 'width' => 10, - 'format' => 'jpg', - ]], $manipulations); - } - - /** @test */ - public function it_will_optimize_the_converted_image_by_default() - { - $manipulations = (new Conversion('test')) - ->getManipulations() - ->getManipulationSequence() - ->toArray(); - - $this->assertArrayHasKey('optimize', $manipulations[0]); - } - - /** @test */ - public function it_can_remove_the_optimization() - { - $manipulations = (new Conversion('test')) - ->nonOptimized() - ->getManipulations() - ->getManipulationSequence() - ->toArray(); - - $this->assertArrayNotHasKey('optimize', $manipulations[0]); - } - /** @test */ - public function it_will_use_the_pdf_page_number_parameter_if_it_was_given() - { - $this->conversion->pdfPageNumber(10); - - $this->assertEquals(10, $this->conversion->getPdfPageNumber()); - } -} +beforeEach(function () { + $this->conversionName = 'test'; + $this->conversion = new Conversion($this->conversionName); +}); + +it('can get its name', function () { + expect($this->conversion->getName())->toEqual($this->conversionName); +}); + +it('will add a format parameter if it was not given', function () { + $this->conversion->width(10); + + expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual('jpg'); +}); + +it('will use the format parameter if it was given', function () { + $this->conversion->format('png'); + + expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual('png'); +}); + +it('will be performed on the given collection names', function () { + $this->conversion->performOnCollections('images', 'downloads'); + expect($this->conversion->shouldBePerformedOn('images'))->toBeTrue(); + expect($this->conversion->shouldBePerformedOn('downloads'))->toBeTrue(); + expect($this->conversion->shouldBePerformedOn('unknown'))->toBeFalse(); +}); + +it('will be performed on all collections if not collection names are set', function () { + $this->conversion->performOnCollections('*'); + expect($this->conversion->shouldBePerformedOn('images'))->toBeTrue(); + expect($this->conversion->shouldBePerformedOn('downloads'))->toBeTrue(); + expect($this->conversion->shouldBePerformedOn('unknown'))->toBeTrue(); +}); + +it('will be performed on all collections if not collection name is a star', function () { + expect($this->conversion->shouldBePerformedOn('images'))->toBeTrue(); + expect($this->conversion->shouldBePerformedOn('downloads'))->toBeTrue(); + expect($this->conversion->shouldBePerformedOn('unknown'))->toBeTrue(); +}); + +it('will be queued without config', function () { + config()->set('media-library.queue_conversions_by_default', null); + expect($this->conversion->shouldBeQueued())->toBeTrue(); +}); + +it('will be queued by default', function () { + config()->set('media-library.queue_conversions_by_default', true); + expect($this->conversion->shouldBeQueued())->toBeTrue(); +}); + +it('will be non queued by default', function () { + config()->set('media-library.queue_conversions_by_default', false); + expect($this->conversion->shouldBeQueued())->toBeTrue(); +}); + +it('can be set to queued', function () { + config()->set('media-library.queue_conversions_by_default', false); + expect($this->conversion->queued()->shouldBeQueued())->toBeTrue(); +}); + +it('can be set to non queued', function () { + config()->set('media-library.queue_conversions_by_default', true); + expect($this->conversion->nonQueued()->shouldBeQueued())->toBeFalse(); +}); + +it('can determine the extension of the result', function () { + $this->conversion->width(50); + + expect($this->conversion->getResultExtension())->toEqual('jpg'); + + $this->conversion->width(100)->format('png'); + + expect($this->conversion->getResultExtension())->toEqual('png'); +}); + +it('can remove a previously set manipulation', function () { + expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual('jpg'); + + $this->conversion->removeManipulation('format'); + + expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toBeNull(); +}); + +it('can remove all previously set manipulations', function () { + expect($this->conversion->getManipulations()->isEmpty())->toBeFalse(); + + $this->conversion->withoutManipulations(); + + expect($this->conversion->getManipulations()->isEmpty())->toBeTrue(); +}); + +it('will use the extract duration parameter if it was given', function () { + $this->conversion->extractVideoFrameAtSecond(10); + + expect($this->conversion->getExtractVideoFrameAtSecond())->toEqual(10); +}); + +test('manipulations can be set using an instance of manipulations', function () { + $this->conversion->setManipulations((new Manipulations())->width(10)); + + $manipulations = $this->conversion + ->getManipulations() + ->getManipulationSequence() + ->toArray(); + + $this->assertArrayHasKey('optimize', $manipulations[0]); + + unset($manipulations[0]['optimize']); + + $this->assertEquals([[ + 'width' => 10, + 'format' => 'jpg', + ]], $manipulations); +}); + +test('manipulations can be set using a closure', function () { + $this->conversion->setManipulations(function (Manipulations $manipulations) { + $manipulations->width(10); + }); + + $manipulations = $this->conversion + ->getManipulations() + ->getManipulationSequence() + ->toArray(); + + $this->assertArrayHasKey('optimize', $manipulations[0]); + + unset($manipulations[0]['optimize']); + + $this->assertEquals([[ + 'width' => 10, + 'format' => 'jpg', + ]], $manipulations); +}); + +it('will optimize the converted image by default', function () { + $manipulations = (new Conversion('test')) + ->getManipulations() + ->getManipulationSequence() + ->toArray(); + + $this->assertArrayHasKey('optimize', $manipulations[0]); +}); + +it('can remove the optimization', function () { + $manipulations = (new Conversion('test')) + ->nonOptimized() + ->getManipulations() + ->getManipulationSequence() + ->toArray(); + + $this->assertArrayNotHasKey('optimize', $manipulations[0]); +}); + +it('will use the pdf page number parameter if it was given', function () { + $this->conversion->pdfPageNumber(10); + + expect($this->conversion->getPdfPageNumber())->toEqual(10); +}); diff --git a/tests/Conversions/EventTest.php b/tests/Conversions/EventTest.php index 70d613ddb..ac93051dc 100644 --- a/tests/Conversions/EventTest.php +++ b/tests/Conversions/EventTest.php @@ -1,48 +1,33 @@ testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - - Event::assertDispatched(ConversionWillStart::class); - } - - /** @test */ - public function it_will_fire_the_conversion_complete_event() - { - $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - - Event::assertDispatched(ConversionHasBeenCompleted::class); - } - - /** @test */ - public function it_will_fire_the_collection_cleared_event() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('images'); - - $this->testModel->clearMediaCollection('images'); - - Event::assertDispatched(CollectionHasBeenCleared::class); - } -} + +beforeEach(function () { + Event::fake(); +}); + +it('will fire the conversion will start event', function () { + $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); + + Event::assertDispatched(ConversionWillStart::class); +}); + +it('will fire the conversion complete event', function () { + $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); + + Event::assertDispatched(ConversionHasBeenCompleted::class); +}); + +it('will fire the collection cleared event', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('images'); + + $this->testModel->clearMediaCollection('images'); + + Event::assertDispatched(CollectionHasBeenCleared::class); +}); diff --git a/tests/Conversions/FileManipulatorTest.php b/tests/Conversions/FileManipulatorTest.php index 277b5e2d5..1be31d357 100644 --- a/tests/Conversions/FileManipulatorTest.php +++ b/tests/Conversions/FileManipulatorTest.php @@ -1,36 +1,22 @@ conversion = new Conversion($this->conversionName); - } +beforeEach(function () { + $this->conversionName = 'test'; + $this->conversion = new Conversion($this->conversionName); +}); - /** @test */ - public function it_does_not_perform_manipulations_if_not_necessary() - { - $imageFile = $this->getTestJpg(); - $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection(); +it('does not perform manipulations if not necessary', function () { + $imageFile = $this->getTestJpg(); + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection(); - $conversionTempFile = (new PerformManipulationsAction())->execute( - $media, - $this->conversion->withoutManipulations(), - $imageFile - ); + $conversionTempFile = (new PerformManipulationsAction())->execute( + $media, + $this->conversion->withoutManipulations(), + $imageFile + ); - $this->assertEquals($imageFile, $conversionTempFile); - } -} + expect($conversionTempFile)->toEqual($imageFile); +}); diff --git a/tests/Conversions/ImageGenerators/DualTypeCheckingTest.php b/tests/Conversions/ImageGenerators/DualTypeCheckingTest.php index a51d0d05b..8ce7d51f4 100644 --- a/tests/Conversions/ImageGenerators/DualTypeCheckingTest.php +++ b/tests/Conversions/ImageGenerators/DualTypeCheckingTest.php @@ -1,74 +1,60 @@ shouldMatchBothExtensionsAndMimeTypes = true; +it('can convert an image with a valid extension and mime type', function () { + $generator = new TestImageGenerator(); + $generator->shouldMatchBothExtensionsAndMimeTypes = true; - $generator->supportedMimetypes->push('supported-mime-type'); - $generator->supportedExtensions->push('supported-extension'); + $generator->supportedMimetypes->push('supported-mime-type'); + $generator->supportedExtensions->push('supported-extension'); - $media = new Media(); - $media->mime_type = 'supported-mime-type'; - $media->file_name = 'some-file.supported-extension'; + $media = new Media(); + $media->mime_type = 'supported-mime-type'; + $media->file_name = 'some-file.supported-extension'; - $this->assertTrue($generator->canConvert($media)); - } + expect($generator->canConvert($media))->toBeTrue(); +}); - /** @test */ - public function it_cannot_convert_an_image_with_an_invalid_extension_and_mime_type() - { - $generator = new TestImageGenerator(); - $generator->shouldMatchBothExtensionsAndMimeTypes = true; +it('cannot convert an image with an invalid extension and mime type', function () { + $generator = new TestImageGenerator(); + $generator->shouldMatchBothExtensionsAndMimeTypes = true; - $generator->supportedMimetypes->push('supported-mime-type'); - $generator->supportedExtensions->push('supported-extension'); + $generator->supportedMimetypes->push('supported-mime-type'); + $generator->supportedExtensions->push('supported-extension'); - $media = new Media(); - $media->mime_type = 'invalid-mime-type'; - $media->file_name = 'some-file.invalid-extension'; + $media = new Media(); + $media->mime_type = 'invalid-mime-type'; + $media->file_name = 'some-file.invalid-extension'; - $this->assertFalse($generator->canConvert($media)); - } + expect($generator->canConvert($media))->toBeFalse(); +}); - /** @test */ - public function it_cannot_convert_an_image_with_only_a_valid_mime_type() - { - $generator = new TestImageGenerator(); - $generator->shouldMatchBothExtensionsAndMimeTypes = true; +it('cannot convert an image with only a valid mime type', function () { + $generator = new TestImageGenerator(); + $generator->shouldMatchBothExtensionsAndMimeTypes = true; - $generator->supportedMimetypes->push('supported-mime-type'); - $generator->supportedExtensions->push('supported-extension'); + $generator->supportedMimetypes->push('supported-mime-type'); + $generator->supportedExtensions->push('supported-extension'); - $media = new Media(); - $media->mime_type = 'supported-mime-type'; - $media->file_name = 'some-file.invalid-extension'; + $media = new Media(); + $media->mime_type = 'supported-mime-type'; + $media->file_name = 'some-file.invalid-extension'; - $this->assertFalse($generator->canConvert($media)); - } + expect($generator->canConvert($media))->toBeFalse(); +}); - /** @test */ - public function it_cannot_convert_an_image_with_only_a_valid_extension() - { - $generator = new TestImageGenerator(); - $generator->shouldMatchBothExtensionsAndMimeTypes = true; +it('cannot convert an image with only a valid extension', function () { + $generator = new TestImageGenerator(); + $generator->shouldMatchBothExtensionsAndMimeTypes = true; - $generator->supportedExtensions->push('supported-extension'); - $generator->supportedMimetypes->push('supported-mime-type'); + $generator->supportedExtensions->push('supported-extension'); + $generator->supportedMimetypes->push('supported-mime-type'); - $media = new Media(); - $media->mime_type = 'invalid-mime-type'; - $media->file_name = 'some-file.supported-extension'; + $media = new Media(); + $media->mime_type = 'invalid-mime-type'; + $media->file_name = 'some-file.supported-extension'; - $this->assertFalse($generator->canConvert($media)); - } -} + expect($generator->canConvert($media))->toBeFalse(); +}); diff --git a/tests/Conversions/ImageGenerators/ImageTest.php b/tests/Conversions/ImageGenerators/ImageTest.php index 24b63a399..393f05416 100644 --- a/tests/Conversions/ImageGenerators/ImageTest.php +++ b/tests/Conversions/ImageGenerators/ImageTest.php @@ -1,24 +1,16 @@ testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection(); + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertTrue($imageGenerator->canConvert($media)); + expect($imageGenerator->canConvert($media))->toBeTrue(); - $imageFile = $imageGenerator->convert($media->getPath()); + $imageFile = $imageGenerator->convert($media->getPath()); - $this->assertEquals('image/jpeg', mime_content_type($imageFile)); - $this->assertEquals($imageFile, $media->getPath()); - } -} + expect(mime_content_type($imageFile))->toEqual('image/jpeg'); + expect($media->getPath())->toEqual($imageFile); +}); diff --git a/tests/Conversions/ImageGenerators/PdfTest.php b/tests/Conversions/ImageGenerators/PdfTest.php index e10496c4e..60dc1b0d5 100644 --- a/tests/Conversions/ImageGenerators/PdfTest.php +++ b/tests/Conversions/ImageGenerators/PdfTest.php @@ -1,27 +1,19 @@ requirementsAreInstalled()) { - $this->markTestSkipped('Skipping pdf test because requirements to run it are not met'); - } + if (! $imageGenerator->requirementsAreInstalled()) { + $this->markTestSkipped('Skipping pdf test because requirements to run it are not met'); + } - $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestPdf())->toMediaCollection(); + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestPdf())->toMediaCollection(); - $this->assertTrue($imageGenerator->canConvert($media)); + expect($imageGenerator->canConvert($media))->toBeTrue(); - $imageFile = $imageGenerator->convert($media->getPath()); + $imageFile = $imageGenerator->convert($media->getPath()); - $this->assertEquals('image/jpeg', mime_content_type($imageFile)); - } -} + expect(mime_content_type($imageFile))->toEqual('image/jpeg'); +}); diff --git a/tests/Conversions/ImageGenerators/SvgTest.php b/tests/Conversions/ImageGenerators/SvgTest.php index 9eb6ed21f..23144d8e0 100644 --- a/tests/Conversions/ImageGenerators/SvgTest.php +++ b/tests/Conversions/ImageGenerators/SvgTest.php @@ -1,27 +1,19 @@ requirementsAreInstalled()) { - $this->markTestSkipped('Skipping svg test because requirements to run it are not met'); - } + if (! $imageGenerator->requirementsAreInstalled()) { + $this->markTestSkipped('Skipping svg test because requirements to run it are not met'); + } - $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestSvg())->toMediaCollection(); + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestSvg())->toMediaCollection(); - $this->assertTrue($imageGenerator->canConvert($media)); + expect($imageGenerator->canConvert($media))->toBeTrue(); - $imageFile = $imageGenerator->convert($media->getPath()); + $imageFile = $imageGenerator->convert($media->getPath()); - $this->assertEquals('image/jpeg', mime_content_type($imageFile)); - } -} + expect(mime_content_type($imageFile))->toEqual('image/jpeg'); +}); diff --git a/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php b/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php index 81bb7ddff..a2626f21b 100644 --- a/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php +++ b/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php @@ -1,43 +1,33 @@ set('media-library.image_generators', [ - TestImageGeneratorWithConfig::class => ['firstName' => 'firstValue', 'secondName' => 'secondValue'], - ]); +test('image generators can get parameter from the config file', function () { + config()->set('media-library.image_generators', [ + TestImageGeneratorWithConfig::class => ['firstName' => 'firstValue', 'secondName' => 'secondValue'], + ]); - $imageGenerators = ImageGeneratorFactory::getImageGenerators(); + $imageGenerators = ImageGeneratorFactory::getImageGenerators(); - $testGeneratorWithConfig = $imageGenerators->first(); + $testGeneratorWithConfig = $imageGenerators->first(); - $this->assertInstanceOf(TestImageGeneratorWithConfig::class, $testGeneratorWithConfig); + expect($testGeneratorWithConfig)->toBeInstanceOf(TestImageGeneratorWithConfig::class); - $this->assertEquals('firstValue', $testGeneratorWithConfig->firstName); - $this->assertEquals('secondValue', $testGeneratorWithConfig->secondName); - } + expect($testGeneratorWithConfig->firstName)->toEqual('firstValue'); + expect($testGeneratorWithConfig->secondName)->toEqual('secondValue'); +}); - /** @test */ - public function image_generators_will_receive_config_parameters_by_name() - { - config()->set('media-library.image_generators', [ - TestImageGeneratorWithConfig::class => ['secondName' => 'secondValue', 'firstName' => 'firstValue', ], - ]); +test('image generators will receive config parameters by name', function () { + config()->set('media-library.image_generators', [ + TestImageGeneratorWithConfig::class => ['secondName' => 'secondValue', 'firstName' => 'firstValue', ], + ]); - $imageGenerators = ImageGeneratorFactory::getImageGenerators(); + $imageGenerators = ImageGeneratorFactory::getImageGenerators(); - $testGeneratorWithConfig = $imageGenerators->first(); + $testGeneratorWithConfig = $imageGenerators->first(); - $this->assertInstanceOf(TestImageGeneratorWithConfig::class, $testGeneratorWithConfig); - $this->assertEquals('firstValue', $testGeneratorWithConfig->firstName); - $this->assertEquals('secondValue', $testGeneratorWithConfig->secondName); - } -} + expect($testGeneratorWithConfig)->toBeInstanceOf(TestImageGeneratorWithConfig::class); + expect($testGeneratorWithConfig->firstName)->toEqual('firstValue'); + expect($testGeneratorWithConfig->secondName)->toEqual('secondValue'); +}); diff --git a/tests/Conversions/ImageGenerators/VideoTest.php b/tests/Conversions/ImageGenerators/VideoTest.php index 7e8c3f5ff..64b0b01ca 100644 --- a/tests/Conversions/ImageGenerators/VideoTest.php +++ b/tests/Conversions/ImageGenerators/VideoTest.php @@ -1,30 +1,22 @@ requirementsAreInstalled()) { - $this->markTestSkipped('Skipping video test because requirements to run it are not met'); - } + if (! $imageGenerator->requirementsAreInstalled()) { + $this->markTestSkipped('Skipping video test because requirements to run it are not met'); + } - $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestWebm())->toMediaCollection(); + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestWebm())->toMediaCollection(); - $this->assertTrue($imageGenerator->canConvert($media)); + expect($imageGenerator->canConvert($media))->toBeTrue(); - $imageFile = $imageGenerator->convert($media->getPath(), new Conversion('test')); + $imageFile = $imageGenerator->convert($media->getPath(), new Conversion('test')); - $this->assertEquals('image/jpeg', mime_content_type($imageFile)); + expect(mime_content_type($imageFile))->toEqual('image/jpeg'); - $this->assertEquals($imageFile, str_replace('.webm', '.jpg', $media->getPath())); - } -} + expect(str_replace('.webm', '.jpg', $media->getPath()))->toEqual($imageFile); +}); diff --git a/tests/Conversions/ImageGenerators/WebpTest.php b/tests/Conversions/ImageGenerators/WebpTest.php index 7037f341b..f095961b1 100644 --- a/tests/Conversions/ImageGenerators/WebpTest.php +++ b/tests/Conversions/ImageGenerators/WebpTest.php @@ -1,27 +1,19 @@ requirementsAreInstalled()) { - $this->markTestSkipped('Skipping webp test because requirements to run it are not met'); - } + if (! $imageGenerator->requirementsAreInstalled()) { + $this->markTestSkipped('Skipping webp test because requirements to run it are not met'); + } - $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestWebp())->toMediaCollection(); + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestWebp())->toMediaCollection(); - $this->assertTrue($imageGenerator->canConvert($media)); + expect($imageGenerator->canConvert($media))->toBeTrue(); - $imageFile = $imageGenerator->convert($media->getPath()); + $imageFile = $imageGenerator->convert($media->getPath()); - $this->assertEquals('image/png', mime_content_type($imageFile)); - } -} + expect(mime_content_type($imageFile))->toEqual('image/png'); +}); diff --git a/tests/Feature/FileAdder/ConversionsDiskTest.php b/tests/Feature/FileAdder/ConversionsDiskTest.php index a96c2abdc..314190181 100644 --- a/tests/Feature/FileAdder/ConversionsDiskTest.php +++ b/tests/Feature/FileAdder/ConversionsDiskTest.php @@ -1,82 +1,69 @@ testModelWithConversion - ->addMedia($this->getTestJpg()) - ->storingConversionsOnDisk('secondMediaDisk') - ->toMediaCollection(); - - $this->assertEquals('public', $media->disk); - $this->assertEquals('secondMediaDisk', $media->conversions_disk); - - $this->assertEquals("/media/{$media->id}/test.jpg", $media->getUrl()); - $this->assertEquals("/media2/{$media->id}/conversions/test-thumb.jpg", $media->getUrl('thumb')); - - $originalFilePath = $media->getPath(); - - $this->assertEquals( - $this->getTestsPath('TestSupport/temp/media/1/test.jpg'), - $originalFilePath - ); - $this->assertFileExists($originalFilePath); - - $conversionsFilePath = $media->getPath('thumb'); - $this->assertEquals( - $this->getTestsPath('TestSupport/temp/media2/1/conversions/test-thumb.jpg'), - $conversionsFilePath - ); - $this->assertFileExists($conversionsFilePath); - } - - /** @test */ - public function the_responsive_images_will_get_saved_on_the_same_disk_as_the_conversions() - { - $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->storingConversionsOnDisk('secondMediaDisk') - ->toMediaCollection(); - - $this->assertFileExists($this->getTempDirectory('media2/1/responsive-images/test___thumb_50_41.jpg')); - } - - /** @test */ - public function deleting_media_will_also_delete_conversions_on_the_separate_disk() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->storingConversionsOnDisk('secondMediaDisk') - ->toMediaCollection(); - - $this->assertFileExists($media->getPath('thumb')); - - $media->delete(); - - $this->assertFileDoesNotExist($media->getPath('thumb')); - - $originalFilePath = $media->getPath(); - $this->assertFileDoesNotExist($originalFilePath); - } - - /** @test */ - public function it_will_store_the_conversion_on_the_disk_specified_in_on_the_media_collection() - { - $media = $this->testModelWithConversionsOnOtherDisk - ->addMedia($this->getTestJpg()) - ->toMediaCollection('thumb'); - - $conversionsFilePath = $media->getPath('thumb'); - $this->assertEquals( - $this->getTestsPath('TestSupport/temp/media2/1/conversions/test-thumb.jpg'), - $conversionsFilePath - ); - $this->assertFileExists($conversionsFilePath); - } -} + + +it('can save conversions on a separate disk', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->storingConversionsOnDisk('secondMediaDisk') + ->toMediaCollection(); + + expect($media->disk)->toEqual('public'); + expect($media->conversions_disk)->toEqual('secondMediaDisk'); + + expect($media->getUrl())->toEqual("/media/{$media->id}/test.jpg"); + expect($media->getUrl('thumb'))->toEqual("/media2/{$media->id}/conversions/test-thumb.jpg"); + + $originalFilePath = $media->getPath(); + + $this->assertEquals( + $this->getTestsPath('TestSupport/temp/media/1/test.jpg'), + $originalFilePath + ); + expect($originalFilePath)->toBeFile(); + + $conversionsFilePath = $media->getPath('thumb'); + $this->assertEquals( + $this->getTestsPath('TestSupport/temp/media2/1/conversions/test-thumb.jpg'), + $conversionsFilePath + ); + expect($conversionsFilePath)->toBeFile(); +}); + +test('the responsive images will get saved on the same disk as the conversions', function () { + $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->storingConversionsOnDisk('secondMediaDisk') + ->toMediaCollection(); + + expect($this->getTempDirectory('media2/1/responsive-images/test___thumb_50_41.jpg'))->toBeFile(); +}); + +test('deleting media will also delete conversions on the separate disk', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->storingConversionsOnDisk('secondMediaDisk') + ->toMediaCollection(); + + expect($media->getPath('thumb'))->toBeFile(); + + $media->delete(); + + $this->assertFileDoesNotExist($media->getPath('thumb')); + + $originalFilePath = $media->getPath(); + $this->assertFileDoesNotExist($originalFilePath); +}); + +it('will store the conversion on the disk specified in on the media collection', function () { + $media = $this->testModelWithConversionsOnOtherDisk + ->addMedia($this->getTestJpg()) + ->toMediaCollection('thumb'); + + $conversionsFilePath = $media->getPath('thumb'); + $this->assertEquals( + $this->getTestsPath('TestSupport/temp/media2/1/conversions/test-thumb.jpg'), + $conversionsFilePath + ); + expect($conversionsFilePath)->toBeFile(); +}); diff --git a/tests/Feature/FileAdder/IntegrationTest.php b/tests/Feature/FileAdder/IntegrationTest.php index 8fa071305..d4c2b2220 100644 --- a/tests/Feature/FileAdder/IntegrationTest.php +++ b/tests/Feature/FileAdder/IntegrationTest.php @@ -1,7 +1,5 @@ testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); +it('can add an file to the default collection', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $this->assertEquals('default', $media->collection_name); - } + expect($media->collection_name)->toEqual('default'); +}); - /** @test */ - public function toMediaCollection_has_an_alias_called_toMediaLibrary() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaLibrary(); +test('to media collection has an alias called to media library', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaLibrary(); - $this->assertEquals('default', $media->collection_name); - } + expect($media->collection_name)->toEqual('default'); +}); - /** @test */ - public function it_will_throw_an_exception_when_adding_a_non_existing_file() - { - $this->expectException(FileDoesNotExist::class); +it('will throw an exception when adding a non existing file', function () { + $this->expectException(FileDoesNotExist::class); - $this->testModel - ->addMedia('this-file-does-not-exist.jpg') - ->toMediaCollection(); - } + $this->testModel + ->addMedia('this-file-does-not-exist.jpg') + ->toMediaCollection(); +}); - /** @test */ - public function it_can_set_the_name_of_the_media() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); +it('can set the name of the media', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $this->assertEquals('test', $media->name); - } + expect($media->name)->toEqual('test'); +}); - /** @test */ - public function it_can_add_a_file_to_a_named_collection() - { - $collectionName = 'images'; +it('can add a file to a named collection', function () { + $collectionName = 'images'; - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection($collectionName); + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection($collectionName); - $this->assertEquals($collectionName, $media->collection_name); - } + expect($media->collection_name)->toEqual($collectionName); +}); - /** @test */ - public function it_can_move_the_original_file_to_the_media_library() - { - $testFile = $this->getTestJpg(); +it('can move the original file to the media library', function () { + $testFile = $this->getTestJpg(); - $media = $this->testModel - ->addMedia($testFile) - ->toMediaCollection(); + $media = $this->testModel + ->addMedia($testFile) + ->toMediaCollection(); - $this->assertFileDoesNotExist($testFile); - $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - } + $this->assertFileDoesNotExist($testFile); + $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); +}); - /** @test */ - public function it_can_copy_the_original_file_to_the_media_library() - { - $testFile = $this->getTestJpg(); +it('can copy the original file to the media library', function () { + $testFile = $this->getTestJpg(); - $media = $this->testModel - ->copyMedia($testFile) - ->toMediaCollection('images'); + $media = $this->testModel + ->copyMedia($testFile) + ->toMediaCollection('images'); - $this->assertFileExists($testFile); - $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - } + expect($testFile)->toBeFile(); + $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); +}); - /** @test */ - public function it_can_handle_a_file_without_an_extension() - { - $media = $this->testModel - ->addMedia($this->getTestFilesDirectory('test')) - ->toMediaCollection(); +it('can handle a file without an extension', function () { + $media = $this->testModel + ->addMedia($this->getTestFilesDirectory('test')) + ->toMediaCollection(); - $this->assertEquals('test', $media->name); + expect($media->name)->toEqual('test'); - $this->assertEquals('test', $media->file_name); + expect($media->file_name)->toEqual('test'); - $this->assertEquals("/media/{$media->id}/test", $media->getUrl()); + expect($media->getUrl())->toEqual("/media/{$media->id}/test"); - $this->assertFileExists($this->getMediaDirectory("/{$media->id}/test")); - } + expect($this->getMediaDirectory("/{$media->id}/test"))->toBeFile(); +}); - /** @test */ - public function it_can_handle_an_image_file_without_an_extension() - { - $media = $this->testModel - ->addMedia($this->getTestFilesDirectory('image')) - ->toMediaCollection(); +it('can handle an image file without an extension', function () { + $media = $this->testModel + ->addMedia($this->getTestFilesDirectory('image')) + ->toMediaCollection(); - $this->assertEquals('image', $media->type); - } + expect($media->type)->toEqual('image'); +}); - /** @test */ - public function it_can_handle_a_non_image_and_non_pdf_file() - { - $media = $this->testModel - ->addMedia($this->getTestFilesDirectory('test.txt')) - ->toMediaCollection(); +it('can handle a non image and non pdf file', function () { + $media = $this->testModel + ->addMedia($this->getTestFilesDirectory('test.txt')) + ->toMediaCollection(); - $this->assertEquals('test', $media->name); + expect($media->name)->toEqual('test'); - $this->assertEquals('test.txt', $media->file_name); + expect($media->file_name)->toEqual('test.txt'); - $this->assertEquals("/media/{$media->id}/test.txt", $media->getUrl()); + expect($media->getUrl())->toEqual("/media/{$media->id}/test.txt"); - $this->assertFileExists($this->getMediaDirectory("/{$media->id}/test.txt")); - } + expect($this->getMediaDirectory("/{$media->id}/test.txt"))->toBeFile(); +}); - /** @test */ - public function it_can_add_an_upload_to_the_media_library() - { - $uploadedFile = new UploadedFile( - $this->getTestFilesDirectory('test.jpg'), - 'alternativename.jpg', - 'image/jpeg', - filesize($this->getTestFilesDirectory('test.jpg')) - ); +it('can add an upload to the media library', function () { + $uploadedFile = new UploadedFile( + $this->getTestFilesDirectory('test.jpg'), + 'alternativename.jpg', + 'image/jpeg', + filesize($this->getTestFilesDirectory('test.jpg')) + ); + + $media = $this->testModel + ->addMedia($uploadedFile) + ->toMediaCollection(); + expect($media->name)->toEqual('alternativename'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); +}); + +it('can add an upload to the media library from the current request', function () { + app()['router']->get('/upload', function () { $media = $this->testModel - ->addMedia($uploadedFile) + ->addMediaFromRequest('file') ->toMediaCollection(); - $this->assertEquals('alternativename', $media->name); + expect($media->name)->toEqual('alternativename'); $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - } + }); - /** @test */ - public function it_can_add_an_upload_to_the_media_library_from_the_current_request() - { - $this->app['router']->get('/upload', function () { - $media = $this->testModel - ->addMediaFromRequest('file') - ->toMediaCollection(); + $fileUpload = new UploadedFile( + $this->getTestFilesDirectory('test.jpg'), + 'alternativename.jpg', + 'image/jpeg', + filesize($this->getTestFilesDirectory('test.jpg')) + ); + + $this->withoutExceptionHandling(); + + $result = $this->call('get', 'upload', [], [], ['file' => $fileUpload]); + + expect($result->getStatusCode())->toEqual(200); +}); + +it('can add multiple uploads to the media library from the current request', function () { + app()['router']->get('/upload', function () { + $fileAdders = collect( + $this->testModel + ->addMultipleMediaFromRequest(['file-1', 'file-2']) + ); - $this->assertEquals('alternativename', $media->name); + $fileAdders->each(function ($fileAdder) { + $media = $fileAdder->toMediaCollection(); + + expect($media->name)->toEqual('alternativename'); $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); }); - $fileUpload = new UploadedFile( - $this->getTestFilesDirectory('test.jpg'), + expect($fileAdders)->toHaveCount(2); + }); + + $uploadedFiles = [ + 'file-1' => new UploadedFile( + $this->getTestJpg(), 'alternativename.jpg', 'image/jpeg', - filesize($this->getTestFilesDirectory('test.jpg')) + filesize($this->getTestJpg()) + ), + 'file-2' => new UploadedFile( + $this->getTestSvg(), + 'alternativename.svg', + 'image/svg', + filesize($this->getTestSvg()) + ), + ]; + + $result = $this->call('get', 'upload', [], [], $uploadedFiles); + + expect($result->getStatusCode())->toEqual(200); +}); + +it('can add handle file keys that contain an array to the media library from the current request', function () { + app()['router']->get('/upload', function () { + $fileAdders = collect( + $this->testModel->addAllMediaFromRequest() ); - $this->withoutExceptionHandling(); - - $result = $this->call('get', 'upload', [], [], ['file' => $fileUpload]); - - $this->assertEquals(200, $result->getStatusCode()); - } - - /** @test */ - public function it_can_add_multiple_uploads_to_the_media_library_from_the_current_request() - { - $this->app['router']->get('/upload', function () { - $fileAdders = collect( - $this->testModel - ->addMultipleMediaFromRequest(['file-1', 'file-2']) - ); + $fileAdders->each(function ($fileAdder) { + $fileAdder = is_array($fileAdder) ? $fileAdder : [$fileAdder]; - $fileAdders->each(function ($fileAdder) { - $media = $fileAdder->toMediaCollection(); + foreach ($fileAdder as $item) { + $media = $item->toMediaCollection(); - $this->assertEquals('alternativename', $media->name); + expect($media->name)->toEqual('alternativename'); $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - }); - - $this->assertCount(2, $fileAdders); + } }); - $uploadedFiles = [ - 'file-1' => new UploadedFile( - $this->getTestJpg(), - 'alternativename.jpg', - 'image/jpeg', - filesize($this->getTestJpg()) + expect($fileAdders)->toHaveCount(4); + }); + + $uploadedFiles = [ + 'file-1' => new UploadedFile( + $this->getTestJpg(), + 'alternativename.jpg', + 'image/jpeg', + filesize($this->getTestJpg()) + ), + 'file-2' => new UploadedFile( + $this->getTestSvg(), + 'alternativename.svg', + 'image/svg', + filesize($this->getTestSvg()) + ), + 'medias' => [ + new UploadedFile( + $this->getTestPng(), + 'alternativename.png', + 'image/png', + filesize($this->getTestPng()) ), - 'file-2' => new UploadedFile( - $this->getTestSvg(), - 'alternativename.svg', - 'image/svg', - filesize($this->getTestSvg()) + new UploadedFile( + $this->getTestWebm(), + 'alternativename.webm', + 'video/webm', + filesize($this->getTestWebm()) ), - ]; + ], + ]; - $result = $this->call('get', 'upload', [], [], $uploadedFiles); + $result = $this->call('get', 'upload', [], [], $uploadedFiles); - $this->assertEquals(200, $result->getStatusCode()); - } + expect($result->getStatusCode())->toEqual(200); +}); - /** @test */ - public function it_can_add_handle_file_keys_that_contain_an_array_to_the_media_library_from_the_current_request() - { - $this->app['router']->get('/upload', function () { - $fileAdders = collect( - $this->testModel->addAllMediaFromRequest() - ); +it('will throw an exception when trying to add a non existing key from a request', function () { + app()['router']->get('/upload', function () { + $exceptionWasThrown = false; - $fileAdders->each(function ($fileAdder) { - $fileAdder = is_array($fileAdder) ? $fileAdder : [$fileAdder]; + try { + $this->testModel + ->addMediaFromRequest('non existing key') + ->toMediaCollection(); + } catch (RequestDoesNotHaveFile) { + $exceptionWasThrown = true; + } - foreach ($fileAdder as $item) { - $media = $item->toMediaCollection(); + expect($exceptionWasThrown)->toBeTrue(); + }); - $this->assertEquals('alternativename', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - } - }); + $this->call('get', 'upload'); +}); - $this->assertCount(4, $fileAdders); - }); +it('can add a remote file to the media library', function () { + $url = 'https://spatie.be/docs/laravel-medialibrary/v9/images/header.jpg'; - $uploadedFiles = [ - 'file-1' => new UploadedFile( - $this->getTestJpg(), - 'alternativename.jpg', - 'image/jpeg', - filesize($this->getTestJpg()) - ), - 'file-2' => new UploadedFile( - $this->getTestSvg(), - 'alternativename.svg', - 'image/svg', - filesize($this->getTestSvg()) - ), - 'medias' => [ - new UploadedFile( - $this->getTestPng(), - 'alternativename.png', - 'image/png', - filesize($this->getTestPng()) - ), - new UploadedFile( - $this->getTestWebm(), - 'alternativename.webm', - 'video/webm', - filesize($this->getTestWebm()) - ), - ], - ]; - - $result = $this->call('get', 'upload', [], [], $uploadedFiles); - - $this->assertEquals(200, $result->getStatusCode()); - } + $media = $this->testModel + ->addMediaFromUrl($url) + ->toMediaCollection(); - /** @test */ - public function it_will_throw_an_exception_when_trying_to_add_a_non_existing_key_from_a_request() - { - $this->app['router']->get('/upload', function () { - $exceptionWasThrown = false; - - try { - $this->testModel - ->addMediaFromRequest('non existing key') - ->toMediaCollection(); - } catch (RequestDoesNotHaveFile $exception) { - $exceptionWasThrown = true; - } + expect($media->name)->toEqual('header'); + expect($this->getMediaDirectory("{$media->id}/header.jpg"))->toBeFile(); +}); - $this->assertTrue($exceptionWasThrown); - }); +it('will not add local files when an url is expected', function () { + $this->expectException(InvalidUrl::class); - $this->call('get', 'upload'); - } + $this->testModel + ->addMediaFromUrl(__FILE__) + ->toMediaCollection(); +}); - /** @test */ - public function it_can_add_a_remote_file_to_the_media_library() - { - $url = 'https://spatie.be/docs/laravel-medialibrary/v9/images/header.jpg'; +it('can add a file from a separate disk to the media library', function () { + Storage::disk('secondMediaDisk')->put('tmp/test.jpg', file_get_contents($this->getTestJpg())); - $media = $this->testModel - ->addMediaFromUrl($url) - ->toMediaCollection(); + $media = $this->testModel + ->addMediaFromDisk('tmp/test.jpg', 'secondMediaDisk') + ->toMediaCollection(); - $this->assertEquals('header', $media->name); - $this->assertFileExists($this->getMediaDirectory("{$media->id}/header.jpg")); - } + expect($this->getMediaDirectory("{$media->id}/test.jpg"))->toBeFile(); +}); - /** @test */ - public function it_will_not_add_local_files_when_an_url_is_expected() - { - $this->expectException(InvalidUrl::class); +it('can natively copy a remote file from the same disk to the media library', function () { + Storage::disk('public')->put('tmp/test.jpg', file_get_contents($this->getTestJpg())); + expect($this->getMediaDirectory('tmp/test.jpg'))->toBeFile(); - $this->testModel - ->addMediaFromUrl(__FILE__) - ->toMediaCollection(); - } + $media = $this->testModel + ->addMediaFromDisk('tmp/test.jpg', 'public') + ->toMediaCollection(); - /** @test */ - public function it_can_add_a_file_from_a_separate_disk_to_the_media_library() - { - Storage::disk('secondMediaDisk')->put('tmp/test.jpg', file_get_contents($this->getTestJpg())); + expect($this->getMediaDirectory("{$media->id}/test.jpg"))->toBeFile(); + $this->assertFileDoesNotExist($this->getMediaDirectory('tmp/test.jpg')); +}); - $media = $this->testModel - ->addMediaFromDisk('tmp/test.jpg', 'secondMediaDisk') - ->toMediaCollection(); +it('can add a remote file with a space in the name to the media library', function () { + $url = 'http://spatie.github.io/laravel-medialibrary/tests/TestSupport/testfiles/test%20with%20space.jpg'; - $this->assertFileExists($this->getMediaDirectory("{$media->id}/test.jpg")); - } + $media = $this->testModel + ->addMediaFromUrl($url) + ->toMediaCollection(); - /** @test */ - public function it_can_natively_copy_a_remote_file_from_the_same_disk_to_the_media_library() - { - Storage::disk('public')->put('tmp/test.jpg', file_get_contents($this->getTestJpg())); - $this->assertFileExists($this->getMediaDirectory('tmp/test.jpg')); - - $media = $this->testModel - ->addMediaFromDisk('tmp/test.jpg', 'public') - ->toMediaCollection(); - - $this->assertFileExists($this->getMediaDirectory("{$media->id}/test.jpg")); - $this->assertFileDoesNotExist($this->getMediaDirectory('tmp/test.jpg')); - } + expect($this->getMediaDirectory("{$media->id}/test-with-space.jpg"))->toBeFile(); +}); - /** @test */ - public function it_can_add_a_remote_file_with_a_space_in_the_name_to_the_media_library() - { - $url = 'http://spatie.github.io/laravel-medialibrary/tests/TestSupport/testfiles/test%20with%20space.jpg'; +it('can add a remote file with an accent in the name to the media library', function () { + $url = 'https://orbit.brightbox.com/v1/acc-jqzwj/Marquis-Leisure/reviews/images/000/000/898/original/Antar%C3%A8sThumb.jpg'; - $media = $this->testModel - ->addMediaFromUrl($url) - ->toMediaCollection(); + $media = $this->testModel + ->addMediaFromUrl($url) + ->toMediaCollection(); - $this->assertFileExists($this->getMediaDirectory("{$media->id}/test-with-space.jpg")); - } + expect($this->getMediaDirectory("{$media->id}/AntarèsThumb.jpg"))->toBeFile(); +}); - /** @test */ - public function it_can_add_a_remote_file_with_an_accent_in_the_name_to_the_media_library() - { - $url = 'https://orbit.brightbox.com/v1/acc-jqzwj/Marquis-Leisure/reviews/images/000/000/898/original/Antar%C3%A8sThumb.jpg'; +it('wil thrown an exception when a remote file could not be added', function () { + $url = 'https://docs.spatie.be/images/medialibrary/thisonedoesnotexist.jpg'; - $media = $this->testModel - ->addMediaFromUrl($url) - ->toMediaCollection(); + $this->expectException(UnreachableUrl::class); - $this->assertFileExists($this->getMediaDirectory("{$media->id}/AntarèsThumb.jpg")); - } + $this->testModel + ->addMediaFromUrl($url) + ->toMediaCollection(); +}); - /** @test */ - public function it_wil_thrown_an_exception_when_a_remote_file_could_not_be_added() - { - $url = 'https://docs.spatie.be/images/medialibrary/thisonedoesnotexist.jpg'; +it('wil throw an exception when a remote file has an invalid mime type', function () { + $url = 'https://spatie.be/docs/laravel-medialibrary/v9/images/header.jpg'; - $this->expectException(UnreachableUrl::class); + $this->expectException(MimeTypeNotAllowed::class); - $this->testModel - ->addMediaFromUrl($url) - ->toMediaCollection(); - } + $this->testModel + ->addMediaFromUrl($url, ['image/png']) + ->toMediaCollection(); +}); - /** @test */ - public function it_wil_throw_an_exception_when_a_remote_file_has_an_invalid_mime_type() - { - $url = 'https://spatie.be/docs/laravel-medialibrary/v9/images/header.jpg'; +it('can rename the media before it gets added', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->usingName('othername') + ->toMediaCollection(); - $this->expectException(MimeTypeNotAllowed::class); + expect($media->name)->toEqual('othername'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); +}); - $this->testModel - ->addMediaFromUrl($url, ['image/png']) - ->toMediaCollection(); - } +it('can rename the file before it gets added', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->usingFileName('othertest.jpg') + ->toMediaCollection(); - /** @test */ - public function it_can_rename_the_media_before_it_gets_added() - { - $media = $this->testModel + expect($media->name)->toEqual('test'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/othertest.jpg')); +}); + +it('will remove strange characters from the file name', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->usingFileName('other#test.jpg') + ->toMediaCollection(); + + expect($media->name)->toEqual('test'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/other-test.jpg')); +}); + +it('will sanitize the file name using callable', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->sanitizingFileName(fn ($fileName) => 'new_file_name.jpg') + ->toMediaCollection(); + + expect($media->name)->toEqual('test'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/new_file_name.jpg')); +}); + +test('the file name can be modified using a file namer', function () { + config()->set('media-library.file_namer', RenameOriginalFileNamer::class); + + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); + + expect($media->name)->toEqual('test'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/renamed_original_file.jpg')); +}); + +test('the file name can be modified using custom sanitizing and default file namer', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->usingFileName('other/otherFileName.jpg') + ->sanitizingFileName(fn ($fileName) => strtolower(str_replace(['#', '\\', ' '], '-', $fileName))) + ->toMediaCollection(); + + expect($media->name)->toEqual('test'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/other/otherfilename.jpg')); +}); + +test('the file name can be modified using custom sanitizing and default file namer and especial chars', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->usingFileName('other/[0]-{0}-(0)-otherFile.Name.jpg') + ->sanitizingFileName(fn ($fileName) => strtolower(str_replace(['#', '\\', ' '], '-', $fileName))) + ->toMediaCollection(); + + expect($media->name)->toEqual('test'); + $this->assertFileExists($this->getMediaDirectory($media->id.'/other/[0]-{0}-(0)-otherfile.name.jpg')); +}); + +it('can save media in the right order', function () { + $media = []; + foreach (range(0, 5) as $index) { + $media[] = $this->testModel ->addMedia($this->getTestJpg()) - ->usingName('othername') + ->preservingOriginal() ->toMediaCollection(); - $this->assertEquals('othername', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + expect($media[$index]->order_column)->toEqual($index + 1); } +}); - /** @test */ - public function it_can_rename_the_file_before_it_gets_added() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->usingFileName('othertest.jpg') - ->toMediaCollection(); +it('can add properties to the saved media', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withProperties(['name' => 'testName']) + ->toMediaCollection(); - $this->assertEquals('test', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/othertest.jpg')); - } + expect($media->name)->toEqual('testName'); - /** @test */ - public function it_will_remove_strange_characters_from_the_file_name() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->usingFileName('other#test.jpg') - ->toMediaCollection(); + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withAttributes(['name' => 'testName']) + ->toMediaCollection(); - $this->assertEquals('test', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/other-test.jpg')); - } + expect($media->name)->toEqual('testName'); +}); - /** @test */ - public function it_will_sanitize_the_file_name_using_callable() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->sanitizingFileName(fn ($fileName) => 'new_file_name.jpg') - ->toMediaCollection(); +it('can add manipulations to the saved media', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withManipulations(['thumb' => ['width' => '10']]) + ->toMediaCollection(); - $this->assertEquals('test', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/new_file_name.jpg')); - } + expect($media->manipulations['thumb']['width'])->toEqual('10'); +}); - /** @test */ - public function the_file_name_can_be_modified_using_a_file_namer() - { - config()->set('media-library.file_namer', RenameOriginalFileNamer::class); +it('can add file to model with morph map', function () { + $media = $this->testModelWithMorphMap + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); + expect($media->model_type)->toEqual($this->testModelWithMorphMap->getMorphClass()); +}); - $this->assertEquals('test', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/renamed_original_file.jpg')); - } +it('will throw an exception when setting the file to a wrong type', function () { + $wrongType = []; - /** @test */ - public function the_file_name_can_be_modified_using_custom_sanitizing_and_default_file_namer() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->usingFileName('other/otherFileName.jpg') - ->sanitizingFileName(function ($fileName) { - return strtolower(str_replace(['#', '\\', ' '], '-', $fileName)); - }) - ->toMediaCollection(); + $this->expectException(UnknownType::class); - $this->assertEquals('test', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/other/otherfilename.jpg')); - } + $this->testModel + ->addMedia($this->getTestJpg()) + ->setFile($wrongType); +}); - /** @test */ - public function the_file_name_can_be_modified_using_custom_sanitizing_and_default_file_namer_and_especial_chars() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->usingFileName('other/[0]-{0}-(0)-otherFile.Name.jpg') - ->sanitizingFileName(function ($fileName) { - return strtolower(str_replace(['#', '\\', ' '], '-', $fileName)); - }) - ->toMediaCollection(); +it('will throw an exception when adding a file that is too big', function () { + config()->set('media-library.max_file_size', 1); - $this->assertEquals('test', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/other/[0]-{0}-(0)-otherfile.name.jpg')); - } + $this->expectException(FileIsTooBig::class); - /** @test */ - public function it_can_save_media_in_the_right_order() - { - $media = []; - foreach (range(0, 5) as $index) { - $media[] = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); + $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); +}); - $this->assertEquals($index + 1, $media[$index]->order_column); - } - } +it('will throw an exception when adding a file to a non existing disk', function () { + $this->expectException(DiskDoesNotExist::class); - /** @test */ - public function it_can_add_properties_to_the_saved_media() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withProperties(['name' => 'testName']) - ->toMediaCollection(); + $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection('images', 'non-existing-disk'); +}); - $this->assertEquals('testName', $media->name); +it('can add a base64 encoded file to the media library', function () { + $testFile = $this->getTestJpg(); + $testBase64Data = base64_encode(file_get_contents($testFile)); - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withAttributes(['name' => 'testName']) - ->toMediaCollection(); + $media = $this->testModel + ->addMediaFromBase64($testBase64Data) + ->toMediaCollection(); - $this->assertEquals('testName', $media->name); - } + $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); +}); - /** @test */ - public function it_can_add_manipulations_to_the_saved_media() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withManipulations(['thumb' => ['width' => '10']]) - ->toMediaCollection(); +test('a string can be accepted to be added to the media library', function () { + $string = 'test123'; - $this->assertEquals('10', $media->manipulations['thumb']['width']); - } + $media = $this->testModel + ->addMediaFromString($string) + ->toMediaCollection(); - /** @test */ - public function it_can_add_file_to_model_with_morph_map() - { - $media = $this->testModelWithMorphMap - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); + expect(file_get_contents($media->getPath()))->toEqual($string); +}); - $this->assertEquals($this->testModelWithMorphMap->getMorphClass(), $media->model_type); - } +test('a stream can be accepted to be added to the media library', function () { + $string = 'test123'; + $stream = fopen('php://temp', 'w+'); + fwrite($stream, $string); + rewind($stream); - /** @test */ - public function it_will_throw_an_exception_when_setting_the_file_to_a_wrong_type() - { - $wrongType = []; + $media = $this->testModel + ->addMediaFromStream($stream) + ->toMediaCollection(); - $this->expectException(UnknownType::class); + expect(file_get_contents($media->getPath()))->toEqual($string); +}); - $this->testModel - ->addMedia($this->getTestJpg()) - ->setFile($wrongType); - } +it('can add data uri prefixed base64 encoded file to the medialibrary', function () { + $testFile = $this->getTestJpg(); + $testBase64Data = 'data:image/jpg;base64,'.base64_encode(file_get_contents($testFile)); - /** @test */ - public function it_will_throw_an_exception_when_adding_a_file_that_is_too_big() - { - $this->app['config']->set('media-library.max_file_size', 1); + $media = $this->testModel + ->addMediaFromBase64($testBase64Data) + ->toMediaCollection(); - $this->expectException(FileIsTooBig::class); + $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); +}); - $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); - } +it('will throw an exception when adding invalid base64 data', function () { + $testFile = $this->getTestJpg(); + $invalidBase64Data = file_get_contents($testFile); - /** @test */ - public function it_will_throw_an_exception_when_adding_a_file_to_a_non_existing_disk() - { - $this->expectException(DiskDoesNotExist::class); + $this->expectException(InvalidBase64Data::class); - $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection('images', 'non-existing-disk'); - } + $this->testModel + ->addMediaFromBase64($invalidBase64Data) + ->toMediaCollection(); +}); - /** @test */ - public function it_can_add_a_base64_encoded_file_to_the_media_library() - { - $testFile = $this->getTestJpg(); - $testBase64Data = base64_encode(file_get_contents($testFile)); +it('will throw an exception when adding invalid base64 mime type', function () { + $testFile = $this->getTestJpg(); + $testBase64Data = base64_encode(file_get_contents($testFile)); - $media = $this->testModel - ->addMediaFromBase64($testBase64Data) - ->toMediaCollection(); - - $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - } + $this->expectException(MimeTypeNotAllowed::class); - /** @test */ - public function a_string_can_be_accepted_to_be_added_to_the_media_library() - { - $string = 'test123'; + $this->testModel + ->addMediaFromBase64($testBase64Data, ['image/png']) + ->toMediaCollection(); +}); - $media = $this->testModel - ->addMediaFromString($string) - ->toMediaCollection(); +it('can add files on an unsaved model even if not preserving the original', function () { + $this->testUnsavedModel->name = 'test'; - $this->assertEquals($string, file_get_contents($media->getPath())); - } + $this->testUnsavedModel->addMedia($this->getTestJpg())->toMediaCollection(); - /** @test */ - public function a_stream_can_be_accepted_to_be_added_to_the_media_library() - { - $string = 'test123'; - $stream = fopen('php://temp', 'w+'); - fwrite($stream, $string); - rewind($stream); + $this->testUnsavedModel->addMedia($this->getTestPdf())->toMediaCollection(); - $media = $this->testModel - ->addMediaFromStream($stream) - ->toMediaCollection(); + $this->testUnsavedModel->save(); - $this->assertEquals($string, file_get_contents($media->getPath())); - } + $media = $this->testUnsavedModel->getMedia(); - /** @test */ - public function it_can_add_data_uri_prefixed_base64_encoded_file_to_the_medialibrary() - { - $testFile = $this->getTestJpg(); - $testBase64Data = 'data:image/jpg;base64,'.base64_encode(file_get_contents($testFile)); + expect($media)->toHaveCount(2); +}); +it('can add an upload to the media library using dot notation', function () { + app()['router']->get('/upload', function () { $media = $this->testModel - ->addMediaFromBase64($testBase64Data) + ->addMediaFromRequest('file.name') ->toMediaCollection(); + expect($media->name)->toEqual('alternativename'); $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - } - - /** @test */ - public function it_will_throw_an_exception_when_adding_invalid_base64_data() - { - $testFile = $this->getTestJpg(); - $invalidBase64Data = file_get_contents($testFile); - - $this->expectException(InvalidBase64Data::class); - - $this->testModel - ->addMediaFromBase64($invalidBase64Data) - ->toMediaCollection(); - } - - /** @test */ - public function it_will_throw_an_exception_when_adding_invalid_base64_mime_type() - { - $testFile = $this->getTestJpg(); - $testBase64Data = base64_encode(file_get_contents($testFile)); - - $this->expectException(MimeTypeNotAllowed::class); - - $this->testModel - ->addMediaFromBase64($testBase64Data, ['image/png']) - ->toMediaCollection(); - } - - /** @test */ - public function it_can_add_files_on_an_unsaved_model_even_if_not_preserving_the_original() - { - $this->testUnsavedModel->name = 'test'; - - $this->testUnsavedModel->addMedia($this->getTestJpg())->toMediaCollection(); - - $this->testUnsavedModel->addMedia($this->getTestPdf())->toMediaCollection(); - - $this->testUnsavedModel->save(); - - $media = $this->testUnsavedModel->getMedia(); + }); - $this->assertCount(2, $media); - } - - /** @test */ - public function it_can_add_an_upload_to_the_media_library_using_dot_notation() - { - $this->app['router']->get('/upload', function () { - $media = $this->testModel - ->addMediaFromRequest('file.name') - ->toMediaCollection(); + $fileUpload = new UploadedFile( + $this->getTestFilesDirectory('test.jpg'), + 'alternativename.jpg', + 'image/jpeg', + filesize($this->getTestFilesDirectory('test.jpg')) + ); - $this->assertEquals('alternativename', $media->name); - $this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name)); - }); + $result = $this->call('get', 'upload', [], [], ['file' => ['name' => $fileUpload]]); - $fileUpload = new UploadedFile( - $this->getTestFilesDirectory('test.jpg'), - 'alternativename.jpg', - 'image/jpeg', - filesize($this->getTestFilesDirectory('test.jpg')) - ); - - $result = $this->call('get', 'upload', [], [], ['file' => ['name' => $fileUpload]]); - - $this->assertEquals(200, $result->getStatusCode()); - } -} + expect($result->getStatusCode())->toEqual(200); +}); diff --git a/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php b/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php index dd241a3dd..f4f2fcb10 100644 --- a/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php +++ b/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php @@ -1,155 +1,133 @@ testModelWithoutMediaConversions - ->copyMedia($this->getTestFilesDirectory('test.jpg')) - ->toMediaCollection(); - - $this->assertEquals('default', $media->collection_name); - } - - /** @test */ - public function it_can_create_a_derived_version_of_an_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - - $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); - } - - /** @test */ - public function it_will_not_create_a_derived_version_for_non_registered_collections() - { - $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection('downloads'); - - $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); - } - - /** @test */ - public function it_will_create_a_derived_version_for_an_image_without_an_extension() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('image')) - ->toMediaCollection('images'); - - $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/image-thumb.jpg')); - } - - /** @test */ - public function it_can_create_a_derived_version_for_an_image_keeping_the_original_format() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestPng()) - ->toMediaCollection('images'); - - $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-keep_original_format.png')); - } - - /** @test */ - public function it_will_use_the_name_of_the_conversion_for_naming_the_converted_file() - { - $modelClass = new class () extends TestModelWithConversion { - public function registerMediaConversions(Media $media = null): void - { - $this->addMediaConversion('my-conversion') - ->setManipulations(function (Manipulations $manipulations) { - $manipulations - ->removeManipulation('format'); - }) - ->nonQueued(); - } - }; - - $model = $modelClass::first(); - - $media = $model - ->addMedia($this->getTestFilesDirectory('test.png')) - ->toMediaCollection('images'); - - $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-my-conversion.png')); - } - - /** @test */ - public function it_can_create_a_derived_version_of_a_pdf_if_imagick_exists() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestFilesDirectory('test.pdf')) - ->toMediaCollection('images'); - - $thumbPath = $this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg'); - - class_exists('Imagick') ? $this->assertFileExists($thumbPath) : $this->assertFileDoesNotExist($thumbPath); - } - - /** @test */ - public function it_will_not_create_a_derived_version_if_manipulations_did_not_change() - { - Carbon::setTestNow(); - - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - - $originalThumbCreatedAt = filemtime($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); - - Carbon::setTestNow(Carbon::now()->addMinute()); - - $media->order_column += 1; - $media->save(); - - $thumbsCreatedAt = filemtime($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); - - $this->assertEquals($originalThumbCreatedAt, $thumbsCreatedAt); - } - - /** @test */ - public function it_will_have_access_the_model_instance_when_registerMediaConversionsUsingModelInstance_has_been_set() - { - $modelClass = new class () extends TestModel { - public bool $registerMediaConversionsUsingModelInstance = true; - - /** - * Register the conversions that should be performed. - * - * @return array - */ - public function registerMediaConversions(Media $media = null): void - { - $this->addMediaConversion('thumb') - ->width($this->width) - ->nonQueued(); - } - }; - - $model = new $modelClass(); - $model->name = 'testmodel'; - $model->width = 123; - $model->save(); - - $media = $model - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); - - $conversionCollection = ConversionCollection::createForMedia($media); - - $conversion = $conversionCollection->getConversions()[0]; - - $conversionManipulations = $conversion - ->getManipulations() - ->getManipulationSequence() - ->toArray()[0]; - - $this->assertEquals(123, $conversionManipulations['width']); - } -} +it('can add an file to the default collection', function () { + $media = $this->testModelWithoutMediaConversions + ->copyMedia($this->getTestFilesDirectory('test.jpg')) + ->toMediaCollection(); + + expect($media->collection_name)->toEqual('default'); +}); + +it('can create a derived version of an image', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); + + $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); +}); + +it('will not create a derived version for non registered collections', function () { + $media = $this->testModelWithoutMediaConversions->addMedia($this->getTestJpg())->toMediaCollection('downloads'); + + $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); +}); + +it('will create a derived version for an image without an extension', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('image')) + ->toMediaCollection('images'); + + $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/image-thumb.jpg')); +}); + +it('can create a derived version for an image keeping the original format', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestPng()) + ->toMediaCollection('images'); + + $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-keep_original_format.png')); +}); + +it('will use the name of the conversion for naming the converted file', function () { + $modelClass = new class () extends TestModelWithConversion { + public function registerMediaConversions(Media $media = null): void + { + $this->addMediaConversion('my-conversion') + ->setManipulations(function (Manipulations $manipulations) { + $manipulations + ->removeManipulation('format'); + }) + ->nonQueued(); + } + }; + + $model = $modelClass::first(); + + $media = $model + ->addMedia($this->getTestFilesDirectory('test.png')) + ->toMediaCollection('images'); + + $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-my-conversion.png')); +}); + +it('can create a derived version of a pdf if imagick exists', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestFilesDirectory('test.pdf')) + ->toMediaCollection('images'); + + $thumbPath = $this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg'); + + class_exists(Imagick::class) + ? expect($thumbPath)->toBeFile() + : $this->assertFileDoesNotExist($thumbPath); +}); + +it('will not create a derived version if manipulations did not change', function () { + Carbon::setTestNow(); + + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); + + $originalThumbCreatedAt = filemtime($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); + + Carbon::setTestNow(Carbon::now()->addMinute()); + + $media->order_column += 1; + $media->save(); + + $thumbsCreatedAt = filemtime($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); + + expect($thumbsCreatedAt)->toEqual($originalThumbCreatedAt); +}); + +it('will have access the model instance when register media conversions using model instance has been set', function () { + $modelClass = new class () extends TestModel { + public bool $registerMediaConversionsUsingModelInstance = true; + + /** + * Register the conversions that should be performed. + * + * @return array + */ + public function registerMediaConversions(Media $media = null): void + { + $this->addMediaConversion('thumb') + ->width($this->width) + ->nonQueued(); + } + }; + + $model = new $modelClass(); + $model->name = 'testmodel'; + $model->width = 123; + $model->save(); + + $media = $model + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); + + $conversionCollection = ConversionCollection::createForMedia($media); + + $conversion = $conversionCollection->getConversions()[0]; + + $conversionManipulations = $conversion + ->getManipulations() + ->getManipulationSequence() + ->toArray()[0]; + + expect($conversionManipulations['width'])->toEqual(123); +}); diff --git a/tests/Feature/FileAdder/MediaConversions/DeleteMediaTest.php b/tests/Feature/FileAdder/MediaConversions/DeleteMediaTest.php index 94275c6b2..7487eda17 100644 --- a/tests/Feature/FileAdder/MediaConversions/DeleteMediaTest.php +++ b/tests/Feature/FileAdder/MediaConversions/DeleteMediaTest.php @@ -1,142 +1,113 @@ testModelWithoutMediaConversions - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - - $this->testModelWithoutMediaConversions - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('images'); - } +beforeEach(function () { + foreach (range(1, 3) as $index) { + $this->testModelWithoutMediaConversions + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + + $this->testModelWithoutMediaConversions + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('images'); } +}); - /** @test */ - public function it_can_clear_a_collection() - { - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('default')); - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('images')); +it('can clear a collection', function () { + expect($this->testModelWithoutMediaConversions->getMedia('default'))->toHaveCount(3); + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(3); - $this->testModelWithoutMediaConversions->clearMediaCollection('images'); - $this->testModelWithoutMediaConversions = $this->testModelWithoutMediaConversions->fresh(); + $this->testModelWithoutMediaConversions->clearMediaCollection('images'); + $this->testModelWithoutMediaConversions = $this->testModelWithoutMediaConversions->fresh(); - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('default')); - $this->assertCount(0, $this->testModelWithoutMediaConversions->getMedia('images')); - } + expect($this->testModelWithoutMediaConversions->getMedia('default'))->toHaveCount(3); + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(0); +}); - /** @test */ - public function it_can_clear_the_default_collection() - { - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('default')); - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('images')); +it('can clear the default collection', function () { + expect($this->testModelWithoutMediaConversions->getMedia('default'))->toHaveCount(3); + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(3); - $this->testModelWithoutMediaConversions->clearMediaCollection(); - $this->testModelWithoutMediaConversions = $this->testModelWithoutMediaConversions->fresh(); + $this->testModelWithoutMediaConversions->clearMediaCollection(); + $this->testModelWithoutMediaConversions = $this->testModelWithoutMediaConversions->fresh(); - $this->assertCount(0, $this->testModelWithoutMediaConversions->getMedia('default')); - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('images')); - } + expect($this->testModelWithoutMediaConversions->getMedia('default'))->toHaveCount(0); + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(3); +}); - /** @test */ - public function it_can_clear_a_collection_excluding_a_single_media() - { - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('images')); +it('can clear a collection excluding a single media', function () { + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(3); - $excludedMedia = $this->testModelWithoutMediaConversions->getFirstMedia('images'); + $excludedMedia = $this->testModelWithoutMediaConversions->getFirstMedia('images'); - $this->testModelWithoutMediaConversions->clearMediaCollectionExcept('images', $excludedMedia); + $this->testModelWithoutMediaConversions->clearMediaCollectionExcept('images', $excludedMedia); - $this->assertEquals($this->testModelWithoutMediaConversions->getMedia('images')[0], $excludedMedia); - $this->assertCount(1, $this->testModelWithoutMediaConversions->getMedia('images')); - } + expect($excludedMedia)->toEqual($this->testModelWithoutMediaConversions->getMedia('images')[0]); + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(1); +}); - /** @test */ - public function it_can_clear_a_collection_excluding_some_media() - { - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('default')); - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('images')); +it('can clear a collection excluding some media', function () { + expect($this->testModelWithoutMediaConversions->getMedia('default'))->toHaveCount(3); + expect($this->testModelWithoutMediaConversions->getMedia('images'))->toHaveCount(3); - $excludedMedia = $this->testModelWithoutMediaConversions->getMedia('images')->take(2); + $excludedMedia = $this->testModelWithoutMediaConversions->getMedia('images')->take(2); - $this->testModelWithoutMediaConversions->clearMediaCollectionExcept('images', $excludedMedia); - $this->testModelWithoutMediaConversions = $this->testModelWithoutMediaConversions->fresh(); + $this->testModelWithoutMediaConversions->clearMediaCollectionExcept('images', $excludedMedia); + $this->testModelWithoutMediaConversions = $this->testModelWithoutMediaConversions->fresh(); - $this->assertCount(3, $this->testModelWithoutMediaConversions->getMedia('default')); - $this->assertEquals($this->testModelWithoutMediaConversions->getMedia('images')[0], $excludedMedia[0]); - $this->assertEquals($this->testModelWithoutMediaConversions->getMedia('images')[1], $excludedMedia[1]); - } + expect($this->testModelWithoutMediaConversions->getMedia('default'))->toHaveCount(3); + expect($excludedMedia[0])->toEqual($this->testModelWithoutMediaConversions->getMedia('images')[0]); + expect($excludedMedia[1])->toEqual($this->testModelWithoutMediaConversions->getMedia('images')[1]); +}); - /** @test */ - public function it_provides_a_chainable_method_for_clearing_a_collection() - { - $result = $this->testModelWithoutMediaConversions->clearMediaCollection('images'); +it('provides a chainable method for clearing a collection', function () { + $result = $this->testModelWithoutMediaConversions->clearMediaCollection('images'); - $this->assertInstanceOf(TestModelWithoutMediaConversions::class, $result); - } + expect($result)->toBeInstanceOf(TestModelWithoutMediaConversions::class); +}); - /** - * @test - */ - public function it_will_remove_the_files_when_clearing_a_collection() - { - $ids = $this->testModelWithoutMediaConversions->getMedia('images')->pluck('id'); +it('will remove the files when clearing a collection', function () { + $ids = $this->testModelWithoutMediaConversions->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $this->testModelWithoutMediaConversions->clearMediaCollection('images'); + $this->testModelWithoutMediaConversions->clearMediaCollection('images'); - $ids->map(function ($id) { - $this->assertFalse(File::isDirectory($this->getMediaDirectory($id))); - }); - } + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeFalse(); + }); +}); - /** - * @test - */ - public function it_will_remove_the_files_when_deleting_a_subject_without_media_conversions() - { - $ids = $this->testModelWithoutMediaConversions->getMedia('images')->pluck('id'); +it('will remove the files when deleting a subject without media conversions', function () { + $ids = $this->testModelWithoutMediaConversions->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $this->testModelWithoutMediaConversions->delete(); + $this->testModelWithoutMediaConversions->delete(); - $ids->map(function ($id) { - $this->assertFalse(File::isDirectory($this->getMediaDirectory($id))); - }); - } + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeFalse(); + }); +}); - /** @test */ - public function it_will_not_remove_the_files_when_deleting_a_subject_and_preserving_media() - { - $ids = $this->testModelWithoutMediaConversions->getMedia('images')->pluck('id'); +it('will not remove the files when deleting a subject and preserving media', function () { + $ids = $this->testModelWithoutMediaConversions->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $this->testModelWithoutMediaConversions->deletePreservingMedia(); + $this->testModelWithoutMediaConversions->deletePreservingMedia(); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); - } -} + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); +}); diff --git a/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php b/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php index 16693514a..9d4fcc8b9 100644 --- a/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php +++ b/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php @@ -1,275 +1,247 @@ addMediaCollection('images') - ->useDisk('secondMediaDisk'); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $media = $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $this->assertFileDoesNotExist($this->getTempDirectory('media').'/'.$media->id.'/test.jpg'); - - $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); - - $media = $model->addMedia($this->getTestJpg())->toMediaCollection('other-images'); - - $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/test.jpg'); - } - - /** @test */ - public function it_will_not_use_the_disk_name_of_the_collection_if_a_diskname_is_specified_while_adding() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this->addMediaCollection('images') - ->useDisk('secondMediaDisk'); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $media = $model->addMedia($this->getTestJpg())->toMediaCollection('images', 'public'); - - $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/test.jpg'); - - $this->assertFileDoesNotExist($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); - } - - /** @test */ - public function it_can_register_media_conversions_when_defining_media_collections() - { - $testModel = new class () extends TestModelWithoutMediaConversions { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->registerMediaConversions(function (Media $media) { - $this - ->addMediaConversion('thumb') - ->greyscale(); - }); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $media = $model->addMedia($this->getTestJpg())->toMediaCollection('images', 'public'); - - $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-thumb.jpg'); - } - - /** @test */ - public function it_will_not_use_media_conversions_from_an_unrelated_collection() - { - $testModel = new class () extends TestModelWithoutMediaConversions { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->registerMediaConversions(function (Media $media) { - $this - ->addMediaConversion('thumb') - ->greyscale(); - }); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $media = $model->addMedia($this->getTestJpg())->toMediaCollection('unrelated-collection'); - - $this->assertFileDoesNotExist($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-thumb.jpg'); - } - - /** @test */ - public function it_will_use_conversions_defined_in_conversions_and_conversions_defined_in_collections() - { - $testModel = new class () extends TestModelWithoutMediaConversions { - public function registerMediaConversions(Media $media = null): void - { - $this - ->addMediaConversion('another-thumb') - ->greyscale(); - } - - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->registerMediaConversions(function (Media $media = null) { - $this - ->addMediaConversion('thumb') - ->greyscale(); - }); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $media = $model->addMedia($this->getTestJpg())->toMediaCollection('images', 'public'); - - $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-thumb.jpg'); - - $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-another-thumb.jpg'); - } - - /** @test */ - public function it_can_accept_certain_files() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->acceptsFile(fn (File $file) => $file->mimeType === 'image/jpeg'); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $this->expectException(FileUnacceptableForCollection::class); - - $model->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection('images'); - } - - /** @test * */ - public function it_can_guard_against_invalid_mimetypes() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->acceptsMimeTypes(['image/jpeg']); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $this->expectException(FileUnacceptableForCollection::class); - - $model->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection('images'); - } - - /** @test * */ - public function it_can_generate_responsive_images() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->withResponsiveImages(); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $media = $model->getMedia('images')->first(); - - $this->assertEquals([ - 'http://localhost/media/1/responsive-images/test___media_library_original_340_280.jpg', - 'http://localhost/media/1/responsive-images/test___media_library_original_284_233.jpg', - 'http://localhost/media/1/responsive-images/test___media_library_original_237_195.jpg', - ], $media->getResponsiveImageUrls()); - - $this->assertEquals([], $media->getResponsiveImageUrls('non-existing-conversion')); - } - - /** @test * */ - public function it_can_generate_responsive_images_on_condition() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->withResponsiveImagesIf(true); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $media = $model->getMedia('images')->first(); - - $this->assertEquals([ - 'http://localhost/media/1/responsive-images/test___media_library_original_340_280.jpg', - 'http://localhost/media/1/responsive-images/test___media_library_original_284_233.jpg', - 'http://localhost/media/1/responsive-images/test___media_library_original_237_195.jpg', - ], $media->getResponsiveImageUrls()); - - $this->assertEquals([], $media->getResponsiveImageUrls('non-existing-conversion')); - } - - /** @test */ - public function if_the_single_file_method_is_specified_it_will_delete_all_other_media_and_will_only_keep_the_new_one() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->singleFile(); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $this->assertCount(1, $model->getMedia('images')); - } - - /** @test */ - public function if_the_only_keeps_latest_method_is_specified_it_will_delete_all_other_media_and_will_only_keep_the_latest_n_ones() - { - $testModel = new class () extends TestModelWithConversion { - public function registerMediaCollections(): void - { - $this - ->addMediaCollection('images') - ->onlyKeepLatest(3); - } - }; - - $model = $testModel::create(['name' => 'testmodel']); - - $firstFile = $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $this->assertFalse($model->getMedia('images')->contains(fn ($model) => $model->is($firstFile))); - $this->assertCount(3, $model->getMedia('images')); - } -} +it('will use the disk from a media collection', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this->addMediaCollection('images') + ->useDisk('secondMediaDisk'); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $media = $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $this->assertFileDoesNotExist($this->getTempDirectory('media').'/'.$media->id.'/test.jpg'); + + $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); + + $media = $model->addMedia($this->getTestJpg())->toMediaCollection('other-images'); + + $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/test.jpg'); +}); + +it('will not use the disk name of the collection if a diskname is specified while adding', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this->addMediaCollection('images') + ->useDisk('secondMediaDisk'); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $media = $model->addMedia($this->getTestJpg())->toMediaCollection('images', 'public'); + + $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/test.jpg'); + + $this->assertFileDoesNotExist($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); +}); + +it('can register media conversions when defining media collections', function () { + $testModel = new class () extends TestModelWithoutMediaConversions { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->registerMediaConversions(function (Media $media) { + $this + ->addMediaConversion('thumb') + ->greyscale(); + }); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $media = $model->addMedia($this->getTestJpg())->toMediaCollection('images', 'public'); + + $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-thumb.jpg'); +}); + +it('will not use media conversions from an unrelated collection', function () { + $testModel = new class () extends TestModelWithoutMediaConversions { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->registerMediaConversions(function (Media $media) { + $this + ->addMediaConversion('thumb') + ->greyscale(); + }); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $media = $model->addMedia($this->getTestJpg())->toMediaCollection('unrelated-collection'); + + $this->assertFileDoesNotExist($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-thumb.jpg'); +}); + +it('will use conversions defined in conversions and conversions defined in collections', function () { + $testModel = new class () extends TestModelWithoutMediaConversions { + public function registerMediaConversions(Media $media = null): void + { + $this + ->addMediaConversion('another-thumb') + ->greyscale(); + } + + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->registerMediaConversions(function (Media $media = null) { + $this + ->addMediaConversion('thumb') + ->greyscale(); + }); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $media = $model->addMedia($this->getTestJpg())->toMediaCollection('images', 'public'); + + $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-thumb.jpg'); + + $this->assertFileExists($this->getTempDirectory('media').'/'.$media->id.'/conversions/test-another-thumb.jpg'); +}); + +it('can accept certain files', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->acceptsFile(fn (File $file) => $file->mimeType === 'image/jpeg'); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $this->expectException(FileUnacceptableForCollection::class); + + $model->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection('images'); +}); + +it('can guard against invalid mimetypes', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->acceptsMimeTypes(['image/jpeg']); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $this->expectException(FileUnacceptableForCollection::class); + + $model->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection('images'); +}); + +it('can generate responsive images', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->withResponsiveImages(); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $media = $model->getMedia('images')->first(); + + $this->assertEquals([ + 'http://localhost/media/1/responsive-images/test___media_library_original_340_280.jpg', + 'http://localhost/media/1/responsive-images/test___media_library_original_284_234.jpg', + 'http://localhost/media/1/responsive-images/test___media_library_original_237_195.jpg', + ], $media->getResponsiveImageUrls()); + + expect($media->getResponsiveImageUrls('non-existing-conversion'))->toEqual([]); +}); + +it('can generate responsive images on condition', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->withResponsiveImagesIf(true); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $media = $model->getMedia('images')->first(); + + $this->assertEquals([ + 'http://localhost/media/1/responsive-images/test___media_library_original_340_280.jpg', + 'http://localhost/media/1/responsive-images/test___media_library_original_284_234.jpg', + 'http://localhost/media/1/responsive-images/test___media_library_original_237_195.jpg', + ], $media->getResponsiveImageUrls()); + + expect($media->getResponsiveImageUrls('non-existing-conversion'))->toEqual([]); +}); + +test('if the single file method is specified it will delete all other media and will only keep the new one', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->singleFile(); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + expect($model->getMedia('images'))->toHaveCount(1); +}); + +test('if the only keeps latest method is specified it will delete all other media and will only keep the latest n ones', function () { + $testModel = new class () extends TestModelWithConversion { + public function registerMediaCollections(): void + { + $this + ->addMediaCollection('images') + ->onlyKeepLatest(3); + } + }; + + $model = $testModel::create(['name' => 'testmodel']); + + $firstFile = $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $model->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $this->assertFalse($model->getMedia('images')->contains(fn ($model) => $model->is($firstFile))); + expect($model->getMedia('images'))->toHaveCount(3); +}); diff --git a/tests/Feature/FileAdder/MultipleDiskTest.php b/tests/Feature/FileAdder/MultipleDiskTest.php index 6c508f5aa..b7b7bfde7 100644 --- a/tests/Feature/FileAdder/MultipleDiskTest.php +++ b/tests/Feature/FileAdder/MultipleDiskTest.php @@ -1,79 +1,63 @@ testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection($collectionName, $diskName); - - $this->assertEquals($collectionName, $media->collection_name); - $this->assertEquals($diskName, $media->disk); - $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); - } - - /** @test */ - public function it_will_throw_an_exception_when_using_a_non_existing_disk() - { - $this->expectException(FileCannotBeAdded::class); - - $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection('images', 'diskdoesnotexist'); - } - - /** @test */ - public function it_will_save_the_derived_images_on_the_same_disk_as_the_original_file() - { - $collectionName = 'images'; - $diskName = 'secondMediaDisk'; - - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection($collectionName, $diskName); - - $this->assertEquals($collectionName, $media->collection_name); - $this->assertEquals($diskName, $media->disk); - $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); - $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/conversions/test-thumb.jpg'); - } - - /** @test */ - public function it_can_generate_urls_to_media_on_an_alternative_disk() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('', 'secondMediaDisk'); - - $this->assertEquals("/media2/{$media->id}/test.jpg", $media->getUrl()); - $this->assertEquals("/media2/{$media->id}/conversions/test-thumb.jpg", $media->getUrl('thumb')); - } - - /** @test */ - public function it_can_put_files_on_the_cloud_disk_configured_the_filesystems_config_file() - { - $collectionName = 'images'; - - $diskName = 'secondMediaDisk'; - - $this->app['config']->set('filesystems.cloud', 'secondMediaDisk'); - - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollectionOnCloudDisk($collectionName); - - $this->assertEquals($collectionName, $media->collection_name); - $this->assertEquals($diskName, $media->disk); - $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); - } -} + +it('can add a file to a named collection on a specific disk', function () { + $collectionName = 'images'; + $diskName = 'secondMediaDisk'; + + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection($collectionName, $diskName); + + expect($media->collection_name)->toEqual($collectionName); + expect($media->disk)->toEqual($diskName); + $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); +}); + +it('will throw an exception when using a non existing disk', function () { + $this->expectException(FileCannotBeAdded::class); + + $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection('images', 'diskdoesnotexist'); +}); + +it('will save the derived images on the same disk as the original file', function () { + $collectionName = 'images'; + $diskName = 'secondMediaDisk'; + + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection($collectionName, $diskName); + + expect($media->collection_name)->toEqual($collectionName); + expect($media->disk)->toEqual($diskName); + $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); + $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/conversions/test-thumb.jpg'); +}); + +it('can generate urls to media on an alternative disk', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('', 'secondMediaDisk'); + + expect($media->getUrl())->toEqual("/media2/{$media->id}/test.jpg"); + expect($media->getUrl('thumb'))->toEqual("/media2/{$media->id}/conversions/test-thumb.jpg"); +}); + +it('can put files on the cloud disk configured the filesystems config file', function () { + $collectionName = 'images'; + + $diskName = 'secondMediaDisk'; + + config()->set('filesystems.cloud', 'secondMediaDisk'); + + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollectionOnCloudDisk($collectionName); + + expect($media->collection_name)->toEqual($collectionName); + expect($media->disk)->toEqual($diskName); + $this->assertFileExists($this->getTempDirectory('media2').'/'.$media->id.'/test.jpg'); +}); diff --git a/tests/Feature/InteractsWithMedia/DeleteMediaTest.php b/tests/Feature/InteractsWithMedia/DeleteMediaTest.php index 9c35c4064..8be889660 100644 --- a/tests/Feature/InteractsWithMedia/DeleteMediaTest.php +++ b/tests/Feature/InteractsWithMedia/DeleteMediaTest.php @@ -1,120 +1,100 @@ testModel); +}); - $this->addMedia($this->testModel); - } +it('can clear a collection', function () { + expect($this->testModel->getMedia('default'))->toHaveCount(3); + expect($this->testModel->getMedia('images'))->toHaveCount(3); - /** @test */ - public function it_can_clear_a_collection() - { - $this->assertCount(3, $this->testModel->getMedia('default')); - $this->assertCount(3, $this->testModel->getMedia('images')); + $this->testModel->clearMediaCollection('images'); - $this->testModel->clearMediaCollection('images'); - - $this->assertCount(3, $this->testModel->getMedia('default')); - $this->assertCount(0, $this->testModel->getMedia('images')); - } + expect($this->testModel->getMedia('default'))->toHaveCount(3); + expect($this->testModel->getMedia('images'))->toHaveCount(0); +}); - /** @test */ - public function it_will_remove_the_files_when_clearing_a_collection() - { - $ids = $this->testModel->getMedia('images')->pluck('id'); +it('will remove the files when clearing a collection', function () { + $ids = $this->testModel->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $this->testModel->clearMediaCollection('images'); + $this->testModel->clearMediaCollection('images'); - $ids->map(function ($id) { - $this->assertFalse(File::isDirectory($this->getMediaDirectory($id))); - }); - } + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeFalse(); + }); +}); - /** @test */ - public function it_will_remove_the_files_when_deleting_a_subject() - { - $ids = $this->testModel->getMedia('images')->pluck('id'); +it('will remove the files when deleting a subject', function () { + $ids = $this->testModel->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $this->testModel->delete(); + $this->testModel->delete(); - $ids->map(function ($id) { - $this->assertFalse(File::isDirectory($this->getMediaDirectory($id))); - }); - } + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeFalse(); + }); +}); - /** @test */ - public function it_will_remove_the_files_when_using_a_custom_model_and_deleting_it() - { - config()->set('media-library.media_model', TestCustomMediaModel::class); +it('will remove the files when using a custom model and deleting it', function () { + config()->set('media-library.media_model', TestCustomMediaModel::class); - (new MediaLibraryServiceProvider($this->app))->boot(); + (new MediaLibraryServiceProvider(app()))->boot(); - $testModel = TestModel::create(['name' => 'test']); + $testModel = TestModel::create(['name' => 'test']); - $this->addMedia($testModel); + addMedia($testModel); - $this->assertInstanceOf(TestCustomMediaModel::class, $testModel->getFirstMedia()); + expect($testModel->getFirstMedia())->toBeInstanceOf(TestCustomMediaModel::class); - $ids = $testModel->getMedia('images')->pluck('id'); + $ids = $testModel->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $testModel->delete(); + $testModel->delete(); - $ids->map(function ($id) { - $this->assertFalse(File::isDirectory($this->getMediaDirectory($id))); - }); - } + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeFalse(); + }); +}); - /** @test */ - public function it_will_not_remove_the_files_when_deleting_a_subject_and_preserving_media() - { - $ids = $this->testModel->getMedia('images')->pluck('id'); +it('will not remove the files when deleting a subject and preserving media', function () { + $ids = $this->testModel->getMedia('images')->pluck('id'); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); - $this->testModel->deletePreservingMedia(); + $this->testModel->deletePreservingMedia(); - $ids->map(function ($id) { - $this->assertTrue(File::isDirectory($this->getMediaDirectory($id))); - }); - } + $ids->map(function ($id) { + expect(File::isDirectory($this->getMediaDirectory($id)))->toBeTrue(); + }); +}); - private function addMedia(TestModel $model) - { - foreach (range(1, 3) as $index) { - $model - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - - $model - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('images'); - } +function addMedia(TestModel $model) +{ + foreach (range(1, 3) as $index) { + $model + ->addMedia(test()->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + + $model + ->addMedia(test()->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('images'); } } diff --git a/tests/Feature/InteractsWithMedia/GetMediaTest.php b/tests/Feature/InteractsWithMedia/GetMediaTest.php index aa2b5de74..790f30c8b 100644 --- a/tests/Feature/InteractsWithMedia/GetMediaTest.php +++ b/tests/Feature/InteractsWithMedia/GetMediaTest.php @@ -1,359 +1,307 @@ testModel->getMedia('images'); - $this->assertInstanceOf(Collection::class, $emptyCollection); - $this->assertCount(0, $emptyCollection); - } - - /** @test */ - public function it_will_only_get_media_from_the_specified_collection() - { - $this->assertCount(0, $this->testModel->getMedia('images')); - $this->assertCount(0, $this->testModel->getMedia('downloads')); - $this->assertCount(0, $this->testModel->getMedia()); - - $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->preservingOriginal()->toMediaCollection('images'); - $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->preservingOriginal()->toMediaCollection('downloads'); - $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->preservingOriginal()->toMediaCollection(); - - $this->testModel = $this->testModel->fresh(); - - $this->assertCount(1, $this->testModel->getMedia('images')); - $this->assertCount(1, $this->testModel->getMedia('downloads')); - $this->assertCount(1, $this->testModel->getMedia()); - } - - /** @test */ - public function it_will_return_media_repository() - { - $this->assertInstanceOf(MediaRepository::class, $this->testModel->getMediaRepository()); - } - - /** @test */ - public function it_returns_a_media_collection_as_a_laravel_collection() - { - $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); - - $this->assertInstanceOf(Collection::class, $this->testModel->getMedia()); - } - - /** @test */ - public function it_returns_collections_filled_with_media_objects() - { - $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); - - $this->assertInstanceOf(Media::class, $this->testModel->getMedia()->first()); - } - - /** @test */ - public function it_can_get_multiple_media_from_the_default_collection() - { - $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); - $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); - - $this->assertCount(2, $this->testModel->getMedia()); - } - - /** @test */ - public function it_can_get_multiple_media_from_the_default_collection_empty() - { - $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); - - $this->assertCount(1, $this->testModel->getMedia()); - $this->assertCount(0, $this->testModel->getMedia('')); - - $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(''); - - $this->assertCount(1, $this->testModel->refresh()->getMedia()); - $this->assertCount(1, $this->testModel->refresh()->getMedia('')); - } - - /** @test */ - public function it_can_get_files_from_a_named_collection() - { - $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); - $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $this->assertCount(1, $this->testModel->getMedia('images')); - $this->assertEquals('images', $this->testModel->getMedia('images')[0]->collection_name); - } - - /** @test */ - public function it_can_get_files_from_a_collection_using_a_filter() - { - $media1 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter1' => 'value1']) - ->toMediaCollection(); - - $media2 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter1' => 'value2']) - ->toMediaCollection('images'); - - $media3 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter2' => 'value1']) - ->toMediaCollection('images'); - - $media4 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter2' => 'value2']) - ->toMediaCollection('images'); - - $collection = $this->testModel->getMedia('images', ['filter2' => 'value1']); - $this->assertCount(1, $collection); - $this->assertSame($collection->first()->id, $media3->id); - } - - /** @test */ - public function it_can_get_files_from_a_collection_using_a_filter_callback() - { - $media1 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter1' => 'value1']) - ->toMediaCollection(); - - $media2 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter1' => 'value2']) - ->toMediaCollection('images'); - - $media3 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter2' => 'value1']) - ->toMediaCollection('images'); - - $media4 = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties(['filter2' => 'value2']) - ->toMediaCollection('images'); - - $collection = $this->testModel->getMedia('images', fn (Media $media) => isset($media->custom_properties['filter1'])); - - $this->assertCount(1, $collection); - $this->assertSame($collection->first()->id, $media2->id); - } - - /** @test */ - public function it_can_get_the_first_media_from_a_collection() - { - $media = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $media->name = 'first'; - $media->save(); - - $media = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $media->name = 'second'; - $media->save(); - - $this->assertEquals('first', $this->testModel->getFirstMedia('images')->name); - } - - /** @test */ - public function it_can_get_the_first_media_from_a_collection_using_a_filter() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->withCustomProperties(['extra_property' => 'yes']) - ->preservingOriginal() - ->toMediaCollection('images'); - $media->name = 'first'; - $media->save(); - - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('images'); - $media->name = 'second'; - $media->save(); - - $this->assertEquals('first', $this->testModel->getFirstMedia('images', ['extra_property' => 'yes'])->name); - } - - /** @test */ - public function it_can_get_the_first_media_from_a_collection_using_a_filter_callback() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->withCustomProperties(['extra_property' => 'yes']) - ->preservingOriginal() - ->toMediaCollection('images'); - $media->name = 'first'; - $media->save(); - - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('images'); - $media->name = 'second'; - $media->save(); - - $firstMedia = $this->testModel->getFirstMedia('images', fn (Media $media) => isset($media->custom_properties['extra_property'])); - - $this->assertEquals('first', $firstMedia->name); - } - - public function it_returns_false_when_getting_first_media_for_an_empty_collection() - { - $this->assertFalse($this->testModel->getFirstMedia()); - } - - /** @test */ - public function it_can_get_the_url_to_first_media_in_a_collection() - { - $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $firstMedia->save(); - - $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $secondMedia->save(); - - $this->assertEquals($firstMedia->getUrl(), $this->testModel->getFirstMediaUrl('images')); - } - - /** @test */ - public function it_can_get_the_path_to_first_media_in_a_collection() - { - $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $firstMedia->save(); - - $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $secondMedia->save(); - - $this->assertEquals($firstMedia->getPath(), $this->testModel->getFirstMediaPath('images')); - } - - /** @test */ - public function it_can_get_the_default_path_to_the_first_media_in_a_collection() - { - $this->assertEquals('/default.jpg', $this->testModel->getFirstMediaPath('avatar')); - } - - /** @test */ - public function it_can_get_the_default_url_to_the_first_media_in_a_collection() - { - $this->assertEquals('/default.jpg', $this->testModel->getFirstMediaUrl('avatar')); - } - - /** @test */ - public function it_can_get_the_default_path_to_the_first_media_in_a_collection_if_conversion_not_marked_as_generated_yet() - { - $media = $this - ->testModelWithConversionQueued - ->addMedia($this->getTestJpg()) - ->toMediaCollection('avatar'); - - $avatarThumbConversion = $this->getMediaDirectory("{$media->id}/conversions/test-avatar_thumb.jpg"); - unlink($avatarThumbConversion); - $this->testModelWithConversionQueued->getFirstMedia('avatar')->markAsConversionNotGenerated('avatar_thumb'); - - $this->assertEquals($this->getMediaDirectory("{$media->id}/test.jpg"), $this->testModelWithConversionQueued->getFirstMediaPath('avatar', 'avatar_thumb')); - } - - /** @test */ - public function it_can_get_the_correct_path_to_the_converted_media_in_a_collection_if_conversion_is_marked_as_generated() - { - $media = $this - ->testModelWithConversionQueued - ->addMedia($this->getTestJpg()) - ->toMediaCollection('avatar'); - - $avatarThumbConversion = $this->getMediaDirectory("{$media->id}/conversions/test-avatar_thumb.jpg"); - unlink($avatarThumbConversion); - $this->testModelWithConversionQueued->getFirstMedia('avatar')->markAsConversionGenerated('avatar_thumb'); - - $this->assertEquals($media->getPath('avatar_thumb'), $this->testModelWithConversionQueued->getFirstMediaPath('avatar', 'avatar_thumb')); - } - - /** @test */ - public function it_can_get_the_default_url_to_the_first_media_in_a_collection_if_conversion_not_marked_as_generated_yet() - { - $media = $this - ->testModelWithConversionQueued - ->addMedia($this->getTestJpg()) - ->toMediaCollection('avatar'); - - $avatarThumbConversion = $this->getMediaDirectory("{$media->id}/conversions/test-avatar_thumb.jpg"); - unlink($avatarThumbConversion); - $this->testModelWithConversionQueued->getFirstMedia('avatar')->markAsConversionNotGenerated('avatar_thumb'); - - $this->assertEquals("/media/{$media->id}/test.jpg", $this->testModelWithConversionQueued->getFirstMediaUrl('avatar', 'avatar_thumb')); - } - - /** @test */ - public function it_will_return_preloaded_media_sorting_on_order_column() - { - $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - - $preloadedTestModel = TestModel::with('media') - ->where('id', $this->testModel->id) - ->first(); - - $this->assertEquals([ - 1 => 1, - 2 => 2, - ], $preloadedTestModel - ->getMedia('images') - ->pluck('order_column', 'id') - ->map(fn ($value) => (int)$value) - ->toArray()); - - $firstMedia->order_column = 3; - $firstMedia->save(); - - $preloadedTestModel = TestModel::with('media') - ->where('id', $this->testModel->id) - ->first(); - - $this->assertSame([ - 2 => 2, - 1 => 3, - ], $preloadedTestModel - ->getMedia('images') - ->pluck('order_column', 'id') - ->map(fn ($value) => (int)$value) - ->toArray()); - } - - /** @test */ - public function it_will_cache_loaded_media() - { - DB::enableQueryLog(); - - $this->assertFalse($this->testModel->relationLoaded('media')); - $this->assertCount(0, DB::getQueryLog()); - - $this->testModel->getMedia('images'); - - $this->assertTrue($this->testModel->relationLoaded('media')); - $this->assertCount(1, DB::getQueryLog()); - - $this->testModel->getMedia('images'); - - $this->assertCount(1, DB::getQueryLog()); - - DB::DisableQueryLog(); - } -} +it('can handle an empty collection', function () { + $emptyCollection = $this->testModel->getMedia('images'); + expect($emptyCollection)->toBeInstanceOf(Collection::class); + expect($emptyCollection)->toHaveCount(0); +}); + +it('will only get media from the specified collection', function () { + expect($this->testModel->getMedia('images'))->toHaveCount(0); + expect($this->testModel->getMedia('downloads'))->toHaveCount(0); + expect($this->testModel->getMedia())->toHaveCount(0); + + $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->preservingOriginal()->toMediaCollection('images'); + $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->preservingOriginal()->toMediaCollection('downloads'); + $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->preservingOriginal()->toMediaCollection(); + + $this->testModel = $this->testModel->fresh(); + + expect($this->testModel->getMedia('images'))->toHaveCount(1); + expect($this->testModel->getMedia('downloads'))->toHaveCount(1); + expect($this->testModel->getMedia())->toHaveCount(1); +}); + +it('will return media repository', function () { + expect($this->testModel->getMediaRepository())->toBeInstanceOf(MediaRepository::class); +}); + +it('returns a media collection as a laravel collection', function () { + $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); + + expect($this->testModel->getMedia())->toBeInstanceOf(Collection::class); +}); + +it('returns collections filled with media objects', function () { + $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); + + expect($this->testModel->getMedia()->first())->toBeInstanceOf(Media::class); +}); + +it('can get multiple media from the default collection', function () { + $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); + $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); + + expect($this->testModel->getMedia())->toHaveCount(2); +}); + +it('can get multiple media from the default collection empty', function () { + $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); + + expect($this->testModel->getMedia())->toHaveCount(1); + expect($this->testModel->getMedia(''))->toHaveCount(0); + + $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(''); + + expect($this->testModel->refresh()->getMedia())->toHaveCount(1); + expect($this->testModel->refresh()->getMedia(''))->toHaveCount(1); +}); + +it('can get files from a named collection', function () { + $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection(); + $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + expect($this->testModel->getMedia('images'))->toHaveCount(1); + expect($this->testModel->getMedia('images')[0]->collection_name)->toEqual('images'); +}); + +it('can get files from a collection using a filter', function () { + $media1 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter1' => 'value1']) + ->toMediaCollection(); + + $media2 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter1' => 'value2']) + ->toMediaCollection('images'); + + $media3 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter2' => 'value1']) + ->toMediaCollection('images'); + + $media4 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter2' => 'value2']) + ->toMediaCollection('images'); + + $collection = $this->testModel->getMedia('images', ['filter2' => 'value1']); + expect($collection)->toHaveCount(1); + expect($media3->id)->toBe($collection->first()->id); +}); + +it('can get files from a collection using a filter callback', function () { + $media1 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter1' => 'value1']) + ->toMediaCollection(); + + $media2 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter1' => 'value2']) + ->toMediaCollection('images'); + + $media3 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter2' => 'value1']) + ->toMediaCollection('images'); + + $media4 = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties(['filter2' => 'value2']) + ->toMediaCollection('images'); + + $collection = $this->testModel->getMedia('images', fn (Media $media) => isset($media->custom_properties['filter1'])); + + expect($collection)->toHaveCount(1); + expect($media2->id)->toBe($collection->first()->id); +}); + +it('can get the first media from a collection', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $media->name = 'first'; + $media->save(); + + $media = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $media->name = 'second'; + $media->save(); + + expect($this->testModel->getFirstMedia('images')->name)->toEqual('first'); +}); + +it('can get the first media from a collection using a filter', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->withCustomProperties(['extra_property' => 'yes']) + ->preservingOriginal() + ->toMediaCollection('images'); + $media->name = 'first'; + $media->save(); + + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('images'); + $media->name = 'second'; + $media->save(); + + expect($this->testModel->getFirstMedia('images', ['extra_property' => 'yes'])->name)->toEqual('first'); +}); + +it('can get the first media from a collection using a filter callback', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->withCustomProperties(['extra_property' => 'yes']) + ->preservingOriginal() + ->toMediaCollection('images'); + $media->name = 'first'; + $media->save(); + + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('images'); + $media->name = 'second'; + $media->save(); + + $firstMedia = $this->testModel->getFirstMedia('images', fn (Media $media) => isset($media->custom_properties['extra_property'])); + + expect($firstMedia->name)->toEqual('first'); +}); + +it('can get the url to first media in a collection', function () { + $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $firstMedia->save(); + + $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $secondMedia->save(); + + expect($this->testModel->getFirstMediaUrl('images'))->toEqual($firstMedia->getUrl()); +}); + +it('can get the path to first media in a collection', function () { + $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $firstMedia->save(); + + $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $secondMedia->save(); + + expect($this->testModel->getFirstMediaPath('images'))->toEqual($firstMedia->getPath()); +}); + +it('can get the default path to the first media in a collection', function () { + expect($this->testModel->getFirstMediaPath('avatar'))->toEqual('/default.jpg'); +}); + +it('can get the default url to the first media in a collection', function () { + expect($this->testModel->getFirstMediaUrl('avatar'))->toEqual('/default.jpg'); +}); + +it('can get the default path to the first media in a collection if conversion not marked as generated yet', function () { + $media = $this + ->testModelWithConversionQueued + ->addMedia($this->getTestJpg()) + ->toMediaCollection('avatar'); + + $avatarThumbConversion = $this->getMediaDirectory("{$media->id}/conversions/test-avatar_thumb.jpg"); + unlink($avatarThumbConversion); + $this->testModelWithConversionQueued->getFirstMedia('avatar')->markAsConversionNotGenerated('avatar_thumb'); + + expect($this->testModelWithConversionQueued->getFirstMediaPath('avatar', 'avatar_thumb'))->toEqual($this->getMediaDirectory("{$media->id}/test.jpg")); +}); + +it('can get the correct path to the converted media in a collection if conversion is marked as generated', function () { + $media = $this + ->testModelWithConversionQueued + ->addMedia($this->getTestJpg()) + ->toMediaCollection('avatar'); + + $avatarThumbConversion = $this->getMediaDirectory("{$media->id}/conversions/test-avatar_thumb.jpg"); + unlink($avatarThumbConversion); + $this->testModelWithConversionQueued->getFirstMedia('avatar')->markAsConversionGenerated('avatar_thumb'); + + expect($this->testModelWithConversionQueued->getFirstMediaPath('avatar', 'avatar_thumb'))->toEqual($media->getPath('avatar_thumb')); +}); + +it('can get the default url to the first media in a collection if conversion not marked as generated yet', function () { + $media = $this + ->testModelWithConversionQueued + ->addMedia($this->getTestJpg()) + ->toMediaCollection('avatar'); + + $avatarThumbConversion = $this->getMediaDirectory("{$media->id}/conversions/test-avatar_thumb.jpg"); + unlink($avatarThumbConversion); + $this->testModelWithConversionQueued->getFirstMedia('avatar')->markAsConversionNotGenerated('avatar_thumb'); + + expect($this->testModelWithConversionQueued->getFirstMediaUrl('avatar', 'avatar_thumb'))->toEqual("/media/{$media->id}/test.jpg"); +}); + +it('will return preloaded media sorting on order column', function () { + $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + + $preloadedTestModel = TestModel::with('media') + ->where('id', $this->testModel->id) + ->first(); + + $this->assertEquals([ + 1 => 1, + 2 => 2, + ], $preloadedTestModel + ->getMedia('images') + ->pluck('order_column', 'id') + ->map(fn ($value) => (int)$value) + ->toArray()); + + $firstMedia->order_column = 3; + $firstMedia->save(); + + $preloadedTestModel = TestModel::with('media') + ->where('id', $this->testModel->id) + ->first(); + + $this->assertSame([ + 2 => 2, + 1 => 3, + ], $preloadedTestModel + ->getMedia('images') + ->pluck('order_column', 'id') + ->map(fn ($value) => (int)$value) + ->toArray()); +}); + +it('will cache loaded media', function () { + DB::enableQueryLog(); + + expect($this->testModel->relationLoaded('media'))->toBeFalse(); + expect(DB::getQueryLog())->toHaveCount(0); + + $this->testModel->getMedia('images'); + + expect($this->testModel->relationLoaded('media'))->toBeTrue(); + expect(DB::getQueryLog())->toHaveCount(1); + + $this->testModel->getMedia('images'); + + expect(DB::getQueryLog())->toHaveCount(1); + + DB::DisableQueryLog(); +}); + +it('returns null when getting first media for an empty collection', function () { + expect($this->testModel->getFirstMedia())->toBeNull(); +}); diff --git a/tests/Feature/InteractsWithMedia/HasMediaTest.php b/tests/Feature/InteractsWithMedia/HasMediaTest.php index b886e39e2..47e6948cf 100644 --- a/tests/Feature/InteractsWithMedia/HasMediaTest.php +++ b/tests/Feature/InteractsWithMedia/HasMediaTest.php @@ -1,66 +1,47 @@ assertFalse($this->testModel->hasMedia()); - } +it('returns false for an empty collection', function () { + expect($this->testModel->hasMedia())->toBeFalse(); +}); - /** @test */ - public function it_returns_true_for_a_non_empty_collection() - { - $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('returns true for a non empty collection', function () { + $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertTrue($this->testModel->hasMedia()); - } + expect($this->testModel->hasMedia())->toBeTrue(); +}); - /** @test */ - public function it_returns_true_for_a_non_empty_collection_in_an_unsaved_model() - { - $this->testUnsavedModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('returns true for a non empty collection in an unsaved model', function () { + $this->testUnsavedModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertTrue($this->testUnsavedModel->hasMedia()); - } + expect($this->testUnsavedModel->hasMedia())->toBeTrue(); +}); - /** @test */ - public function it_returns_true_if_any_collection_is_not_empty() - { - $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); +it('returns true if any collection is not empty', function () { + $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $this->assertTrue($this->testModel->hasMedia('images')); - } + expect($this->testModel->hasMedia('images'))->toBeTrue(); +}); - /** @test */ - public function it_returns_false_for_an_empty_named_collection() - { - $this->assertFalse($this->testModel->hasMedia('images')); - } +it('returns false for an empty named collection', function () { + expect($this->testModel->hasMedia('images'))->toBeFalse(); +}); - /** @test */ - public function it_returns_true_for_a_non_empty_named_collection() - { - $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); +it('returns true for a non empty named collection', function () { + $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $this->assertTrue($this->testModel->hasMedia('images')); - $this->assertFalse($this->testModel->hasMedia('downloads')); - } + expect($this->testModel->hasMedia('images'))->toBeTrue(); + expect($this->testModel->hasMedia('downloads'))->toBeFalse(); +}); - /** @test */ - public function it_returns_true_for_a_filtered_collection() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->withCustomProperties(['test' => true]) - ->toMediaCollection(); +it('returns true for a filtered collection', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->withCustomProperties(['test' => true]) + ->toMediaCollection(); - $this->assertTrue($this->testModel->hasMedia('default')); - $this->assertTrue($this->testModel->hasMedia('default', ['test' => true])); - $this->assertFalse($this->testModel->hasMedia('default', ['test' => false])); - } -} + expect($this->testModel->hasMedia('default'))->toBeTrue(); + expect($this->testModel->hasMedia('default', ['test' => true]))->toBeTrue(); + expect($this->testModel->hasMedia('default', ['test' => false]))->toBeFalse(); +}); diff --git a/tests/Feature/InteractsWithMedia/UpdateMediaTest.php b/tests/Feature/InteractsWithMedia/UpdateMediaTest.php index 4a2da156a..8fa5871e3 100644 --- a/tests/Feature/InteractsWithMedia/UpdateMediaTest.php +++ b/tests/Feature/InteractsWithMedia/UpdateMediaTest.php @@ -1,88 +1,68 @@ testModel->addMedia($this->getTestJpg())->usingName('test1')->preservingOriginal()->toMediaCollection(); + $this->testModel->addMedia($this->getTestJpg())->usingName('test2')->preservingOriginal()->toMediaCollection(); +}); - $this->testModel->addMedia($this->getTestJpg())->usingName('test1')->preservingOriginal()->toMediaCollection(); - $this->testModel->addMedia($this->getTestJpg())->usingName('test2')->preservingOriginal()->toMediaCollection(); - } +it('removes a media item if its not in the update array', function () { + $mediaArray = $this->testModel->media->toArray(); + unset($mediaArray[0]); - /** @test */ - public function it_removes_a_media_item_if_its_not_in_the_update_array() - { - $mediaArray = $this->testModel->media->toArray(); - unset($mediaArray[0]); + $this->testModel->updateMedia($mediaArray); + $this->testModel->load('media'); - $this->testModel->updateMedia($mediaArray); - $this->testModel->load('media'); + expect($this->testModel->media)->toHaveCount(1); + expect($this->testModel->getFirstMedia()->name)->toEqual('test2'); +}); - $this->assertCount(1, $this->testModel->media); - $this->assertEquals('test2', $this->testModel->getFirstMedia()->name); - } +it('removes a media item with eager loaded relation', function () { + $mediaArray = $this->testModel->media->toArray(); + unset($mediaArray[0]); - /** @test */ - public function it_removes_a_media_item_with_eager_loaded_relation() - { - $mediaArray = $this->testModel->media->toArray(); - unset($mediaArray[0]); + $this->testModel->load('media'); + $this->testModel->updateMedia($mediaArray); - $this->testModel->load('media'); - $this->testModel->updateMedia($mediaArray); + expect($this->testModel->media)->toHaveCount(1); + expect($this->testModel->getFirstMedia()->name)->toEqual('test2'); +}); - $this->assertCount(1, $this->testModel->media); - $this->assertEquals('test2', $this->testModel->getFirstMedia()->name); - } +it('renames media items', function () { + $mediaArray = $this->testModel->media->toArray(); - /** @test */ - public function it_renames_media_items() - { - $mediaArray = $this->testModel->media->toArray(); + $mediaArray[0]['name'] = 'testFoo'; + $mediaArray[1]['name'] = 'testBar'; - $mediaArray[0]['name'] = 'testFoo'; - $mediaArray[1]['name'] = 'testBar'; + $this->testModel->updateMedia($mediaArray); + $this->testModel->load('media'); - $this->testModel->updateMedia($mediaArray); - $this->testModel->load('media'); + expect($this->testModel->media[0]->name)->toEqual('testFoo'); + expect($this->testModel->media[1]->name)->toEqual('testBar'); +}); - $this->assertEquals('testFoo', $this->testModel->media[0]->name); - $this->assertEquals('testBar', $this->testModel->media[1]->name); - } +it('updates media item custom properties', function () { + $mediaArray = $this->testModel->media->toArray(); - /** @test */ - public function it_updates_media_item_custom_properties() - { - $mediaArray = $this->testModel->media->toArray(); + $mediaArray[0]['custom_properties']['foo'] = 'bar'; - $mediaArray[0]['custom_properties']['foo'] = 'bar'; + $this->testModel->updateMedia($mediaArray); + $this->testModel->load('media'); - $this->testModel->updateMedia($mediaArray); - $this->testModel->load('media'); + expect($this->testModel->media[0]->getCustomProperty('foo'))->toEqual('bar'); +}); - $this->assertEquals('bar', $this->testModel->media[0]->getCustomProperty('foo')); - } +it('reorders media items', function () { + $mediaArray = $this->testModel->media->toArray(); - /** - * @test - */ - public function it_reorders_media_items() - { - $mediaArray = $this->testModel->media->toArray(); + $differentOrder = array_reverse($mediaArray); - $differentOrder = array_reverse($mediaArray); + $this->testModel->updateMedia($differentOrder); + $this->testModel->load('media'); - $this->testModel->updateMedia($differentOrder); - $this->testModel->load('media'); + $orderedMedia = $this->testModel->media->sortBy('order_column'); - $orderedMedia = $this->testModel->media->sortBy('order_column'); - - $this->assertEquals($mediaArray[0]['order_column'], $orderedMedia[1]->order_column); - $this->assertEquals($mediaArray[1]['order_column'], $orderedMedia[0]->order_column); - } -} + expect($orderedMedia[1]->order_column)->toEqual($mediaArray[0]['order_column']); + expect($orderedMedia[0]->order_column)->toEqual($mediaArray[1]['order_column']); +}); diff --git a/tests/Feature/Media/CopyTest.php b/tests/Feature/Media/CopyTest.php index 70b5aab30..49580c0a8 100644 --- a/tests/Feature/Media/CopyTest.php +++ b/tests/Feature/Media/CopyTest.php @@ -1,166 +1,150 @@ 'test']); +it('can copy media from one model to another', function () { + /** @var TestModel $model */ + $model = TestModel::create(['name' => 'test']); + + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $model + ->addMedia($this->getTestJpg()) + ->usingName('custom-name') + ->withCustomProperties(['custom-property-name' => 'custom-property-value']) + ->toMediaCollection(); - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $model - ->addMedia($this->getTestJpg()) - ->usingName('custom-name') - ->withCustomProperties(['custom-property-name' => 'custom-property-value']) - ->toMediaCollection(); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + $anotherModel = TestModel::create(['name' => 'another-test']); - $anotherModel = TestModel::create(['name' => 'another-test']); + $movedMedia = $media->copy($anotherModel, 'images'); - $movedMedia = $media->copy($anotherModel, 'images'); + $movedMedia->refresh(); - $movedMedia->refresh(); + expect($model->getMedia('default'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertCount(1, $model->getMedia('default')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + expect($anotherModel->getMedia('images'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/test.jpg')); + expect($anotherModel->id)->toEqual($movedMedia->model->id); + expect('custom-name')->toEqual($movedMedia->name); + expect('custom-property-value')->toEqual($movedMedia->getCustomProperty('custom-property-name')); +}); - $this->assertCount(1, $anotherModel->getMedia('images')); - $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/test.jpg')); - $this->assertEquals($movedMedia->model->id, $anotherModel->id); - $this->assertEquals($movedMedia->name, 'custom-name'); - $this->assertEquals($movedMedia->getCustomProperty('custom-property-name'), 'custom-property-value'); +it('can copy file without extension', function () { + if (! file_exists(storage_path('media-library/temp'))) { + mkdir(storage_path('media-library/temp'), 0777, true); } - /** @test */ - public function it_can_copy_file_without_extension() - { - if (! file_exists(storage_path('media-library/temp'))) { - mkdir(storage_path('media-library/temp'), 0777, true); - } + config(['media-library.temporary_directory_path' => realpath(storage_path('media-library/temp'))]); - config(['media-library.temporary_directory_path' => realpath(storage_path('media-library/temp'))]); + /** @var TestModel $model */ + $model = TestModel::create(['name' => 'test']); - /** @var TestModel $model */ - $model = TestModel::create(['name' => 'test']); + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $model + ->addMedia($this->getTestImageWithoutExtension()) + ->usingName('custom-name') + ->withCustomProperties(['custom-property-name' => 'custom-property-value']) + ->toMediaCollection(); - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $model - ->addMedia($this->getTestImageWithoutExtension()) - ->usingName('custom-name') - ->withCustomProperties(['custom-property-name' => 'custom-property-value']) - ->toMediaCollection(); + $this->assertFileExists($this->getMediaDirectory($media->id.'/image')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/image')); + $anotherModel = TestModel::create(['name' => 'another-test']); - $anotherModel = TestModel::create(['name' => 'another-test']); + $movedMedia = $media->copy($anotherModel, 'images'); - $movedMedia = $media->copy($anotherModel, 'images'); + $movedMedia->refresh(); - $movedMedia->refresh(); + expect($model->getMedia('default'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($media->id.'/image')); - $this->assertCount(1, $model->getMedia('default')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/image')); + expect($anotherModel->getMedia('images'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/image')); + expect($anotherModel->id)->toEqual($movedMedia->model->id); + expect('custom-name')->toEqual($movedMedia->name); + expect('custom-property-value')->toEqual($movedMedia->getCustomProperty('custom-property-name')); +}); - $this->assertCount(1, $anotherModel->getMedia('images')); - $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/image')); - $this->assertEquals($movedMedia->model->id, $anotherModel->id); - $this->assertEquals($movedMedia->name, 'custom-name'); - $this->assertEquals($movedMedia->getCustomProperty('custom-property-name'), 'custom-property-value'); - } +it('can copy media from one model to another on a specific disk', function () { + $diskName = 'secondMediaDisk'; - /** @test */ - public function it_can_copy_media_from_one_model_to_another_on_a_specific_disk() - { - $diskName = 'secondMediaDisk'; + /** @var TestModel $model */ + $model = TestModel::create(['name' => 'test']); - /** @var TestModel $model */ - $model = TestModel::create(['name' => 'test']); + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $model + ->addMedia($this->getTestJpg()) + ->usingName('custom-name') + ->withCustomProperties(['custom-property-name' => 'custom-property-value']) + ->toMediaCollection(); - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $model - ->addMedia($this->getTestJpg()) - ->usingName('custom-name') - ->withCustomProperties(['custom-property-name' => 'custom-property-value']) - ->toMediaCollection(); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + $anotherModel = TestModel::create(['name' => 'another-test']); - $anotherModel = TestModel::create(['name' => 'another-test']); + $movedMedia = $media->copy($anotherModel, 'images', $diskName); - $movedMedia = $media->copy($anotherModel, 'images', $diskName); + $movedMedia->refresh(); - $movedMedia->refresh(); + expect($model->getMedia('default'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertCount(1, $model->getMedia('default')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + expect($anotherModel->getMedia('images'))->toHaveCount(1); + $this->assertFileExists($this->getTempDirectory('media2').'/'.$movedMedia->id.'/test.jpg'); + expect('images')->toEqual($movedMedia->collection_name); + expect($diskName)->toEqual($movedMedia->disk); + expect($anotherModel->id)->toEqual($movedMedia->model->id); + expect('custom-name')->toEqual($movedMedia->name); + expect('custom-property-value')->toEqual($movedMedia->getCustomProperty('custom-property-name')); +}); - $this->assertCount(1, $anotherModel->getMedia('images')); - $this->assertFileExists($this->getTempDirectory('media2').'/'.$movedMedia->id.'/test.jpg'); - $this->assertEquals($movedMedia->collection_name, 'images'); - $this->assertEquals($movedMedia->disk, $diskName); - $this->assertEquals($movedMedia->model->id, $anotherModel->id); - $this->assertEquals($movedMedia->name, 'custom-name'); - $this->assertEquals($movedMedia->getCustomProperty('custom-property-name'), 'custom-property-value'); +it('can copy file with accent', function () { + if (! file_exists(storage_path('media-library/temp'))) { + mkdir(storage_path('media-library/temp'), 0777, true); } - /** @test */ - public function it_can_copy_file_with_accent() - { - if (! file_exists(storage_path('media-library/temp'))) { - mkdir(storage_path('media-library/temp'), 0777, true); - } + config(['media-library.temporary_directory_path' => realpath(storage_path('media-library/temp'))]); - config(['media-library.temporary_directory_path' => realpath(storage_path('media-library/temp'))]); + /** @var TestModel $model */ + $model = TestModel::create(['name' => 'test']); - /** @var TestModel $model */ - $model = TestModel::create(['name' => 'test']); + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $model + ->addMedia($this->getAntaresThumbJpgWithAccent()) + ->usingName('custom-name') + ->withCustomProperties(['custom-property-name' => 'custom-property-value']) + ->toMediaCollection(); - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $model - ->addMedia($this->getAntaresThumbJpgWithAccent()) - ->usingName('custom-name') - ->withCustomProperties(['custom-property-name' => 'custom-property-value']) - ->toMediaCollection(); + $this->assertFileExists($this->getMediaDirectory($media->id.'/antarèsthumb.jpg')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/antarèsthumb.jpg')); + $anotherModel = TestModel::create(['name' => 'another-test']); - $anotherModel = TestModel::create(['name' => 'another-test']); + $movedMedia = $media->copy($anotherModel, 'images'); - $movedMedia = $media->copy($anotherModel, 'images'); + $movedMedia->refresh(); - $movedMedia->refresh(); + expect($model->getMedia('default'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($media->id.'/antarèsthumb.jpg')); - $this->assertCount(1, $model->getMedia('default')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/antarèsthumb.jpg')); + expect($anotherModel->getMedia('images'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/antarèsthumb.jpg')); + expect($anotherModel->id)->toEqual($movedMedia->model->id); + expect('custom-name')->toEqual($movedMedia->name); + expect('custom-property-value')->toEqual($movedMedia->getCustomProperty('custom-property-name')); +}); - $this->assertCount(1, $anotherModel->getMedia('images')); - $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/antarèsthumb.jpg')); - $this->assertEquals($movedMedia->model->id, $anotherModel->id); - $this->assertEquals($movedMedia->name, 'custom-name'); - $this->assertEquals($movedMedia->getCustomProperty('custom-property-name'), 'custom-property-value'); - } - - /** @test */ - public function it_preserves_original_file_on_copy_media_item_to_model() - { - $model = TestModel::create(['name' => 'original']); +it('preserves original file on copy media item to model', function () { + $model = TestModel::create(['name' => 'original']); - $media = $model - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); + $media = $model + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $anotherModel = TestModel::create(['name' => 'target']); + $anotherModel = TestModel::create(['name' => 'target']); - $anotherMedia = $media->copy($anotherModel); + $anotherMedia = $media->copy($anotherModel); - $this->assertFileExists($media->getPath()); - $this->assertFileExists($anotherMedia->getPath()); - } -} + expect($media->getPath())->toBeFile(); + expect($anotherMedia->getPath())->toBeFile(); +}); diff --git a/tests/Feature/Media/CustomHeadersTest.php b/tests/Feature/Media/CustomHeadersTest.php index 3a7e459c0..6cdcde455 100644 --- a/tests/Feature/Media/CustomHeadersTest.php +++ b/tests/Feature/Media/CustomHeadersTest.php @@ -1,35 +1,26 @@ testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); +it('does not set empty custom headers when saved', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $this->assertFalse($media->hasCustomProperty('custom_headers')); - $this->assertEquals([], $media->getCustomHeaders()); - } + expect($media->hasCustomProperty('custom_headers'))->toBeFalse(); + expect($media->getCustomHeaders())->toEqual([]); +}); - /** @test */ - public function it_can_set_and_retrieve_custom_headers_when_explicitly_added() - { - $headers = [ - 'Header' => 'Present', - ]; +it('can set and retrieve custom headers when explicitly added', function () { + $headers = [ + 'Header' => 'Present', + ]; - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection() - ->setCustomHeaders($headers); + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection() + ->setCustomHeaders($headers); - $this->assertTrue($media->hasCustomProperty('custom_headers')); - $this->assertEquals($headers, $media->getCustomHeaders()); - } -} + expect($media->hasCustomProperty('custom_headers'))->toBeTrue(); + expect($media->getCustomHeaders())->toEqual($headers); +}); diff --git a/tests/Feature/Media/CustomPropertyTest.php b/tests/Feature/Media/CustomPropertyTest.php index 17f723197..5ac9e4c50 100644 --- a/tests/Feature/Media/CustomPropertyTest.php +++ b/tests/Feature/Media/CustomPropertyTest.php @@ -1,80 +1,57 @@ media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties([ + 'customName' => 'customValue', + 'nested' => [ + 'customName' => 'nested customValue', + ], + ]) + ->toMediaCollection('images'); +}); - protected Media $mediaWithoutCustomProperty; +it('can determine if a media item has a custom property', function () { + expect($this->media->hasCustomProperty('customName'))->toBeTrue(); + expect($this->media->hasCustomProperty('nested.customName'))->toBeTrue(); - public function setUp(): void - { - parent::setUp(); + expect($this->media->hasCustomProperty('nonExisting'))->toBeFalse(); + expect($this->media->hasCustomProperty('nested.nonExisting'))->toBeFalse(); +}); - $this->media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties([ - 'customName' => 'customValue', - 'nested' => [ - 'customName' => 'nested customValue', - ], - ]) - ->toMediaCollection('images'); - } +it('can get a custom property', function () { + expect($this->media->getCustomProperty('customName'))->toEqual('customValue'); + expect($this->media->getCustomProperty('nested.customName'))->toEqual('nested customValue'); - /** @test */ - public function it_can_determine_if_a_media_item_has_a_custom_property() - { - $this->assertTrue($this->media->hasCustomProperty('customName')); - $this->assertTrue($this->media->hasCustomProperty('nested.customName')); + expect($this->media->getCustomProperty('nonExisting'))->toBeNull(); + expect($this->media->getCustomProperty('nested.nonExisting'))->toBeNull(); +}); - $this->assertFalse($this->media->hasCustomProperty('nonExisting')); - $this->assertFalse($this->media->hasCustomProperty('nested.nonExisting')); - } +it('can set a custom property', function () { + $this->media->setCustomProperty('anotherName', 'anotherValue'); - /** @test */ - public function it_can_get_a_custom_property() - { - $this->assertEquals('customValue', $this->media->getCustomProperty('customName')); - $this->assertEquals('nested customValue', $this->media->getCustomProperty('nested.customName')); + expect($this->media->getCustomProperty('anotherName'))->toEqual('anotherValue'); + expect($this->media->getCustomProperty('customName'))->toEqual('customValue'); - $this->assertNull($this->media->getCustomProperty('nonExisting')); - $this->assertNull($this->media->getCustomProperty('nested.nonExisting')); - } + $this->media->setCustomProperty('nested.anotherName', 'anotherValue'); + expect($this->media->getCustomProperty('nested.anotherName'))->toEqual('anotherValue'); +}); - /** @test */ - public function it_can_set_a_custom_property() - { - $this->media->setCustomProperty('anotherName', 'anotherValue'); +it('can forget a custom property', function () { + expect($this->media->hasCustomProperty('customName'))->toBeTrue(); + expect($this->media->hasCustomProperty('nested.customName'))->toBeTrue(); - $this->assertEquals('anotherValue', $this->media->getCustomProperty('anotherName')); - $this->assertEquals('customValue', $this->media->getCustomProperty('customName')); + $this->media->forgetCustomProperty('customName'); + $this->media->forgetCustomProperty('nested.customName'); - $this->media->setCustomProperty('nested.anotherName', 'anotherValue'); - $this->assertEquals('anotherValue', $this->media->getCustomProperty('nested.anotherName')); - } + expect($this->media->hasCustomProperty('customName'))->toBeFalse(); + expect($this->media->hasCustomProperty('nested.customName'))->toBeFalse(); +}); - /** @test */ - public function it_can_forget_a_custom_property() - { - $this->assertTrue($this->media->hasCustomProperty('customName')); - $this->assertTrue($this->media->hasCustomProperty('nested.customName')); - - $this->media->forgetCustomProperty('customName'); - $this->media->forgetCustomProperty('nested.customName'); - - $this->assertFalse($this->media->hasCustomProperty('customName')); - $this->assertFalse($this->media->hasCustomProperty('nested.customName')); - } - - /** @test */ - public function it_returns_a_fallback_if_a_custom_property_isnt_set() - { - $this->assertEquals('foo', $this->media->getCustomProperty('imNotHere', 'foo')); - } -} +it('returns a fallback if a custom property isnt set', function () { + expect($this->media->getCustomProperty('imNotHere', 'foo'))->toEqual('foo'); +}); diff --git a/tests/Feature/Media/DeleteTest.php b/tests/Feature/Media/DeleteTest.php index f70dd85cc..d4cdda336 100644 --- a/tests/Feature/Media/DeleteTest.php +++ b/tests/Feature/Media/DeleteTest.php @@ -1,142 +1,117 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); +it('will remove the files when deleting an object that has media', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $this->assertTrue(File::isDirectory($this->getMediaDirectory($media->id))); + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeTrue(); - $this->testModel->delete(); + $this->testModel->delete(); - $this->assertFalse(File::isDirectory($this->getMediaDirectory($media->id))); - } + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeFalse(); +}); - /** @test */ - public function it_will_remove_the_files_when_deleting_a_media_instance() - { - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); +it('will remove the files when deleting a media instance', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $this->assertTrue(File::isDirectory($this->getMediaDirectory($media->id))); + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeTrue(); - $media->delete(); + $media->delete(); - $this->assertFalse(File::isDirectory($this->getMediaDirectory($media->id))); - } + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeFalse(); +}); - /** @test */ - public function it_will_remove_files_when_deleting_a_media_object_with_a_custom_path_generator() - { - config(['media-library.path_generator' => TestPathGenerator::class]); +it('will remove files when deleting a media object with a custom path generator', function () { + config(['media-library.path_generator' => TestPathGenerator::class]); - $pathGenerator = new TestPathGenerator(); + $pathGenerator = new TestPathGenerator(); - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $path = $pathGenerator->getPath($media); + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + $path = $pathGenerator->getPath($media); - $this->assertTrue(File::isDirectory($this->getMediaDirectory($media->id))); + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeTrue(); - $this->testModel->delete(); + $this->testModel->delete(); - $this->assertFalse(File::isDirectory($this->getTempDirectory($path))); - } + expect(File::isDirectory($this->getTempDirectory($path)))->toBeFalse(); +}); - /** - * @test - */ - public function it_will_not_remove_the_files_when_shouldDeletePreservingMedia_returns_true() - { - $testModelClass = new class () extends TestModel { - public function shouldDeletePreservingMedia(): bool - { - return true; - } - }; +it('will not remove the files when should delete preserving media returns true', function () { + $testModelClass = new class () extends TestModel { + public function shouldDeletePreservingMedia(): bool + { + return true; + } + }; - $testModel = $testModelClass::find($this->testModel->id); + $testModel = $testModelClass::find($this->testModel->id); - $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $testModel = $testModel->fresh(); + $testModel = $testModel->fresh(); - $testModel->delete(); + $testModel->delete(); - $this->assertNotNull(Media::find($media->id)); - } + $this->assertNotNull(Media::find($media->id)); +}); - /** - * @test - */ - public function it_will_remove_the_files_when_shouldDeletePreservingMedia_returns_false() - { - $testModelClass = new class () extends TestModel { - public function shouldDeletePreservingMedia(): bool - { - return false; - } - }; +it('will remove the files when should delete preserving media returns false', function () { + $testModelClass = new class () extends TestModel { + public function shouldDeletePreservingMedia(): bool + { + return false; + } + }; - $testModel = $testModelClass::find($this->testModel->id); + $testModel = $testModelClass::find($this->testModel->id); - $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $testModel = $testModel->fresh(); + $testModel = $testModel->fresh(); - $testModel->delete(); + $testModel->delete(); - $this->assertNull(Media::find($media->id)); - } + expect(Media::find($media->id))->toBeNull(); +}); - /** @test */ - public function it_will_not_remove_the_file_when_model_uses_softdelete() - { - $testModelClass = new class () extends TestModel { - use SoftDeletes; - }; +it('will not remove the file when model uses softdelete', function () { + $testModelClass = new class () extends TestModel { + use SoftDeletes; + }; - /** @var TestModel $testModel */ - $testModel = $testModelClass::find($this->testModel->id); + /** @var TestModel $testModel */ + $testModel = $testModelClass::find($this->testModel->id); - $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $this->assertTrue(File::isDirectory($this->getMediaDirectory($media->id))); + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeTrue(); - $testModel = $testModel->fresh(); + $testModel = $testModel->fresh(); - $testModel->delete(); + $testModel->delete(); - $this->assertTrue(File::isDirectory($this->getMediaDirectory($media->id))); - } + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeTrue(); +}); - /** @test */ - public function it_will_remove_the_file_when_model_uses_softdelete_with_force() - { - $testModelClass = new class () extends TestModel { - use SoftDeletes; - }; +it('will remove the file when model uses softdelete with force', function () { + $testModelClass = new class () extends TestModel { + use SoftDeletes; + }; - /** @var TestModel $testModel */ - $testModel = $testModelClass::find($this->testModel->id); + /** @var TestModel $testModel */ + $testModel = $testModelClass::find($this->testModel->id); - $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $this->assertTrue(File::isDirectory($this->getMediaDirectory($media->id))); + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeTrue(); - $testModel = $testModel->fresh(); + $testModel = $testModel->fresh(); - $testModel->forceDelete(); + $testModel->forceDelete(); - $this->assertFalse(File::isDirectory($this->getMediaDirectory($media->id))); - } -} + expect(File::isDirectory($this->getMediaDirectory($media->id)))->toBeFalse(); +}); diff --git a/tests/Feature/Media/GetMediaConversionsTest.php b/tests/Feature/Media/GetMediaConversionsTest.php index a6262524a..d0f7d5b0d 100644 --- a/tests/Feature/Media/GetMediaConversionsTest.php +++ b/tests/Feature/Media/GetMediaConversionsTest.php @@ -1,26 +1,19 @@ testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); +it('can get the names of registered conversions', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); - $this->assertSame([], $media->getMediaConversionNames()); + expect($media->getMediaConversionNames())->toBe([]); - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); - $this->assertSame(['thumb', 'keep_original_format'], $media->getMediaConversionNames()); - } -} + expect($media->getMediaConversionNames())->toBe(['thumb', 'keep_original_format']); +}); diff --git a/tests/Feature/Media/GetOriginalUrlAttributeTest.php b/tests/Feature/Media/GetOriginalUrlAttributeTest.php index a3acfe569..74e2566e7 100644 --- a/tests/Feature/Media/GetOriginalUrlAttributeTest.php +++ b/tests/Feature/Media/GetOriginalUrlAttributeTest.php @@ -1,24 +1,15 @@ testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); +test('the original url attribute exists', function () { + $media = $this->testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertArrayHasKey('original_url', $media->toArray()); - } + $this->assertArrayHasKey('original_url', $media->toArray()); +}); - /** @test */ - public function it_can_get_url_of_original_image() - { - $media = $this->testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get url of original image', function () { + $media = $this->testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertEquals("/media/{$media->id}/test.jpg", $media->original_url); - } -} + expect($media->original_url)->toEqual("/media/{$media->id}/test.jpg"); +}); diff --git a/tests/Feature/Media/GetPathTest.php b/tests/Feature/Media/GetPathTest.php index fd96e565d..7f06c105d 100644 --- a/tests/Feature/Media/GetPathTest.php +++ b/tests/Feature/Media/GetPathTest.php @@ -1,75 +1,59 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get a path of an original item', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/test.jpg"); + $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/test.jpg"); - $actual = $this->makePathOsSafe($media->getPath()); + $actual = $this->makePathOsSafe($media->getPath()); - $this->assertEquals($expected, $actual); - } + expect($actual)->toEqual($expected); +}); - /** @test */ - public function it_can_get_a_path_of_a_derived_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get a path of a derived image', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $conversionName = 'thumb'; + $conversionName = 'thumb'; - $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/conversions/test-{$conversionName}.jpg"); + $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/conversions/test-{$conversionName}.jpg"); - $actual = $this->makePathOsSafe($media->getPath($conversionName)); + $actual = $this->makePathOsSafe($media->getPath($conversionName)); - $this->assertEquals($expected, $actual); - } + expect($actual)->toEqual($expected); +}); - /** @test */ - public function it_returns_an_exception_when_getting_a_path_for_an_unknown_conversion() - { - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('returns an exception when getting a path for an unknown conversion', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->expectException(InvalidConversion::class); + $this->expectException(InvalidConversion::class); - $media->getPath('unknownConversionName'); - } + $media->getPath('unknownConversionName'); +}); - /** @test */ - public function it_can_get_a_path_of_an_original_item_with_prefix() - { - config(['media-library.prefix' => 'prefix']); +it('can get a path of an original item with prefix', function () { + config(['media-library.prefix' => 'prefix']); - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/prefix/{$media->id}/test.jpg"); + $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/prefix/{$media->id}/test.jpg"); - $actual = $this->makePathOsSafe($media->getPath()); + $actual = $this->makePathOsSafe($media->getPath()); - $this->assertEquals($expected, $actual); - } + expect($actual)->toEqual($expected); +}); - /** @test */ - public function it_can_get_a_path_of_a_derived_image_with_prefix() - { - config(['media-library.prefix' => 'prefix']); +it('can get a path of a derived image with prefix', function () { + config(['media-library.prefix' => 'prefix']); - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $conversionName = 'thumb'; + $conversionName = 'thumb'; - $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/prefix/{$media->id}/conversions/test-{$conversionName}.jpg"); + $expected = $this->makePathOsSafe($this->getMediaDirectory() . "/prefix/{$media->id}/conversions/test-{$conversionName}.jpg"); - $actual = $this->makePathOsSafe($media->getPath($conversionName)); + $actual = $this->makePathOsSafe($media->getPath($conversionName)); - $this->assertEquals($expected, $actual); - } -} + expect($actual)->toEqual($expected); +}); diff --git a/tests/Feature/Media/GetPreviewUrlAttributeTest.php b/tests/Feature/Media/GetPreviewUrlAttributeTest.php index 4eee892df..818c692f7 100644 --- a/tests/Feature/Media/GetPreviewUrlAttributeTest.php +++ b/tests/Feature/Media/GetPreviewUrlAttributeTest.php @@ -1,26 +1,17 @@ testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); +test('the preview url attribute exists', function () { + $media = $this->testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertArrayHasKey('preview_url', $media->toArray()); - } + $this->assertArrayHasKey('preview_url', $media->toArray()); +}); - /** @test */ - public function it_can_get_url_of_preview_image() - { - $media = $this->testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get url of preview image', function () { + $media = $this->testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $conversionName = 'preview'; + $conversionName = 'preview'; - $this->assertEquals("/media/{$media->id}/conversions/test-{$conversionName}.jpg", $media->preview_url); - } -} + expect($media->preview_url)->toEqual("/media/{$media->id}/conversions/test-{$conversionName}.jpg"); +}); diff --git a/tests/Feature/Media/GetTypeTest.php b/tests/Feature/Media/GetTypeTest.php index 4a7233744..eb55275ae 100644 --- a/tests/Feature/Media/GetTypeTest.php +++ b/tests/Feature/Media/GetTypeTest.php @@ -1,16 +1,9 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('can return the file mime', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertEquals('image/jpeg', $media->mime_type); - } -} + expect($media->mime_type)->toEqual('image/jpeg'); +}); diff --git a/tests/Feature/Media/GetUrlTest.php b/tests/Feature/Media/GetUrlTest.php index 10478b419..7f3351b6a 100644 --- a/tests/Feature/Media/GetUrlTest.php +++ b/tests/Feature/Media/GetUrlTest.php @@ -1,67 +1,48 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get an url of an original item', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertEquals($media->getUrl(), "/media/{$media->id}/test.jpg"); - } + expect("/media/{$media->id}/test.jpg")->toEqual($media->getUrl()); +}); - /** @test */ - public function it_can_get_an_url_of_a_derived_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get an url of a derived image', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $conversionName = 'thumb'; + $conversionName = 'thumb'; - $this->assertEquals("/media/{$media->id}/conversions/test-{$conversionName}.jpg", $media->getUrl($conversionName)); - } + expect($media->getUrl($conversionName))->toEqual("/media/{$media->id}/conversions/test-{$conversionName}.jpg"); +}); - /** @test */ - public function it_returns_an_exception_when_getting_an_url_for_an_unknown_conversion() - { - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('returns an exception when getting an url for an unknown conversion', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->expectException(InvalidConversion::class); + $this->expectException(InvalidConversion::class); - $media->getUrl('unknownConversionName'); - } + $media->getUrl('unknownConversionName'); +}); - /** @test */ - public function it_can_get_the_full_url_of_an_original_item() - { - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get the full url of an original item', function () { + $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - $this->assertEquals($media->getFullUrl(), "http://localhost/media/{$media->id}/test.jpg"); - } + expect("http://localhost/media/{$media->id}/test.jpg")->toEqual($media->getFullUrl()); +}); - /** @test */ - public function it_can_get_the_full_url_of_a_derived_image() - { - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); +it('can get the full url of a derived image', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $conversionName = 'thumb'; + $conversionName = 'thumb'; - $this->assertEquals("http://localhost/media/{$media->id}/conversions/test-{$conversionName}.jpg", $media->getFullUrl($conversionName)); - } + expect($media->getFullUrl($conversionName))->toEqual("http://localhost/media/{$media->id}/conversions/test-{$conversionName}.jpg"); +}); - /** @test */ - public function it_throws_an_exception_when_trying_to_get_a_temporary_url_on_local_disk() - { - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); +it('throws an exception when trying to get a temporary url on local disk', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); - $this->expectException(RuntimeException::class); + $this->expectException(RuntimeException::class); - $media->getTemporaryUrl(Carbon::now()->addMinutes(5)); - } -} + $media->getTemporaryUrl(Carbon::now()->addMinutes(5)); +}); diff --git a/tests/Feature/Media/HasConversionTest.php b/tests/Feature/Media/HasConversionTest.php index 939811158..a88e914c2 100644 --- a/tests/Feature/Media/HasConversionTest.php +++ b/tests/Feature/Media/HasConversionTest.php @@ -1,16 +1,7 @@ testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); -use Spatie\MediaLibrary\Tests\TestCase; - -class HasConversionTest extends TestCase -{ - /** @test */ - public function test() - { - $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection(); - - $this->assertTrue($media->hasGeneratedConversion('thumb')); - } -} + expect($media->hasGeneratedConversion('thumb'))->toBeTrue(); +}); diff --git a/tests/Feature/Media/MediaRepositoryTest.php b/tests/Feature/Media/MediaRepositoryTest.php index 26d7511e9..782858666 100644 --- a/tests/Feature/Media/MediaRepositoryTest.php +++ b/tests/Feature/Media/MediaRepositoryTest.php @@ -1,29 +1,16 @@ set('media-library.media_model', TestCustomMediaModel::class); - } +it('can use a custom media model', function () { + config()->set('media-library.media_model', TestCustomMediaModel::class); - /** @test */ - public function it_can_use_a_custom_media_model() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); + $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); - $mediaRepository = app(MediaRepository::class); + $mediaRepository = app(MediaRepository::class); - $this->assertEquals(TestCustomMediaModel::class, $mediaRepository->all()->getQueueableClass()); - } -} + expect($mediaRepository->all()->getQueueableClass())->toEqual(TestCustomMediaModel::class); +}); diff --git a/tests/Feature/Media/MoveTest.php b/tests/Feature/Media/MoveTest.php index 709c56353..a06369689 100644 --- a/tests/Feature/Media/MoveTest.php +++ b/tests/Feature/Media/MoveTest.php @@ -1,67 +1,57 @@ 'test']); +it('can move media from one model to another', function () { + $model = TestModel::create(['name' => 'test']); - $media = $model - ->addMedia($this->getTestJpg()) - ->usingName('custom-name') - ->withCustomProperties(['custom-property-name' => 'custom-property-value']) - ->toMediaCollection(); + $media = $model + ->addMedia($this->getTestJpg()) + ->usingName('custom-name') + ->withCustomProperties(['custom-property-name' => 'custom-property-value']) + ->toMediaCollection(); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $anotherModel = TestModel::create(['name' => 'another-test']); + $anotherModel = TestModel::create(['name' => 'another-test']); - $movedMedia = $media->move($anotherModel, 'images'); + $movedMedia = $media->move($anotherModel, 'images'); - $this->assertCount(0, $model->getMedia('default')); - $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/test.jpg')); + expect($model->getMedia('default'))->toHaveCount(0); + $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertCount(1, $anotherModel->getMedia('images')); - $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/test.jpg')); - $this->assertEquals($movedMedia->model->id, $anotherModel->id); - $this->assertEquals($movedMedia->name, 'custom-name'); - $this->assertEquals($movedMedia->getCustomProperty('custom-property-name'), 'custom-property-value'); - } + expect($anotherModel->getMedia('images'))->toHaveCount(1); + $this->assertFileExists($this->getMediaDirectory($movedMedia->id.'/test.jpg')); + expect($anotherModel->id)->toEqual($movedMedia->model->id); + expect('custom-name')->toEqual($movedMedia->name); + expect('custom-property-value')->toEqual($movedMedia->getCustomProperty('custom-property-name')); +}); - /** @test */ - public function it_can_move_media_from_one_model_to_another_on_a_specific_disk() - { - $diskName = 'secondMediaDisk'; +it('can move media from one model to another on a specific disk', function () { + $diskName = 'secondMediaDisk'; - $model = TestModel::create(['name' => 'test']); + $model = TestModel::create(['name' => 'test']); - $media = $model - ->addMedia($this->getTestJpg()) - ->usingName('custom-name') - ->withCustomProperties(['custom-property-name' => 'custom-property-value']) - ->toMediaCollection(); + $media = $model + ->addMedia($this->getTestJpg()) + ->usingName('custom-name') + ->withCustomProperties(['custom-property-name' => 'custom-property-value']) + ->toMediaCollection(); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $anotherModel = TestModel::create(['name' => 'another-test']); + $anotherModel = TestModel::create(['name' => 'another-test']); - $movedMedia = $media->move($anotherModel, 'images', $diskName); + $movedMedia = $media->move($anotherModel, 'images', $diskName); - $this->assertCount(0, $model->getMedia('default')); - $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/test.jpg')); + expect($model->getMedia('default'))->toHaveCount(0); + $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertCount(1, $anotherModel->getMedia('images')); - $this->assertFileExists($this->getTempDirectory('media2').'/'.$movedMedia->id.'/test.jpg'); - $this->assertEquals($movedMedia->collection_name, 'images'); - $this->assertEquals($movedMedia->disk, $diskName); - $this->assertEquals($movedMedia->model->id, $anotherModel->id); - $this->assertEquals($movedMedia->name, 'custom-name'); - $this->assertEquals($movedMedia->getCustomProperty('custom-property-name'), 'custom-property-value'); - } -} + expect($anotherModel->getMedia('images'))->toHaveCount(1); + $this->assertFileExists($this->getTempDirectory('media2').'/'.$movedMedia->id.'/test.jpg'); + expect('images')->toEqual($movedMedia->collection_name); + expect($diskName)->toEqual($movedMedia->disk); + expect($anotherModel->id)->toEqual($movedMedia->model->id); + expect('custom-name')->toEqual($movedMedia->name); + expect('custom-property-value')->toEqual($movedMedia->getCustomProperty('custom-property-name')); +}); diff --git a/tests/Feature/Media/RenameTest.php b/tests/Feature/Media/RenameTest.php index 816903101..fbccdd61a 100644 --- a/tests/Feature/Media/RenameTest.php +++ b/tests/Feature/Media/RenameTest.php @@ -1,64 +1,53 @@ getTestFilesDirectory('test.jpg'); +it('wil rename the file if it is changed on the media object', function () { + $testFile = $this->getTestFilesDirectory('test.jpg'); - $media = $this->testModel->addMedia($testFile)->toMediaCollection(); + $media = $this->testModel->addMedia($testFile)->toMediaCollection(); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test.jpg')); - $media->file_name = 'test-new-name.jpg'; - $media->save(); + $media->file_name = 'test-new-name.jpg'; + $media->save(); - $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/test.jpg')); - $this->assertFileExists($this->getMediaDirectory($media->id.'/test-new-name.jpg')); - } + $this->assertFileDoesNotExist($this->getMediaDirectory($media->id.'/test.jpg')); + $this->assertFileExists($this->getMediaDirectory($media->id.'/test-new-name.jpg')); +}); - /** @test */ - public function it_will_rename_conversions() - { - $testFile = $this->getTestFilesDirectory('test.jpg'); +it('will rename conversions', function () { + $testFile = $this->getTestFilesDirectory('test.jpg'); - $media = $this->testModelWithConversion->addMedia($testFile)->toMediaCollection(); + $media = $this->testModelWithConversion->addMedia($testFile)->toMediaCollection(); - $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); + $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg')); - $media->file_name = 'test-new-name.jpg'; + $media->file_name = 'test-new-name.jpg'; - $media->save(); + $media->save(); - $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-new-name-thumb.jpg')); - } + $this->assertFileExists($this->getMediaDirectory($media->id.'/conversions/test-new-name-thumb.jpg')); +}); - /** @test */ - public function it_keeps_valid_file_name_when_renaming_with_missing_conversions() - { - $testFile = $this->getTestFilesDirectory('test.jpg'); +it('keeps valid file name when renaming with missing conversions', function () { + $testFile = $this->getTestFilesDirectory('test.jpg'); - $media = $this->testModelWithConversion->addMedia($testFile)->toMediaCollection(); + $media = $this->testModelWithConversion->addMedia($testFile)->toMediaCollection(); - $this->assertFileExists( - $thumb_conversion = $this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg') - ); + $this->assertFileExists( + $thumb_conversion = $this->getMediaDirectory($media->id.'/conversions/test-thumb.jpg') + ); - unlink($thumb_conversion); + unlink($thumb_conversion); - $media->file_name = $new_filename = 'test-new-name.jpg'; + $media->file_name = $new_filename = 'test-new-name.jpg'; - $media->save(); + $media->save(); - // Reload attributes from the database - $media = $media->fresh(); + // Reload attributes from the database + $media = $media->fresh(); - $this->assertFileExists($media->getPath()); - $this->assertEquals($new_filename, $media->file_name); - } -} + expect($media->getPath())->toBeFile(); + expect($media->file_name)->toEqual($new_filename); +}); diff --git a/tests/Feature/Media/ResponsableTest.php b/tests/Feature/Media/ResponsableTest.php index fb0111270..23b1b11fc 100644 --- a/tests/Feature/Media/ResponsableTest.php +++ b/tests/Feature/Media/ResponsableTest.php @@ -1,36 +1,27 @@ app['router']->get('/upload', fn () => $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection()); - - $result = $this->call('get', 'upload'); - - $this->assertEquals(200, $result->getStatusCode()); - $result->assertHeader('Content-Type', 'image/jpeg'); - $result->assertHeader('Content-Length', 29085); - } - - /** @test */ - public function it_can_return_a_text_as_a_response() - { - $this->app['router']->get('/upload', fn () => $this->testModel - ->addMedia($this->getTestFilesDirectory('test.txt')) - ->toMediaCollection()); - - $result = $this->call('get', 'upload'); - - $this->assertEquals(200, $result->getStatusCode()); - $result->assertHeader('Content-Type', 'text/plain; charset=UTF-8'); - $result->assertHeader('Content-Length', 45); - } -} + + +it('can return an image as a response', function () { + app()['router']->get('/upload', fn () => $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection()); + + $result = $this->call('get', 'upload'); + + expect($result->getStatusCode())->toEqual(200); + $result->assertHeader('Content-Type', 'image/jpeg'); + $result->assertHeader('Content-Length', 29085); +}); + +it('can return a text as a response', function () { + app()['router']->get('/upload', fn () => $this->testModel + ->addMedia($this->getTestFilesDirectory('test.txt')) + ->toMediaCollection()); + + $result = $this->call('get', 'upload'); + + expect($result->getStatusCode())->toEqual(200); + $result->assertHeader('Content-Type', 'text/plain; charset=UTF-8'); + $result->assertHeader('Content-Length', 45); +}); diff --git a/tests/Feature/Media/ToHtmlTest.php b/tests/Feature/Media/ToHtmlTest.php index 17501aa94..d5dd668ff 100644 --- a/tests/Feature/Media/ToHtmlTest.php +++ b/tests/Feature/Media/ToHtmlTest.php @@ -1,156 +1,120 @@ testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - } - - /** @test */ - public function it_can_render_itself_as_an_image() - { - $this->assertEquals( - 'test', - $this->firstMedia()->img(), - ); - } - - /** @test */ - public function it_can_render_a_conversion_of_itself_as_an_image() - { - $this->assertEquals( - 'test', - $this->firstMedia()->img('thumb') - ); - } - - /** @test */ - public function it_can_render_extra_attributes() - { - $this->assertEquals( - 'test', - $this->firstMedia()->img('thumb', ['class' => 'my-class', 'id' => 'my-id']), - ); - } - - /** @test */ - public function a_media_instance_is_htmlable() - { - $media = $this->firstMedia(); - - $renderedView = $this->renderView('media', compact('media')); - - $this->assertEquals( - 'test test', - $renderedView, - ); - } - - /** @test */ - public function converting_a_non_image_to_an_image_tag_will_not_blow_up() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestPdf()) - ->toMediaCollection(); - - $this->assertEquals('', $media->img()); - } - - /** @test */ - public function it_can_render_itself_with_responsive_images_and_a_placeholder() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - $image = $media->refresh()->img(); - - $this->assertEquals(3, substr_count($image, '/media/2/responsive-images/')); - $this->assertTrue(Str::contains($image, 'data:image/svg+xml;base64,')); - } - - /** @test */ - public function it_can_render_itself_with_responsive_images_of_a_conversion_and_a_placeholder() - { - $media = $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); - - $image = $media->refresh()->img('thumb'); - - $this->assertStringContainsString('/media/2/responsive-images/', $image); - $this->assertStringContainsString('data:image/svg+xml;base64,', $image); - } - - /** @test */ - public function it_will_not_rendering_extra_javascript_or_including_base64_svg_when_tiny_placeholders_are_turned_off() - { - config()->set('media-library.responsive_images.use_tiny_placeholders', false); - - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - $imgTag = $media->refresh()->img(); - - $this->assertEquals('', $imgTag); - } - - /** @test */ - public function the_loading_attribute_can_be_specified_on_the_conversion() - { - $media = TestModelWithCustomLoadingAttribute::create(['name' => 'test']) - ->addMedia($this->getTestJpg()) - ->toMediaCollection(); - - $originalImgTag = $media->refresh()->img(); - $this->assertEquals('test', $originalImgTag); - - $lazyConversionImageTag = $media->refresh()->img('lazy-conversion'); - $this->assertEquals('test', $lazyConversionImageTag); - - $eagerConversionImageTag = $media->refresh()->img('eager-conversion'); - $this->assertEquals('test', $eagerConversionImageTag); - } - - /** @test */ - public function it_has_a_shorthand_function_to_use_lazy_loading() - { - $this->assertEquals( - 'test', - $this->firstMedia()->img()->lazy() - ); - } - - /** @test */ - public function it_can_set_extra_attributes() - { - $this->assertEquals( - 'test', - (string) $this->firstMedia()->img()->attributes(['extra' => 'value']) - ); - } - - protected function firstMedia(): Media - { - return Media::first(); - } -} +uses(MatchesSnapshots::class); + +beforeEach(function () { + $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); +}); + +it('can render itself as an image', function () { + $this->assertEquals( + 'test', + Media::first()->img(), + ); +}); + +it('can render a conversion of itself as an image', function () { + $this->assertEquals( + 'test', + Media::first()->img('thumb') + ); +}); + +it('can render extra attributes', function () { + $this->assertEquals( + 'test', + Media::first()->img('thumb', ['class' => 'my-class', 'id' => 'my-id']), + ); +}); + +test('a media instance is htmlable', function () { + $media = Media::first(); + + $renderedView = $this->renderView('media', compact('media')); + + $this->assertEquals( + 'test test', + $renderedView, + ); +}); + +test('converting a non image to an image tag will not blow up', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestPdf()) + ->toMediaCollection(); + + expect($media->img())->toEqual(''); +}); + +it('can render itself with responsive images and a placeholder', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); + + $image = $media->refresh()->img(); + + expect(substr_count($image, '/media/2/responsive-images/'))->toEqual(3); + expect(Str::contains($image, 'data:image/svg+xml;base64,'))->toBeTrue(); +}); + +it('can render itself with responsive images of a conversion and a placeholder', function () { + $media = $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); + + $image = $media->refresh()->img('thumb'); + + expect((string)$image)->toContain('/media/2/responsive-images/'); + expect((string)$image)->toContain('data:image/svg+xml;base64,'); +}); + +it('will not rendering extra javascript or including base64 svg when tiny placeholders are turned off', function () { + config()->set('media-library.responsive_images.use_tiny_placeholders', false); + + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); + + $imgTag = $media->refresh()->img(); + + expect($imgTag)->toEqual(''); +}); + +test('the loading attribute can be specified on the conversion', function () { + $media = TestModelWithCustomLoadingAttribute::create(['name' => 'test']) + ->addMedia($this->getTestJpg()) + ->toMediaCollection(); + + $originalImgTag = $media->refresh()->img(); + expect($originalImgTag)->toEqual('test'); + + $lazyConversionImageTag = $media->refresh()->img('lazy-conversion'); + expect($lazyConversionImageTag)->toEqual('test'); + + $eagerConversionImageTag = $media->refresh()->img('eager-conversion'); + expect($eagerConversionImageTag)->toEqual('test'); +}); + +it('has a shorthand function to use lazy loading', function () { + $this->assertEquals( + 'test', + Media::first()->img()->lazy() + ); +}); + +it('can set extra attributes', function () { + $this->assertEquals( + 'test', + (string) Media::first()->img()->attributes(['extra' => 'value']) + ); +}); diff --git a/tests/Feature/Media/ToResponseTest.php b/tests/Feature/Media/ToResponseTest.php index 82be261c7..983fca1d4 100644 --- a/tests/Feature/Media/ToResponseTest.php +++ b/tests/Feature/Media/ToResponseTest.php @@ -1,45 +1,33 @@ testModel->addMedia($testPdf = $this->getTestPdf())->preservingOriginal()->toMediaCollection(); +test('to response sends the content', function () { + $media = $this->testModel->addMedia($testPdf = $this->getTestPdf())->preservingOriginal()->toMediaCollection(); - ob_start(); - @$media->toResponse(request())->sendContent(); - $content = ob_get_contents(); - ob_end_clean(); + ob_start(); + @$media->toResponse(request())->sendContent(); + $content = ob_get_contents(); + ob_end_clean(); - $temporaryDirectory = (new TemporaryDirectory())->create(); - file_put_contents($temporaryDirectory->path('response.pdf'), $content); + $temporaryDirectory = (new TemporaryDirectory())->create(); + file_put_contents($temporaryDirectory->path('response.pdf'), $content); - $this->assertFileEquals($testPdf, $temporaryDirectory->path('response.pdf')); - } + $this->assertFileEquals($testPdf, $temporaryDirectory->path('response.pdf')); +}); - /** @test */ - public function test_to_response_sends_correct_attachment_header() - { - $media = $this->testModel->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection(); +test('to response sends correct attachment header', function () { + $media = $this->testModel->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection(); - $response = $media->toResponse(request()); + $response = $media->toResponse(request()); - $this->assertEquals('attachment; filename="test.pdf"', $response->headers->get('Content-Disposition')); - } + expect($response->headers->get('Content-Disposition'))->toEqual('attachment; filename="test.pdf"'); +}); - /** @test */ - public function test_to_inline_response_sends_correct_attachment_header() - { - $media = $this->testModel->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection(); +test('to inline response sends correct attachment header', function () { + $media = $this->testModel->addMedia($this->getTestPdf())->preservingOriginal()->toMediaCollection(); - $response = $media->toInlineResponse(request()); + $response = $media->toInlineResponse(request()); - $this->assertEquals('inline; filename="test.pdf"', $response->headers->get('Content-Disposition')); - } -} + expect($response->headers->get('Content-Disposition'))->toEqual('inline; filename="test.pdf"'); +}); diff --git a/tests/Feature/Media/UpdateManipulationsTest.php b/tests/Feature/Media/UpdateManipulationsTest.php index 42ad47adc..1d3ef6455 100644 --- a/tests/Feature/Media/UpdateManipulationsTest.php +++ b/tests/Feature/Media/UpdateManipulationsTest.php @@ -1,85 +1,75 @@ addMediaConversion('update_test'); - } - }; +it('will create derived files when manipulations have changed', function () { + $testModelClass = new class () extends TestModel { + public function registerMediaConversions(Media $media = null): void + { + $this->addMediaConversion('update_test'); + } + }; - $testModel = $testModelClass::find($this->testModel->id); + $testModel = $testModelClass::find($this->testModel->id); - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - touch($media->getPath('update_test'), time() - 1); + touch($media->getPath('update_test'), time() - 1); - $conversionModificationTime = filemtime($media->getPath('update_test')); + $conversionModificationTime = filemtime($media->getPath('update_test')); - $media->manipulations = [ - 'update_test' => [ - 'width' => 1, - 'height' => 1, - ], - ]; + $media->manipulations = [ + 'update_test' => [ + 'width' => 1, + 'height' => 1, + ], + ]; - $media->save(); + $media->save(); - $modificationTimeAfterManipulationChanged = filemtime($media->getPath('update_test')); + $modificationTimeAfterManipulationChanged = filemtime($media->getPath('update_test')); - $this->assertGreaterThan($conversionModificationTime, $modificationTimeAfterManipulationChanged); - } + expect($modificationTimeAfterManipulationChanged)->toBeGreaterThan($conversionModificationTime); +}); - /** @test */ - public function it_will_not_create_derived_files_when_manipulations_have_not_changed() - { - $testModelClass = new class () extends TestModel { - public function registerMediaConversions(Media $media = null): void - { - $this->addMediaConversion('update_test'); - } - }; +it('will not create derived files when manipulations have not changed', function () { + $testModelClass = new class () extends TestModel { + public function registerMediaConversions(Media $media = null): void + { + $this->addMediaConversion('update_test'); + } + }; - $testModel = $testModelClass::find($this->testModel->id); + $testModel = $testModelClass::find($this->testModel->id); - /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ - $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); + /** @var \Spatie\MediaLibrary\MediaCollections\Models\Media $media */ + $media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); - $media->manipulations = [ - 'update_test' => [ - 'width' => 1, - 'height' => 1, - ], ]; + $media->manipulations = [ + 'update_test' => [ + 'width' => 1, + 'height' => 1, + ], ]; - $media->save(); + $media->save(); - touch($media->getPath('update_test'), time() - 1); + touch($media->getPath('update_test'), time() - 1); - $conversionModificationTime = filemtime($media->getPath('update_test')); + $conversionModificationTime = filemtime($media->getPath('update_test')); - $media->manipulations = [ - 'update_test' => [ - 'width' => 1, - 'height' => 1, - ], ]; + $media->manipulations = [ + 'update_test' => [ + 'width' => 1, + 'height' => 1, + ], ]; - $media->updated_at = now()->addSecond(); + $media->updated_at = now()->addSecond(); - $media->save(); + $media->save(); - $modificationTimeAfterManipulationChanged = filemtime($media->getPath('update_test')); + $modificationTimeAfterManipulationChanged = filemtime($media->getPath('update_test')); - $this->assertEquals($conversionModificationTime, $modificationTimeAfterManipulationChanged); - } -} + expect($modificationTimeAfterManipulationChanged)->toEqual($conversionModificationTime); +}); diff --git a/tests/Feature/Media/__snapshots__/ToHtmlTest__it_can_render_itself_with_responsive_images_and_a_placeholder__1.php b/tests/Feature/Media/__snapshots__/ToHtmlTest__it_can_render_itself_with_responsive_images_and_a_placeholder__1.php index 464524a95..0878d9da8 100644 --- a/tests/Feature/Media/__snapshots__/ToHtmlTest__it_can_render_itself_with_responsive_images_and_a_placeholder__1.php +++ b/tests/Feature/Media/__snapshots__/ToHtmlTest__it_can_render_itself_with_responsive_images_and_a_placeholder__1.php @@ -1,4 +1,4 @@ +return ' '; diff --git a/tests/Feature/Performance/PerformanceTest.php b/tests/Feature/Performance/PerformanceTest.php index 2f0aa8672..13df0cade 100644 --- a/tests/Feature/Performance/PerformanceTest.php +++ b/tests/Feature/Performance/PerformanceTest.php @@ -1,29 +1,19 @@ testModelWithConversion->create(['name' => "test{$index}"]); - $testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); - } - - DB::connection()->enableQueryLog(); +it('can use eagerly loaded media', function () { + foreach (range(1, 10) as $index) { + $testModel = $this->testModelWithConversion->create(['name' => "test{$index}"]); + $testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images'); + } - $testModels = $this->testModelWithConversion->get(); - $testModels->load('media'); + DB::connection()->enableQueryLog(); - foreach ($testModels as $testModel) { - $testModel->getFirstMediaUrl('images', 'thumb'); - } + $testModels = $this->testModelWithConversion->get(); + $testModels->load('media'); - $this->assertCount(2, DB::getQueryLog()); + foreach ($testModels as $testModel) { + $testModel->getFirstMediaUrl('images', 'thumb'); } -} + + expect(DB::getQueryLog())->toHaveCount(2); +}); diff --git a/tests/Feature/S3Integration/S3IntegrationTest.php b/tests/Feature/S3Integration/S3IntegrationTest.php index 323e1814b..ef6bd2e2b 100644 --- a/tests/Feature/S3Integration/S3IntegrationTest.php +++ b/tests/Feature/S3Integration/S3IntegrationTest.php @@ -1,464 +1,241 @@ canTestS3()) { - $this->markTestSkipped('Skipping S3 tests because no S3 env variables found'); - } - - $this->s3BaseDirectory = self::getS3BaseTestDirectory(); - - $this->app['config']->set('media-library.path_generator', S3TestPathGenerator::class); - } - - public function tearDown(): void - { - $this->cleanUpS3(); - - $this->app['config']->set('media-library.path_generator', null); - - parent::tearDown(); - } - - /** @test */ - public function it_can_add_media_from_a_disk_to_s3() - { - $randomNumber = rand(); - - $fileName = "test{$randomNumber}.jpg"; - - Storage::disk('s3_disk')->put("tmp/{$fileName}", file_get_contents($this->getTestJpg())); - - $media = $this->testModel - ->addMediaFromDisk("tmp/{$fileName}", 's3_disk') - ->toMediaCollection('default', 's3_disk'); - - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/{$fileName}"); - } - - /** @test */ - public function it_can_store_a_file_on_s3() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); - - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - } - - /** @test */ - public function it_can_store_a_file_and_its_conversion_on_s3() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); - - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg"); - } - - /** @test */ - public function it_can_delete_a_file_on_s3() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); - - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - - $media->delete(); - - $this->assertS3FileNotExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - } - - /** @test */ - public function it_deletes_file_conversions_on_s3() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); - - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - $this->assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg"); - - $media->delete(); - - $this->assertS3FileNotExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - $this->assertS3FileNotExists("{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg"); +beforeEach(function () { + if (! canTestS3()) { + $this->markTestSkipped('Skipping S3 tests because no S3 getenv variables found'); } - /** @test */ - public function it_retrieve_a_media_url_from_s3() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('default', 's3_disk'); - - $this->assertEquals( - $this->s3BaseUrl()."/{$this->s3BaseDirectory}/{$media->id}/test.jpg", - $media->getUrl() - ); - - $this->assertEquals( - sha1(file_get_contents($this->getTestJpg())), - sha1(file_get_contents($media->getUrl())) - ); - } - - /** @test */ - public function it_retrieve_a_media_conversion_url_from_s3() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); - - $this->assertEquals( - $this->s3BaseUrl()."/{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg", - $media->getUrl('thumb') - ); - } - - /** @test */ - public function it_retrieve_a_media_responsive_urls_from_s3() - { - $media = $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection('default', 's3_disk'); - - $this->assertEquals([ - $this->s3BaseUrl()."/{$this->s3BaseDirectory}/{$media->id}/responsive-images/test___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls('thumb')); - } + $this->s3BaseDirectory = getS3BaseTestDirectory(); - /** @test */ - public function it_retrieves_a_temporary_media_url_from_s3() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('default', 's3_disk'); - - $this->assertStringContainsString( - "/{$this->s3BaseDirectory}/{$media->id}/test.jpg", - $media->getTemporaryUrl(Carbon::now()->addMinutes(5)) - ); - - $this->assertEquals( - sha1(file_get_contents($this->getTestJpg())), - sha1(file_get_contents($media->getTemporaryUrl(Carbon::now()->addMinutes(5)))) - ); - } + config()->set('media-library.path_generator', S3TestPathGenerator::class); +}); - /** @test */ - public function it_retrieves_a_temporary_media_url_from_s3_when_s3_root_not_empty() - { - config()->set('filesystems.disks.s3_disk.root', 'test-root'); - - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection('default', 's3_disk'); - - $this->assertStringContainsString( - "/{$this->s3BaseDirectory}/{$media->id}/test.jpg", - $media->getTemporaryUrl(Carbon::now()->addMinutes(5)) - ); - - $this->assertStringNotContainsString( - '/test-root/test-root', - $media->getTemporaryUrl(Carbon::now()->addMinutes(5)) - ); - - $this->assertEquals( - sha1(file_get_contents($this->getTestJpg())), - sha1(file_get_contents($media->getTemporaryUrl(Carbon::now()->addMinutes(5)))) - ); - } +afterEach(function () { + cleanUpS3(); - /** @test */ - public function it_can_get_the_temporary_url_to_first_media_in_a_collection() - { - $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images', 's3_disk'); - $firstMedia->save(); + config()->set('media-library.path_generator', null); +}); - $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images', 's3_disk'); - $secondMedia->save(); +it('can add media from a disk to s3', function () { + $randomNumber = rand(); - $this->assertEquals($firstMedia->getTemporaryUrl(Carbon::now()->addMinutes(5)), $this->testModel->getFirstTemporaryUrl(Carbon::now()->addMinutes(5), 'images')); - } + $fileName = "test{$randomNumber}.jpg"; - /** @test */ - public function it_retrieves_a_temporary_media_conversion_url_from_s3() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); - - $this->assertStringContainsString( - "/{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg", - $media->getTemporaryUrl(Carbon::now()->addMinutes(5), 'thumb') - ); - } + Storage::disk('s3_disk')->put("tmp/{$fileName}", file_get_contents($this->getTestJpg())); - /** @test */ - public function custom_headers_are_used_for_all_conversions() - { - $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->addCustomHeaders([ - 'ACL' => 'public-read', - ]) - ->toMediaCollection('default', 's3_disk'); - - $client = $this->getS3Client(); - - /** @var \Aws\Result $responseForMainItem */ - $responseForMainItem = $client->execute($client->getCommand('GetObjectAcl', [ - 'Bucket' => getenv('AWS_BUCKET'), - 'Key' => $media->getPath(), - ])); - - $this->assertEquals('READ', $responseForMainItem->get('Grants')[1]['Permission'] ?? null); - - /** @var \Aws\Result $responseForConversion */ - $responseForConversion = $client->execute($client->getCommand('GetObjectAcl', [ - 'Bucket' => getenv('AWS_BUCKET'), - 'Key' => $media->getPath('thumb'), - ])); - - $this->assertEquals('READ', $responseForConversion->get('Grants')[1]['Permission'] ?? null); - } + $media = $this->testModel + ->addMediaFromDisk("tmp/{$fileName}", 's3_disk') + ->toMediaCollection('default', 's3_disk'); - /** @test */ - public function custom_headers_are_used_for_all_conversions_when_adding_private_media_from_same_s3_disk() - { - $randomNumber = rand(); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/{$fileName}"); +}); - $fileName = "test{$randomNumber}.jpg"; +it('can store a file on s3', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - Storage::disk('s3_disk')->put("tmp/{$fileName}", file_get_contents($this->getTestJpg())); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); +}); - $media = $this->testModelWithConversion - ->addMediaFromDisk("tmp/{$fileName}", 's3_disk') - ->addCustomHeaders([ - 'ACL' => 'public-read', - ]) - ->toMediaCollection('default', 's3_disk'); +it('can store a file and its conversion on s3', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - $client = $this->getS3Client(); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg"); +}); - /** @var \Aws\Result $responseForMainItem */ - $responseForMainItem = $client->execute($client->getCommand('GetObjectAcl', [ - 'Bucket' => getenv('AWS_BUCKET'), - 'Key' => $media->getPath(), - ])); +it('can delete a file on s3', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - $this->assertEquals('READ', $responseForMainItem->get('Grants')[1]['Permission'] ?? null); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); - /** @var \Aws\Result $responseForConversion */ - $responseForConversion = $client->execute($client->getCommand('GetObjectAcl', [ - 'Bucket' => getenv('AWS_BUCKET'), - 'Key' => $media->getPath('thumb'), - ])); + $media->delete(); - $this->assertEquals('READ', $responseForConversion->get('Grants')[1]['Permission'] ?? null); - } + assertS3FileNotExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); +}); - /** @test */ - public function extra_headers_are_used_for_all_conversions_when_adding_private_media_from_same_s3_disk() - { - config()->set('media-library.remote.extra_headers', [ - 'ACL' => 'public-read', - ]); +it('deletes file conversions on s3', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - $randomNumber = rand(); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); + assertS3FileExists("{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg"); - $fileName = "test{$randomNumber}.jpg"; + $media->delete(); - Storage::disk('s3_disk')->put("tmp/{$fileName}", file_get_contents($this->getTestJpg())); + assertS3FileNotExists("{$this->s3BaseDirectory}/{$media->id}/test.jpg"); + assertS3FileNotExists("{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg"); +}); - $media = $this->testModelWithConversion - ->addMediaFromDisk("tmp/{$fileName}", 's3_disk') - ->toMediaCollection('default', 's3_disk'); +it('retrieve a media url from s3', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('default', 's3_disk'); - $client = $this->getS3Client(); + $this->assertEquals( + s3BaseUrl()."/{$this->s3BaseDirectory}/{$media->id}/test.jpg", + $media->getUrl() + ); - /** @var \Aws\Result $responseForMainItem */ - $responseForMainItem = $client->execute($client->getCommand('GetObjectAcl', [ - 'Bucket' => getenv('AWS_BUCKET'), - 'Key' => $media->getPath(), - ])); + $this->assertEquals( + sha1(file_get_contents($this->getTestJpg())), + sha1(file_get_contents($media->getUrl())) + ); +}); - $this->assertEquals('READ', $responseForMainItem->get('Grants')[1]['Permission'] ?? null); +it('retrieve a media conversion url from s3', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - /** @var \Aws\Result $responseForConversion */ - $responseForConversion = $client->execute($client->getCommand('GetObjectAcl', [ - 'Bucket' => getenv('AWS_BUCKET'), - 'Key' => $media->getPath('thumb'), - ])); + $this->assertEquals( + s3BaseUrl()."/{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg", + $media->getUrl('thumb') + ); +}); - $this->assertEquals('READ', $responseForConversion->get('Grants')[1]['Permission'] ?? null); - } +it('retrieves a temporary media url from s3 when s3 root not empty', function () { + config()->set('filesystems.disks.s3_disk.root', 'test-root'); - /** @test */ - public function it_can_regenerate_only_missing_with_s3_disk() - { - $mediaExists = $this - ->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection('default', 's3_disk'); - $mediaMissing = $this - ->testModelWithConversion - ->addMedia($this->getTestPng()) - ->toMediaCollection('default', 's3_disk'); + $this->assertStringContainsString( + "/{$this->s3BaseDirectory}/{$media->id}/test.jpg", + $media->getTemporaryUrl(Carbon::now()->addMinutes(5)) + ); - $derivedImageExists = "{$this->s3BaseDirectory}/{$mediaExists->id}/conversions/test-thumb.jpg"; - $derivedMissingImage = "{$this->s3BaseDirectory}/{$mediaMissing->id}/conversions/test-thumb.jpg"; + $this->assertStringNotContainsString( + '/test-root/test-root', + $media->getTemporaryUrl(Carbon::now()->addMinutes(5)) + ); - $existsCreatedAt = Storage::disk('s3_disk')->lastModified($derivedImageExists); - $missingCreatedAt = Storage::disk('s3_disk')->lastModified($derivedMissingImage); + $this->assertEquals( + sha1(file_get_contents($this->getTestJpg())), + sha1(file_get_contents($media->getTemporaryUrl(Carbon::now()->addMinutes(5)))) + ); +}); - Storage::disk('s3_disk')->delete($derivedMissingImage); +it('can get the temporary url to first media in a collection', function () { + $firstMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images', 's3_disk'); + $firstMedia->save(); - $this->assertS3FileNotExists($derivedMissingImage); + $secondMedia = $this->testModel->addMedia($this->getTestJpg())->preservingOriginal()->toMediaCollection('images', 's3_disk'); + $secondMedia->save(); - sleep(1); + expect($this->testModel->getFirstTemporaryUrl(Carbon::now()->addMinutes(5), 'images'))->toEqual($firstMedia->getTemporaryUrl(Carbon::now()->addMinutes(5))); +}); - $this->artisan('media-library:regenerate', [ - '--only-missing' => true, - ]); +it('retrieves a temporary media conversion url from s3', function () { + $media = $this->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - $this->assertS3FileExists($derivedMissingImage); + $this->assertStringContainsString( + "/{$this->s3BaseDirectory}/{$media->id}/conversions/test-thumb.jpg", + $media->getTemporaryUrl(Carbon::now()->addMinutes(5), 'thumb') + ); +}); - $this->assertSame($existsCreatedAt, Storage::disk('s3_disk')->lastModified($derivedImageExists)); - $this->assertGreaterThan($missingCreatedAt, Storage::disk('s3_disk')->lastModified($derivedMissingImage)); - } +it('can regenerate only missing with s3 disk', function () { + $mediaExists = $this + ->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - /** @test */ - public function it_can_regenerate_only_missing_files_of_named_conversions_with_s3_disk() - { - $mediaExists = $this - ->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->toMediaCollection('images', 's3_disk'); + $mediaMissing = $this + ->testModelWithConversion + ->addMedia($this->getTestPng()) + ->toMediaCollection('default', 's3_disk'); + + $derivedImageExists = "{$this->s3BaseDirectory}/{$mediaExists->id}/conversions/test-thumb.jpg"; + $derivedMissingImage = "{$this->s3BaseDirectory}/{$mediaMissing->id}/conversions/test-thumb.jpg"; + + $existsCreatedAt = Storage::disk('s3_disk')->lastModified($derivedImageExists); + $missingCreatedAt = Storage::disk('s3_disk')->lastModified($derivedMissingImage); - $mediaMissing = $this - ->testModelWithConversion - ->addMedia($this->getTestPng()) - ->toMediaCollection('images', 's3_disk'); + Storage::disk('s3_disk')->delete($derivedMissingImage); + + assertS3FileNotExists($derivedMissingImage); - $derivedImageExists = "{$this->s3BaseDirectory}/{$mediaExists->id}/conversions/test-thumb.jpg"; - $derivedMissingImage = "{$this->s3BaseDirectory}/{$mediaMissing->id}/conversions/test-thumb.jpg"; - $derivedMissingImageOriginal = "{$this->s3BaseDirectory}/{$mediaMissing->id}/conversions/test-keep_original_format.png"; + sleep(1); + + $this->artisan('media-library:regenerate', [ + '--only-missing' => true, + ]); + + assertS3FileExists($derivedMissingImage); + + expect(Storage::disk('s3_disk')->lastModified($derivedImageExists))->toBe($existsCreatedAt); + expect(Storage::disk('s3_disk')->lastModified($derivedMissingImage))->toBeGreaterThan($missingCreatedAt); +}); - $existsCreatedAt = Storage::disk('s3_disk')->lastModified($derivedImageExists); - $missingCreatedAt = Storage::disk('s3_disk')->lastModified($derivedMissingImage); +it('can regenerate only missing files of named conversions with s3 disk', function () { + $mediaExists = $this + ->testModelWithConversion + ->addMedia($this->getTestJpg()) + ->toMediaCollection('images', 's3_disk'); + + $mediaMissing = $this + ->testModelWithConversion + ->addMedia($this->getTestPng()) + ->toMediaCollection('images', 's3_disk'); - Storage::disk('s3_disk')->delete($derivedMissingImage); - Storage::disk('s3_disk')->delete($derivedMissingImageOriginal); + $derivedImageExists = "{$this->s3BaseDirectory}/{$mediaExists->id}/conversions/test-thumb.jpg"; + $derivedMissingImage = "{$this->s3BaseDirectory}/{$mediaMissing->id}/conversions/test-thumb.jpg"; + $derivedMissingImageOriginal = "{$this->s3BaseDirectory}/{$mediaMissing->id}/conversions/test-keep_original_format.png"; - $this->assertS3FileNotExists($derivedMissingImage); - $this->assertS3FileNotExists($derivedMissingImageOriginal); + $existsCreatedAt = Storage::disk('s3_disk')->lastModified($derivedImageExists); + $missingCreatedAt = Storage::disk('s3_disk')->lastModified($derivedMissingImage); - sleep(1); + Storage::disk('s3_disk')->delete($derivedMissingImage); + Storage::disk('s3_disk')->delete($derivedMissingImageOriginal); - $this->artisan('media-library:regenerate', [ - '--only-missing' => true, - '--only' => 'thumb', - ]); + assertS3FileNotExists($derivedMissingImage); + assertS3FileNotExists($derivedMissingImageOriginal); - $this->assertS3FileExists($derivedMissingImage); - $this->assertS3FileNotExists($derivedMissingImageOriginal); - $this->assertSame($existsCreatedAt, Storage::disk('s3_disk')->lastModified($derivedImageExists)); - $this->assertGreaterThan($missingCreatedAt, Storage::disk('s3_disk')->lastModified($derivedMissingImage)); - } + sleep(1); - /** @test */ - public function it_can_retrieve_a_zip_with_s3_disk() - { - $media = $this->testModel - ->addMedia($this->getTestJpg()) - ->toMediaCollection('default', 's3_disk'); + $this->artisan('media-library:regenerate', [ + '--only-missing' => true, + '--only' => 'thumb', + ]); - $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia($media); + assertS3FileExists($derivedMissingImage); + assertS3FileNotExists($derivedMissingImageOriginal); + expect(Storage::disk('s3_disk')->lastModified($derivedImageExists))->toBe($existsCreatedAt); + expect(Storage::disk('s3_disk')->lastModified($derivedMissingImage))->toBeGreaterThan($missingCreatedAt); +}); - ob_start(); - @$zipStreamResponse->toResponse(request())->sendContent(); - $content = ob_get_contents(); - ob_end_clean(); +it('can retrieve a zip with s3 disk', function () { + $media = $this->testModel + ->addMedia($this->getTestJpg()) + ->toMediaCollection('default', 's3_disk'); - $temporaryDirectory = (new TemporaryDirectory())->create(); - file_put_contents($temporaryDirectory->path('response.zip'), $content); + $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia($media); - $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test.jpg'); - } + ob_start(); + @$zipStreamResponse->toResponse(request())->sendContent(); + $content = ob_get_contents(); + ob_end_clean(); - protected function cleanUpS3() - { - collect(Storage::disk('s3_disk')->allDirectories(self::getS3BaseTestDirectory()))->each(function ($directory) { - Storage::disk('s3_disk')->deleteDirectory($directory); - }); - } + $temporaryDirectory = (new TemporaryDirectory())->create(); + file_put_contents($temporaryDirectory->path('response.zip'), $content); - protected function getS3Client(): S3Client - { - /** @var \Illuminate\Filesystem\FilesystemAdapter $disk */ - $disk = app(Factory::class)->disk('s3_disk'); - - /** @var \Aws\S3\S3Client $client */ - $client = $disk->getDriver()->getAdapter()->getClient(); - - return $client; - } - - protected function assertS3FileExists(string $filePath) - { - $this->assertTrue(Storage::disk('s3_disk')->has($filePath)); - } - - protected function assertS3FileNotExists(string $filePath) - { - $this->assertFalse(Storage::disk('s3_disk')->has($filePath)); - } - - public function canTestS3() - { - return ! empty(getenv('AWS_ACCESS_KEY_ID')); - } - - public static function getS3BaseTestDirectory(): string - { - static $uuid = null; - - if (is_null($uuid)) { - $uuid = Str::uuid(); - } - - return $uuid; - } - - public function s3BaseUrl(): string - { - return 'https://laravel-medialibrary-tests.s3.eu-west-1.amazonaws.com'; - } -} + $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test.jpg'); +}); diff --git a/tests/Feature/S3Integration/S3TestPathGenerator.php b/tests/Feature/S3Integration/S3TestPathGenerator.php index d3edca0ad..b77822097 100644 --- a/tests/Feature/S3Integration/S3TestPathGenerator.php +++ b/tests/Feature/S3Integration/S3TestPathGenerator.php @@ -33,6 +33,6 @@ public function getPathForResponsiveImages(Media $media): string */ protected function getBasePath(Media $media): string { - return (S3IntegrationTest::getS3BaseTestDirectory()).'/'.$media->getKey(); + return (getS3BaseTestDirectory()).'/'.$media->getKey(); } } diff --git a/tests/Image/ImageFactoryTest.php b/tests/Image/ImageFactoryTest.php index bacc43e3d..8fcf82ae7 100644 --- a/tests/Image/ImageFactoryTest.php +++ b/tests/Image/ImageFactoryTest.php @@ -1,28 +1,19 @@ 'imagick']); +test('loading an image uses the correct driver', function () { + config(['media-library.image_driver' => 'imagick']); - $image = ImageFactory::load($this->getTestJpg()); + $image = ImageFactory::load($this->getTestJpg()); - $reflection = new ReflectionClass($image); + $reflection = new ReflectionClass($image); - $imageDriver = $reflection->getProperty('imageDriver'); + $imageDriver = $reflection->getProperty('imageDriver'); - $imageDriver->setAccessible(true); + $imageDriver->setAccessible(true); - $imageDriverValue = $imageDriver->getValue($image); + $imageDriverValue = $imageDriver->getValue($image); - $this->assertEquals('imagick', $imageDriverValue); - } -} + expect($imageDriverValue)->toEqual('imagick'); +}); diff --git a/tests/MediaCollections/EventTest.php b/tests/MediaCollections/EventTest.php index db4c2b84b..eb9e23a50 100644 --- a/tests/MediaCollections/EventTest.php +++ b/tests/MediaCollections/EventTest.php @@ -1,25 +1,12 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection(); + $this->testModel->addMedia($this->getTestJpg())->toMediaCollection(); - Event::assertDispatched(MediaHasBeenAdded::class); - } -} + Event::assertDispatched(MediaHasBeenAdded::class); +}); diff --git a/tests/MediaCollections/FileSystem/FileSystemTest.php b/tests/MediaCollections/FileSystem/FileSystemTest.php index e610b3fc8..1071410da 100644 --- a/tests/MediaCollections/FileSystem/FileSystemTest.php +++ b/tests/MediaCollections/FileSystem/FileSystemTest.php @@ -1,69 +1,52 @@ filesystem = $this->app->make(Filesystem::class); - } - - /** @test */ - public function it_can_determine_the_header_for_file_that_will_be_copied_to_an_external_filesytem() - { - $expectedHeaders = [ - 'ContentType' => 'image/jpeg', - 'CacheControl' => 'max-age=604800', - ]; - - $this->assertEquals( - $expectedHeaders, - $this->filesystem->getRemoteHeadersForFile($this->getTestJpg()) - ); - } - - /** @test */ - public function it_can_add_custom_headers_for_file_that_will_be_copied_to_an_external_filesytem() - { - $this->filesystem->addCustomRemoteHeaders([ - 'ACL' => 'public-read', - ]); - - $expectedHeaders = [ - 'ContentType' => 'image/jpeg', - 'CacheControl' => 'max-age=604800', - 'ACL' => 'public-read', - ]; - - $this->assertEquals( - $expectedHeaders, - $this->filesystem->getRemoteHeadersForFile($this->getTestJpg()) - ); - } - - /** @test */ - public function it_can_use_custom_headers_when_copying_the_media_to_an_external_filesystem() - { - $this->filesystem->addCustomRemoteHeaders([ - 'CacheControl' => 'max-age=302400', - ]); - - $expectedHeaders = [ - 'ContentType' => 'image/jpeg', - 'CacheControl' => 'max-age=302400', - ]; - $this->assertEquals( - $expectedHeaders, - $this->filesystem->getRemoteHeadersForFile($this->getTestJpg()) - ); - } -} +beforeEach(function () { + $this->filesystem = app()->make(Filesystem::class); +}); + +it('can determine the header for file that will be copied to an external filesytem', function () { + $expectedHeaders = [ + 'ContentType' => 'image/jpeg', + 'CacheControl' => 'max-age=604800', + ]; + + $this->assertEquals( + $expectedHeaders, + $this->filesystem->getRemoteHeadersForFile($this->getTestJpg()) + ); +}); + +it('can add custom headers for file that will be copied to an external filesytem', function () { + $this->filesystem->addCustomRemoteHeaders([ + 'ACL' => 'public-read', + ]); + + $expectedHeaders = [ + 'ContentType' => 'image/jpeg', + 'CacheControl' => 'max-age=604800', + 'ACL' => 'public-read', + ]; + + $this->assertEquals( + $expectedHeaders, + $this->filesystem->getRemoteHeadersForFile($this->getTestJpg()) + ); +}); + +it('can use custom headers when copying the media to an external filesystem', function () { + $this->filesystem->addCustomRemoteHeaders([ + 'CacheControl' => 'max-age=302400', + ]); + + $expectedHeaders = [ + 'ContentType' => 'image/jpeg', + 'CacheControl' => 'max-age=302400', + ]; + + $this->assertEquals( + $expectedHeaders, + $this->filesystem->getRemoteHeadersForFile($this->getTestJpg()) + ); +}); diff --git a/tests/MediaCollections/MediaCollectionTest.php b/tests/MediaCollections/MediaCollectionTest.php index 1cda7a782..a1059b7a9 100644 --- a/tests/MediaCollections/MediaCollectionTest.php +++ b/tests/MediaCollections/MediaCollectionTest.php @@ -1,98 +1,84 @@ testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - $this->assertGreaterThan(0, $mediaItem->size); - - $anotherMediaItem = $this - ->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - $this->assertGreaterThan(0, $anotherMediaItem->size); - - $mediaCollection = Media::get(); - - $totalSize = $mediaCollection->totalSizeInBytes(); - - $this->assertEquals($mediaItem->size + $anotherMediaItem->size, $totalSize); - } - - /** @test */ - public function it_can_get_registered_media_collections() - { - // the 'avatar' media collection is registered in - // \Spatie\MediaLibrary\Tests\TestSupport\TestModels\TestModel->registerMediaCollections() - $collections = $this->testModel->getRegisteredMediaCollections(); - - $this->assertCount(1, $collections); - $this->assertInstanceOf(MediaCollection::class, $collections->first()); - $this->assertEquals('avatar', $collections->first()->name); - } - - /** @test */ - public function it_doesnt_move_media_on_change() - { - config([ - 'media-library.path_generator' => TestUuidPathGenerator::class, - 'media-library.moves_media_on_update' => false, - ]); - - $mediaItem = $this - ->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - - $oldMediaPath = $mediaItem->getPath(); - - $this->assertFileExists($oldMediaPath); - - $mediaItem->update(['uuid' => Str::uuid()]); - - $this->assertNotEquals($oldMediaPath, $mediaItem->getPath()); - $this->assertFileExists($oldMediaPath); - $this->assertFileDoesNotExist($mediaItem->getPath()); - } - - /** @test */ - public function it_moves_media_on_change() - { - config([ - 'media-library.path_generator' => TestUuidPathGenerator::class, - 'media-library.moves_media_on_update' => true, - ]); - - $mediaItem = $this - ->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - - $oldMediaPath = $mediaItem->getPath(); - - $this->assertFileExists($oldMediaPath); - - $mediaItem->update(['uuid' => Str::uuid()]); - - $this->assertNotEquals($oldMediaPath, $mediaItem->getPath()); - $this->assertFileDoesNotExist($oldMediaPath); - $this->assertFileExists($mediaItem->getPath()); - } -} +it('can get the sum of all media item sizes', function () { + $mediaItem = $this + ->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + expect($mediaItem->size)->toBeGreaterThan(0); + + $anotherMediaItem = $this + ->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + expect($anotherMediaItem->size)->toBeGreaterThan(0); + + $mediaCollection = Media::get(); + + $totalSize = $mediaCollection->totalSizeInBytes(); + + expect($totalSize)->toEqual($mediaItem->size + $anotherMediaItem->size); +}); + +it('can get registered media collections', function () { + // the 'avatar' media collection is registered in + // \Spatie\MediaLibrary\Tests\TestSupport\TestModels\TestModel->registerMediaCollections() + $collections = $this->testModel->getRegisteredMediaCollections(); + + expect($collections)->toHaveCount(1); + expect($collections->first())->toBeInstanceOf(MediaCollection::class); + expect($collections->first()->name)->toEqual('avatar'); +}); + +it('doesnt move media on change', function () { + config([ + 'media-library.path_generator' => TestUuidPathGenerator::class, + 'media-library.moves_media_on_update' => false, + ]); + + $mediaItem = $this + ->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + + $oldMediaPath = $mediaItem->getPath(); + + expect($oldMediaPath)->toBeFile(); + + $mediaItem->update(['uuid' => Str::uuid()]); + + $this->assertNotEquals($oldMediaPath, $mediaItem->getPath()); + expect($oldMediaPath)->toBeFile(); + $this->assertFileDoesNotExist($mediaItem->getPath()); +}); + +it('moves media on change', function () { + config([ + 'media-library.path_generator' => TestUuidPathGenerator::class, + 'media-library.moves_media_on_update' => true, + ]); + + $mediaItem = $this + ->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); + + $oldMediaPath = $mediaItem->getPath(); + + expect($oldMediaPath)->toBeFile(); + + $mediaItem->update(['uuid' => Str::uuid()]); + + $this->assertNotEquals($oldMediaPath, $mediaItem->getPath()); + $this->assertFileDoesNotExist($oldMediaPath); + expect($mediaItem->getPath())->toBeFile(); +}); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 000000000..7af2818c2 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,52 @@ +in(__DIR__); + +expect()->extend('toHaveExtension', function (string $expectedExtension) { + $actualExtension = pathinfo($this->value, PATHINFO_EXTENSION); + + expect($actualExtension)->toEqual($expectedExtension); +}); + +function assertS3FileExists(string $filePath): void +{ + expect(Storage::disk('s3_disk')->exists($filePath))->toBeTrue(); +} + +function assertS3FileNotExists(string $filePath): void +{ + expect(Storage::disk('s3_disk')->exists($filePath))->toBeFalse(); +} + +function canTestS3(): bool +{ + return ! empty(getenv('AWS_ACCESS_KEY_ID')); +} + +function getS3BaseTestDirectory(): string +{ + static $uuid = null; + + if (is_null($uuid)) { + $uuid = Str::uuid(); + } + + return $uuid; +} + +function s3BaseUrl(): string +{ + return 'https://laravel-medialibrary-tests.s3.eu-west-1.amazonaws.com'; +} + +function cleanUpS3(): void +{ + collect(Storage::disk('s3_disk')->allDirectories(getS3BaseTestDirectory())) + ->each(function ($directory) { + Storage::disk('s3_disk')->deleteDirectory($directory); + }); +} diff --git a/tests/ResponsiveImages/FileSizeOptimizedWidthCalculatorTest.php b/tests/ResponsiveImages/FileSizeOptimizedWidthCalculatorTest.php index 20ae9d22e..6e4225d1f 100644 --- a/tests/ResponsiveImages/FileSizeOptimizedWidthCalculatorTest.php +++ b/tests/ResponsiveImages/FileSizeOptimizedWidthCalculatorTest.php @@ -1,92 +1,82 @@ calculateWidthsFromFile($this->getTestJpg()); +it('can calculate the optimized widths from a file', function () { + $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidthsFromFile($this->getTestJpg()); - $this->assertEquals([ - 0 => 340, - 1 => 284, - 2 => 237, - ], $dimensions->toArray()); + $this->assertEquals([ + 0 => 340, + 1 => 284, + 2 => 237, + ], $dimensions->toArray()); - $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidthsFromFile($this->getSmallTestJpg()); + $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidthsFromFile($this->getSmallTestJpg()); - $this->assertEquals([ - 0 => 150, - ], $dimensions->toArray()); - } + $this->assertEquals([ + 0 => 150, + ], $dimensions->toArray()); +}); - /** @test */ - public function it_can_calculate_the_optimized_widths_for_different_dimensions() - { - $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidths(300 * 1024, 300, 200); +it('can calculate the optimized widths for different dimensions', function () { + $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidths(300 * 1024, 300, 200); - $this->assertEquals([ - 0 => 300, - 1 => 250, - 2 => 210, - 3 => 175, - 4 => 147, - 5 => 122, - 6 => 102, - 7 => 86, - 8 => 72, - 9 => 60, - ], $dimensions->toArray()); + $this->assertEquals([ + 0 => 300, + 1 => 250, + 2 => 210, + 3 => 175, + 4 => 147, + 5 => 122, + 6 => 102, + 7 => 86, + 8 => 72, + 9 => 60, + ], $dimensions->toArray()); - $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidths(3000 * 1024, 2400, 1800); + $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidths(3000 * 1024, 2400, 1800); - $this->assertEquals([ - 0 => 2400, - 1 => 2007, - 2 => 1680, - 3 => 1405, - 4 => 1176, - 5 => 983, - 6 => 823, - 7 => 688, - 8 => 576, - 9 => 482, - 10 => 403, - 11 => 337, - 12 => 282, - 13 => 236, - 14 => 197, - 15 => 165, - ], $dimensions->toArray()); + $this->assertEquals([ + 0 => 2400, + 1 => 2007, + 2 => 1680, + 3 => 1405, + 4 => 1176, + 5 => 983, + 6 => 823, + 7 => 688, + 8 => 576, + 9 => 482, + 10 => 403, + 11 => 337, + 12 => 282, + 13 => 236, + 14 => 197, + 15 => 165, + ], $dimensions->toArray()); - $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidths(12000 * 1024, 8200, 5500); + $dimensions = (new FileSizeOptimizedWidthCalculator())->calculateWidths(12000 * 1024, 8200, 5500); - $this->assertEquals([ - 0 => 8200, - 1 => 6860, - 2 => 5740, - 3 => 4802, - 4 => 4017, - 5 => 3361, - 6 => 2812, - 7 => 2353, - 8 => 1968, - 9 => 1647, - 10 => 1378, - 11 => 1153, - 12 => 964, - 13 => 807, - 14 => 675, - 15 => 565, - 16 => 472, - 17 => 395, - 18 => 330, - 19 => 276, - ], $dimensions->toArray()); - } -} + $this->assertEquals([ + 0 => 8200, + 1 => 6860, + 2 => 5740, + 3 => 4802, + 4 => 4017, + 5 => 3361, + 6 => 2812, + 7 => 2353, + 8 => 1968, + 9 => 1647, + 10 => 1378, + 11 => 1153, + 12 => 964, + 13 => 807, + 14 => 675, + 15 => 565, + 16 => 472, + 17 => 395, + 18 => 330, + 19 => 276, + ], $dimensions->toArray()); +}); diff --git a/tests/ResponsiveImages/RegisteredResponsiveImagesTest.php b/tests/ResponsiveImages/RegisteredResponsiveImagesTest.php index 1da9429ed..ef9bcdd66 100644 --- a/tests/ResponsiveImages/RegisteredResponsiveImagesTest.php +++ b/tests/ResponsiveImages/RegisteredResponsiveImagesTest.php @@ -1,49 +1,39 @@ testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); +it('will register generated responsive images in the db', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); - $media = $this->testModel->getFirstMedia(); + $media = $this->testModel->getFirstMedia(); - $this->assertEquals([ - 'test___media_library_original_340_280.jpg', - 'test___media_library_original_284_233.jpg', - 'test___media_library_original_237_195.jpg', - ], $media->responsive_images['media_library_original']['urls']); - } + $this->assertEquals([ + 'test___media_library_original_340_280.jpg', + 'test___media_library_original_284_234.jpg', + 'test___media_library_original_237_195.jpg', + ], $media->responsive_images['media_library_original']['urls']); +}); - /** @test */ - public function it_can_render_a_srcset_when_the_base64svg_is_not_rendered_yet() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); +it('can render a srcset when the base64svg is not rendered yet', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); - $media = $this->testModel->getFirstMedia(); + $media = $this->testModel->getFirstMedia(); - $responsiveImages = $media->responsive_images; + $responsiveImages = $media->responsive_images; - unset($responsiveImages['media_library_original']['base64svg']); + unset($responsiveImages['media_library_original']['base64svg']); - $media->responsive_images = $responsiveImages; + $media->responsive_images = $responsiveImages; - $registeredResponsiveImage = new RegisteredResponsiveImages($media); + $registeredResponsiveImage = new RegisteredResponsiveImages($media); - $this->assertNull($registeredResponsiveImage->getPlaceholderSvg()); + expect($registeredResponsiveImage->getPlaceholderSvg())->toBeNull(); - $this->assertNotEmpty($registeredResponsiveImage->getSrcset()); - } -} + $this->assertNotEmpty($registeredResponsiveImage->getSrcset()); +}); diff --git a/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php b/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php index f118b1b17..6c30ce2a0 100644 --- a/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php +++ b/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php @@ -1,18 +1,10 @@ set("media-library.file_namer", TestFileNamer::class); +beforeEach(function () { + config()->set("media-library.file_namer", TestFileNamer::class); - $this->fileName = "prefix_test_suffix"; - $this->fileNameWithUnderscore = "prefix_test__suffix"; - } -} + $this->fileName = "prefix_test_suffix"; + $this->fileNameWithUnderscore = "prefix_test__suffix"; +}); diff --git a/tests/ResponsiveImages/ResponsiveImageGeneratorFileNamerTest.php b/tests/ResponsiveImages/ResponsiveImageGeneratorFileNamerTest.php index d89dce928..d074f2753 100644 --- a/tests/ResponsiveImages/ResponsiveImageGeneratorFileNamerTest.php +++ b/tests/ResponsiveImages/ResponsiveImageGeneratorFileNamerTest.php @@ -1,17 +1,9 @@ set("media-library.file_namer", TestFileNamer::class); +beforeEach(function () { + config()->set("media-library.file_namer", TestFileNamer::class); - $this->fileName = "prefix_test_suffix"; - } -} + $this->fileName = "prefix_test_suffix"; +}); diff --git a/tests/ResponsiveImages/ResponsiveImageGeneratorTest.php b/tests/ResponsiveImages/ResponsiveImageGeneratorTest.php index 9505ef1f7..1dbe205cd 100644 --- a/tests/ResponsiveImages/ResponsiveImageGeneratorTest.php +++ b/tests/ResponsiveImages/ResponsiveImageGeneratorTest.php @@ -1,117 +1,97 @@ testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg")); - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_284_233.jpg")); - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg")); - } - - /** @test */ - public function it_will_generate_responsive_images_if_withResponsiveImagesIf_returns_true() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImagesIf(fn () => true) - ->toMediaCollection(); - - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg")); - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_284_233.jpg")); - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg")); - } - - /** @test */ - public function it_will_not_generate_responsive_images_if_withResponsiveImagesIf_returns_false() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImagesIf(fn () => false) - ->toMediaCollection(); +beforeEach(function () { + $this->fileName = 'test'; +}); - $this->assertFileDoesNotExist($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg")); - } - - /** @test */ - public function its_conversions_can_have_responsive_images() - { - $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg")); - } - - /** @test */ - public function its_conversions_can_have_responsive_images_and_change_format() - { - $this->testModelWithResponsiveImages - ->addMedia($this->getTestPng()) +it('can generate responsive images', function () { + $this->testModel + ->addMedia($this->getTestJpg()) ->withResponsiveImages() ->toMediaCollection(); - $this->assertFileExists($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___pngtojpg_700_883.jpg")); - } - - /** @test */ - public function it_triggers_an_event_when_the_responsive_images_are_generated() - { - Event::fake(ResponsiveImagesGenerated::class); + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg"))->toBeFile(); + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_284_234.jpg"))->toBeFile(); + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg"))->toBeFile(); +}); - $this->testModelWithResponsiveImages +it('will generate responsive images if with responsive images if returns true', function () { + $this->testModel ->addMedia($this->getTestJpg()) - ->withResponsiveImages() + ->withResponsiveImagesIf(fn () => true) ->toMediaCollection(); - Event::assertDispatched(ResponsiveImagesGenerated::class); - } + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg"))->toBeFile(); + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_284_234.jpg"))->toBeFile(); + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg"))->toBeFile(); +}); - /** @test */ - public function it_cleans_the_responsive_images_urls_from_the_db_before_regeneration() - { - $media = $this->testModelWithResponsiveImages - ->addMedia($this->getTestFilesDirectory("test.jpg")) - ->withResponsiveImages() +it('will not generate responsive images if with responsive images if returns false', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->withResponsiveImagesIf(fn () => false) ->toMediaCollection(); - $this->assertCount(1, $media->fresh()->responsive_images["thumb"]["urls"]); + $this->assertFileDoesNotExist($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg")); +}); - $this->artisan("media-library:regenerate"); - $this->assertCount(1, $media->fresh()->responsive_images["thumb"]["urls"]); - } - - /** @test */ - public function it_will_add_responsive_image_entries_when_there_were_none_when_regenerating() - { - $media = $this->testModelWithResponsiveImages - ->addMedia($this->getTestFilesDirectory("test.jpg")) - ->withResponsiveImages() - ->toMediaCollection(); +test('its conversions can have responsive images', function () { + $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); - // remove all responsive image db entries - $responsiveImages = $media->responsive_images; - $responsiveImages["thumb"]["urls"] = []; - $media->responsive_images = $responsiveImages; - $media->save(); - $this->assertCount(0, $media->fresh()->responsive_images["thumb"]["urls"]); - - $this->artisan("media-library:regenerate"); - $this->assertCount(1, $media->fresh()->responsive_images["thumb"]["urls"]); - } -} + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg"))->toBeFile(); +}); + +test('its conversions can have responsive images and change format', function () { + $this->testModelWithResponsiveImages + ->addMedia($this->getTestPng()) + ->withResponsiveImages() + ->toMediaCollection(); + + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___pngtojpg_700_883.jpg"))->toBeFile(); +}); + +it('triggers an event when the responsive images are generated', function () { + Event::fake(ResponsiveImagesGenerated::class); + + $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); + + Event::assertDispatched(ResponsiveImagesGenerated::class); +}); + +it('cleans the responsive images urls from the db before regeneration', function () { + $media = $this->testModelWithResponsiveImages + ->addMedia($this->getTestFilesDirectory("test.jpg")) + ->withResponsiveImages() + ->toMediaCollection(); + + expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(1); + + $this->artisan("media-library:regenerate"); + expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(1); +}); + +it('will add responsive image entries when there were none when regenerating', function () { + $media = $this->testModelWithResponsiveImages + ->addMedia($this->getTestFilesDirectory("test.jpg")) + ->withResponsiveImages() + ->toMediaCollection(); + + // remove all responsive image db entries + $responsiveImages = $media->responsive_images; + $responsiveImages["thumb"]["urls"] = []; + $media->responsive_images = $responsiveImages; + $media->save(); + expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(0); + + $this->artisan("media-library:regenerate"); + expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(1); +}); diff --git a/tests/ResponsiveImages/ResponsiveImageTest.php b/tests/ResponsiveImages/ResponsiveImageTest.php index 8f9628945..11fac66b7 100644 --- a/tests/ResponsiveImages/ResponsiveImageTest.php +++ b/tests/ResponsiveImages/ResponsiveImageTest.php @@ -1,131 +1,114 @@ testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - $media = $this->testModelWithResponsiveImages->getFirstMedia(); - - $this->assertEquals([ - "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg", - "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_284_233.jpg", - "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg", - ], $media->getResponsiveImageUrls()); - - $this->assertEquals([ - "http://localhost/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls("thumb")); - - $this->assertEquals([], $media->getResponsiveImageUrls("non-existing-conversion")); - } - - /** @test */ - public function a_media_instance_can_generate_the_contents_of_scrset() - { - $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - $media = $this->testModelWithResponsiveImages->getFirstMedia(); - - $this->assertStringContainsString( - "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg 340w, http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_284_233.jpg 284w, http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg 237w", - $media->getSrcset() - ); - $this->assertStringContainsString("data:image/svg+xml;base64", $media->getSrcset()); - - $this->assertStringContainsString( - "http://localhost/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg 50w", - $media->getSrcset("thumb") - ); - $this->assertStringContainsString("data:image/svg+xml;base64,", $media->getSrcset("thumb")); - } - - /** @test */ - public function a_responsive_image_can_return_some_properties() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - $media = $this->testModel->getFirstMedia(); - - $responsiveImage = $media->responsiveImages()->files->first(); - - $this->assertEquals("media_library_original", $responsiveImage->generatedFor()); - - $this->assertEquals(340, $responsiveImage->width()); - - $this->assertEquals(280, $responsiveImage->height()); - } - - /** @test */ - public function responsive_image_generation_respects_the_conversion_quality_setting() - { - $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection("default"); - - $standardQualityResponsiveConversion = $this->getTempDirectory("media/1/responsive-images/{$this->fileName}___standardQuality_340_280.jpg"); - $lowerQualityResponsiveConversion = $this->getTempDirectory("media/1/responsive-images/{$this->fileName}___lowerQuality_340_280.jpg"); - - $this->assertLessThan(filesize($standardQualityResponsiveConversion), filesize($lowerQualityResponsiveConversion)); - } - - /** @test */ - public function a_media_instance_can_get_responsive_image_urls_with_conversions_stored_on_second_media_disk() - { - $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->storingConversionsOnDisk("secondMediaDisk") - ->toMediaCollection(); - - $media = $this->testModelWithResponsiveImages->getFirstMedia(); - - $this->assertEquals([ - "http://localhost/media2/1/responsive-images/{$this->fileName}___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls("thumb")); - } - - /** @test */ - public function it_can_handle_file_names_with_underscore() - { - $this - ->testModelWithResponsiveImages - ->addMedia($this->getTestImageEndingWithUnderscore()) - ->withResponsiveImages() - ->toMediaCollection(); - - $media = $this->testModelWithResponsiveImages->getFirstMedia(); - - $this->assertSame([ - "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___media_library_original_340_280.jpg", - "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___media_library_original_284_233.jpg", - "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___media_library_original_237_195.jpg", - ], $media->getResponsiveImageUrls()); - - $this->assertSame([ - "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls("thumb")); - - $this->assertSame([], $media->getResponsiveImageUrls("non-existing-conversion")); - } -} +beforeEach(function () { + $this->fileName = 'test'; + $this->fileNameWithUnderscore = 'test_'; +}); + +test('a media instance can get responsive image urls', function () { + $this + ->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); + + $media = $this->testModelWithResponsiveImages->getFirstMedia(); + + $this->assertEquals([ + "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg", + "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_284_234.jpg", + "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg", + ], $media->getResponsiveImageUrls()); + + $this->assertEquals([ + "http://localhost/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg", + ], $media->getResponsiveImageUrls("thumb")); + + expect($media->getResponsiveImageUrls("non-existing-conversion"))->toEqual([]); +}); + +test('a media instance can generate the contents of scrset', function () { + $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); + + $media = $this->testModelWithResponsiveImages->getFirstMedia(); + + $this->assertStringContainsString( + "http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg 340w, http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_284_234.jpg 284w, http://localhost/media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg 237w", + $media->getSrcset() + ); + expect($media->getSrcset())->toContain("data:image/svg+xml;base64"); + + $this->assertStringContainsString( + "http://localhost/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg 50w", + $media->getSrcset("thumb") + ); + expect($media->getSrcset("thumb"))->toContain("data:image/svg+xml;base64,"); +}); + +test('a responsive image can return some properties', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); + + $media = $this->testModel->getFirstMedia(); + + $responsiveImage = $media->responsiveImages()->files->first(); + + expect($responsiveImage->generatedFor())->toEqual("media_library_original"); + + expect($responsiveImage->width())->toEqual(340); + + expect($responsiveImage->height())->toEqual(280); +}); + +test('responsive image generation respects the conversion quality setting', function () { + $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection("default"); + + $standardQualityResponsiveConversion = $this->getTempDirectory("media/1/responsive-images/{$this->fileName}___standardQuality_340_280.jpg"); + $lowerQualityResponsiveConversion = $this->getTempDirectory("media/1/responsive-images/{$this->fileName}___lowerQuality_340_280.jpg"); + + expect(filesize($lowerQualityResponsiveConversion))->toBeLessThan(filesize($standardQualityResponsiveConversion)); +}); + +test('a media instance can get responsive image urls with conversions stored on second media disk', function () { + $this->testModelWithResponsiveImages + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->storingConversionsOnDisk("secondMediaDisk") + ->toMediaCollection(); + + $media = $this->testModelWithResponsiveImages->getFirstMedia(); + + $this->assertEquals([ + "http://localhost/media2/1/responsive-images/{$this->fileName}___thumb_50_41.jpg", + ], $media->getResponsiveImageUrls("thumb")); +}); + +it('can handle file names with underscore', function () { + $this + ->testModelWithResponsiveImages + ->addMedia($this->getTestImageEndingWithUnderscore()) + ->withResponsiveImages() + ->toMediaCollection(); + + $media = $this->testModelWithResponsiveImages->getFirstMedia(); + + $this->assertSame([ + "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___media_library_original_340_280.jpg", + "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___media_library_original_284_234.jpg", + "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___media_library_original_237_195.jpg", + ], $media->getResponsiveImageUrls()); + + $this->assertSame([ + "http://localhost/media/1/responsive-images/{$this->fileNameWithUnderscore}___thumb_50_41.jpg", + ], $media->getResponsiveImageUrls("thumb")); + + expect($media->getResponsiveImageUrls("non-existing-conversion"))->toBe([]); +}); diff --git a/tests/Support/FileTest.php b/tests/Support/FileTest.php new file mode 100644 index 000000000..b7c2bf695 --- /dev/null +++ b/tests/Support/FileTest.php @@ -0,0 +1,17 @@ +toEqual('10 B'); + expect(File::getHumanReadableSize(100))->toEqual('100 B'); + expect(File::getHumanReadableSize(1000))->toEqual('1000 B'); + expect(File::getHumanReadableSize(10000))->toEqual('9.77 KB'); + $this->assertEquals('976.56 KB', File::getHumanReadableSize(1_000_000)); + $this->assertEquals('9.54 MB', File::getHumanReadableSize(10_000_000)); + $this->assertEquals('9.31 GB', File::getHumanReadableSize(10_000_000_000)); +}); + +it('can determine the mime type of a file', function () { + expect(File::getMimeType(__FILE__))->toEqual('text/x-php'); +}); diff --git a/tests/Support/MediaStreamTest.php b/tests/Support/MediaStreamTest.php index d0f84835e..0464160f7 100644 --- a/tests/Support/MediaStreamTest.php +++ b/tests/Support/MediaStreamTest.php @@ -1,164 +1,141 @@ testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - } +beforeEach(function () { + foreach (range(1, 3) as $i) { + $this + ->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); } +}); - /** @test */ - public function it_can_return_a_stream_of_media() - { - $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); +it('can return a stream of media', function () { + $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); - $this->assertEquals(count(Media::all()), $zipStreamResponse->getMediaItems()->count()); + expect($zipStreamResponse->getMediaItems()->count())->toEqual(count(Media::all())); - Route::get('stream-test', fn () => $zipStreamResponse); + Route::get('stream-test', fn () => $zipStreamResponse); - $response = $this->get('stream-test'); + $response = $this->get('stream-test'); - $this->assertInstanceOf(StreamedResponse::class, $response->baseResponse); - } + expect($response->baseResponse)->toBeInstanceOf(StreamedResponse::class); +}); - /** @test */ - public function it_can_return_a_stream_of_multiple_files_with_the_same_filename() - { - $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); +it('can return a stream of multiple files with the same filename', function () { + $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); - ob_start(); - @$zipStreamResponse->toResponse(request())->sendContent(); - $content = ob_get_contents(); - ob_end_clean(); + ob_start(); + @$zipStreamResponse->toResponse(request())->sendContent(); + $content = ob_get_contents(); + ob_end_clean(); - $temporaryDirectory = (new TemporaryDirectory())->create(); - file_put_contents($temporaryDirectory->path('response.zip'), $content); + $temporaryDirectory = (new TemporaryDirectory())->create(); + file_put_contents($temporaryDirectory->path('response.zip'), $content); - $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test.jpg'); - $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test (1).jpg'); - $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test (2).jpg'); - } + $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test.jpg'); + $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test (1).jpg'); + $this->assertFileExistsInZip($temporaryDirectory->path('response.zip'), 'test (2).jpg'); +}); - /** @test */ - public function media_can_be_added_to_it_one_by_one() - { - $zipStreamResponse = MediaStream::create('my-media.zip') - ->addMedia(Media::find(1)) - ->addMedia(Media::find(2)); +test('media can be added to it one by one', function () { + $zipStreamResponse = MediaStream::create('my-media.zip') + ->addMedia(Media::find(1)) + ->addMedia(Media::find(2)); - $this->assertEquals(2, $zipStreamResponse->getMediaItems()->count()); - } + expect($zipStreamResponse->getMediaItems()->count())->toEqual(2); +}); - /** @test */ - public function an_array_of_media_can_be_added_to_it() - { - $zipStreamResponse = MediaStream::create('my-media.zip') - ->addMedia([Media::find(1), Media::find(2)]); +test('an array of media can be added to it', function () { + $zipStreamResponse = MediaStream::create('my-media.zip') + ->addMedia([Media::find(1), Media::find(2)]); - $this->assertEquals(2, $zipStreamResponse->getMediaItems()->count()); - } + expect($zipStreamResponse->getMediaItems()->count())->toEqual(2); +}); - /** @test */ - public function media_with_zip_file_folder_prefix_property_saved_in_correct_zip_folder() - { - $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties([ - 'zip_filename_prefix' => 'folder/subfolder/', - ]) - ->toMediaCollection(); +test('media with zip file folder prefix property saved in correct zip folder', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties([ + 'zip_filename_prefix' => 'folder/subfolder/', + ]) + ->toMediaCollection(); - $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); + $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); - ob_start(); - @$zipStreamResponse->toResponse(request())->sendContent(); - $content = ob_get_contents(); - ob_end_clean(); + ob_start(); + @$zipStreamResponse->toResponse(request())->sendContent(); + $content = ob_get_contents(); + ob_end_clean(); - $temporaryDirectory = (new TemporaryDirectory())->create(); - file_put_contents($temporaryDirectory->path('response.zip'), $content); + $temporaryDirectory = (new TemporaryDirectory())->create(); + file_put_contents($temporaryDirectory->path('response.zip'), $content); - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test (2).jpg'); + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test (2).jpg'); - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'folder/subfolder/test.jpg'); - } + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'folder/subfolder/test.jpg'); +}); - /** @test */ - public function media_with_zip_file_folder_prefix_property_saved_in_correct_zip_folder_and_correct_suffix() - { - foreach (range(1, 2) as $i) { - $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); - } - - foreach (range(1, 2) as $i) { - $this->testModel - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->withCustomProperties([ - 'zip_filename_prefix' => 'folder/subfolder/', - ]) - ->toMediaCollection(); - } - - $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); - - ob_start(); - @$zipStreamResponse->toResponse(request())->sendContent(); - $content = ob_get_contents(); - ob_end_clean(); - - $temporaryDirectory = (new TemporaryDirectory())->create(); - file_put_contents($temporaryDirectory->path('response.zip'), $content); - - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test.jpg'); - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test (1).jpg'); - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test (2).jpg'); - - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'folder/subfolder/test.jpg'); - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'folder/subfolder/test (1).jpg'); +test('media with zip file folder prefix property saved in correct zip folder and correct suffix', function () { + foreach (range(1, 2) as $i) { + $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); } - /** @test */ - public function media_with_zip_file_prefix_property_saved_with_correct_prefix() - { + foreach (range(1, 2) as $i) { $this->testModel ->addMedia($this->getTestJpg()) ->preservingOriginal() ->withCustomProperties([ - 'zip_filename_prefix' => 'just_a_string_prefix ', + 'zip_filename_prefix' => 'folder/subfolder/', ]) ->toMediaCollection(); + } - $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); + $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); - ob_start(); - @$zipStreamResponse->toResponse(request())->sendContent(); - $content = ob_get_contents(); - ob_end_clean(); - $temporaryDirectory = (new TemporaryDirectory())->create(); - file_put_contents($temporaryDirectory->path('response.zip'), $content); + ob_start(); + @$zipStreamResponse->toResponse(request())->sendContent(); + $content = ob_get_contents(); + ob_end_clean(); - $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'just_a_string_prefix test.jpg'); - } -} + $temporaryDirectory = (new TemporaryDirectory())->create(); + file_put_contents($temporaryDirectory->path('response.zip'), $content); + + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test.jpg'); + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test (1).jpg'); + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'test (2).jpg'); + + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'folder/subfolder/test.jpg'); + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'folder/subfolder/test (1).jpg'); +}); + +test('media with zip file prefix property saved with correct prefix', function () { + $this->testModel + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->withCustomProperties([ + 'zip_filename_prefix' => 'just_a_string_prefix ', + ]) + ->toMediaCollection(); + + $zipStreamResponse = MediaStream::create('my-media.zip')->addMedia(Media::all()); + + ob_start(); + @$zipStreamResponse->toResponse(request())->sendContent(); + $content = ob_get_contents(); + ob_end_clean(); + $temporaryDirectory = (new TemporaryDirectory())->create(); + file_put_contents($temporaryDirectory->path('response.zip'), $content); + + $this->assertFileExistsInZipRecognizeFolder($temporaryDirectory->path('response.zip'), 'just_a_string_prefix test.jpg'); +}); diff --git a/tests/Support/PathGenerator/BasePathGeneratorTest.php b/tests/Support/PathGenerator/BasePathGeneratorTest.php index 2ea749795..363db00be 100644 --- a/tests/Support/PathGenerator/BasePathGeneratorTest.php +++ b/tests/Support/PathGenerator/BasePathGeneratorTest.php @@ -1,63 +1,38 @@ config = app('config'); +beforeEach(function () { + $this->config = app('config'); - $this->urlGenerator = new DefaultUrlGenerator($this->config); + $this->urlGenerator = new DefaultUrlGenerator($this->config); - $this->pathGenerator = new CustomPathGenerator(); + $this->pathGenerator = new CustomPathGenerator(); - $this->urlGenerator->setPathGenerator($this->pathGenerator); - } + $this->urlGenerator->setPathGenerator($this->pathGenerator); +}); - /** @test */ - public function it_can_get_the_custom_path_for_media_without_conversions() - { - $media = $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); +it('can get the custom path for media without conversions', function () { + $media = $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); - $this->urlGenerator->setMedia($media); + $this->urlGenerator->setMedia($media); - $pathRelativeToRoot = md5($media->id).'/'.$media->file_name; + $pathRelativeToRoot = md5($media->id).'/'.$media->file_name; - $this->assertEquals($pathRelativeToRoot, $this->urlGenerator->getPathRelativeToRoot()); - } + expect($this->urlGenerator->getPathRelativeToRoot())->toEqual($pathRelativeToRoot); +}); - /** @test */ - public function it_can_get_the_custom_path_for_media_with_conversions() - { - $media = $this->testModelWithConversion->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); - $conversion = ConversionCollection::createForMedia($media)->getByName('thumb'); +it('can get the custom path for media with conversions', function () { + $media = $this->testModelWithConversion->addMedia($this->getTestFilesDirectory('test.jpg'))->toMediaCollection(); + $conversion = ConversionCollection::createForMedia($media)->getByName('thumb'); - $this->urlGenerator - ->setMedia($media) - ->setConversion($conversion); + $this->urlGenerator + ->setMedia($media) + ->setConversion($conversion); - $pathRelativeToRoot = md5($media->id).'/c/test-'.$conversion->getName().'.'.$conversion->getResultExtension($media->extension); + $pathRelativeToRoot = md5($media->id).'/c/test-'.$conversion->getName().'.'.$conversion->getResultExtension($media->extension); - $this->assertEquals($pathRelativeToRoot, $this->urlGenerator->getPathRelativeToRoot()); - } -} + expect($this->urlGenerator->getPathRelativeToRoot())->toEqual($pathRelativeToRoot); +}); diff --git a/tests/Support/UrlGenerator/BaseUrlGeneratorTest.php b/tests/Support/UrlGenerator/BaseUrlGeneratorTest.php index 87d86f70c..10ccf4a9b 100644 --- a/tests/Support/UrlGenerator/BaseUrlGeneratorTest.php +++ b/tests/Support/UrlGenerator/BaseUrlGeneratorTest.php @@ -1,92 +1,60 @@ config = app('config'); +beforeEach(function () { + $this->config = app('config'); - $this->media = $this->testModelWithConversion->addMedia($this->getTestPng())->toMediaCollection(); + $this->media = $this->testModelWithConversion->addMedia($this->getTestPng())->toMediaCollection(); - $this->conversion = ConversionCollection::createForMedia($this->media)->getByName('thumb'); + $this->conversion = ConversionCollection::createForMedia($this->media)->getByName('thumb'); - $this->conversionKeepingOriginalImageFormat = ConversionCollection::createForMedia($this->media)->getByName('keep_original_format'); + $this->conversionKeepingOriginalImageFormat = ConversionCollection::createForMedia($this->media)->getByName('keep_original_format'); - $this->urlGenerator = new DefaultUrlGenerator($this->config); - $this->pathGenerator = new DefaultPathGenerator(); + $this->urlGenerator = new DefaultUrlGenerator($this->config); + $this->pathGenerator = new DefaultPathGenerator(); - $this->urlGenerator - ->setMedia($this->media) - ->setConversion($this->conversion) - ->setPathGenerator($this->pathGenerator); - } + $this->urlGenerator + ->setMedia($this->media) + ->setConversion($this->conversion) + ->setPathGenerator($this->pathGenerator); +}); - /** @test */ - public function it_can_get_the_path_relative_to_the_root_of_media_folder() - { - $pathRelativeToRoot = $this->media->id.'/conversions/test-'.$this->conversion->getName().'.jpg'; +it('can get the path relative to the root of media folder', function () { + $pathRelativeToRoot = $this->media->id.'/conversions/test-'.$this->conversion->getName().'.jpg'; - $this->assertEquals($pathRelativeToRoot, $this->urlGenerator->getPathRelativeToRoot()); - } + expect($this->urlGenerator->getPathRelativeToRoot())->toEqual($pathRelativeToRoot); +}); - /** @test */ - public function it_can_get_the_path_relative_to_the_root_of_media_folder_when_keeping_the_original_image_format() - { - $this->urlGenerator->setConversion($this->conversionKeepingOriginalImageFormat); +it('can get the path relative to the root of media folder when keeping the original image format', function () { + $this->urlGenerator->setConversion($this->conversionKeepingOriginalImageFormat); - $pathRelativeToRoot = $this->media->id - .'/conversions/'. - 'test-'.$this->conversionKeepingOriginalImageFormat->getName() - .'.png'; + $pathRelativeToRoot = $this->media->id + .'/conversions/'. + 'test-'.$this->conversionKeepingOriginalImageFormat->getName() + .'.png'; - $this->assertEquals($pathRelativeToRoot, $this->urlGenerator->getPathRelativeToRoot()); - } + expect($this->urlGenerator->getPathRelativeToRoot())->toEqual($pathRelativeToRoot); +}); - /** @test * */ - public function it_appends_a_version_string_when_versioning_is_enabled() - { - config()->set('media-library.version_urls', true); +it('appends a version string when versioning is enabled', function () { + config()->set('media-library.version_urls', true); - $url = '/media/'.$this->media->id.'/conversions/test-'.$this->conversion->getName().'.jpg?v='.$this->media->updated_at->timestamp; + $url = '/media/'.$this->media->id.'/conversions/test-'.$this->conversion->getName().'.jpg?v='.$this->media->updated_at->timestamp; - $this->assertEquals($url, $this->urlGenerator->getUrl()); + expect($this->urlGenerator->getUrl())->toEqual($url); - config()->set('media-library.version_urls', false); + config()->set('media-library.version_urls', false); - $url = '/media/'.$this->media->id.'/conversions/test-'.$this->conversion->getName().'.jpg'; + $url = '/media/'.$this->media->id.'/conversions/test-'.$this->conversion->getName().'.jpg'; - $this->assertEquals($url, $this->urlGenerator->getUrl()); - } + expect($this->urlGenerator->getUrl())->toEqual($url); +}); - /** @test */ - public function it_can_get_the_responsive_images_directory_url() - { - $this->config->set('filesystems.disks.public.url', 'http://localhost/media/'); +it('can get the responsive images directory url', function () { + $this->config->set('filesystems.disks.public.url', 'http://localhost/media/'); - $this->assertEquals('http://localhost/media/1/responsive-images/', $this->urlGenerator->getResponsiveImagesDirectoryUrl()); - } -} + expect($this->urlGenerator->getResponsiveImagesDirectoryUrl())->toEqual('http://localhost/media/1/responsive-images/'); +}); diff --git a/tests/TestCase.php b/tests/TestCase.php index 2ccec87c1..0950dd3b9 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -4,10 +4,10 @@ use CreateMediaTable; use CreateTemporaryUploadsTable; -use Dotenv\Dotenv; -use File; +use Dotgetenv\Dotgetenv; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\File; use Orchestra\Testbench\TestCase as Orchestra; use Spatie\MediaLibrary\MediaLibraryServiceProvider; use Spatie\MediaLibrary\Support\MediaLibraryPro; @@ -41,7 +41,7 @@ abstract class TestCase extends Orchestra protected TestModelWithConversionsOnOtherDisk $testModelWithConversionsOnOtherDisk; - public function setUp(): void + protected function setUp(): void { $this->loadEnvironmentVariables(); @@ -64,11 +64,11 @@ public function setUp(): void protected function loadEnvironmentVariables() { - if (! file_exists(__DIR__.'/../.env')) { + if (! file_exists(__DIR__.'/../.getenv')) { return; } - $dotEnv = Dotenv::createImmutable(__DIR__.'/..'); + $dotEnv = Dotgetenv::createImmutable(__DIR__.'/..'); $dotEnv->load(); } @@ -90,7 +90,7 @@ protected function getPackageProviders($app) /** * @param \Illuminate\Foundation\Application $app */ - protected function getEnvironmentSetUp($app) + public function getEnvironmentSetUp($app) { $this->initializeDirectory($this->getTempDirectory()); @@ -171,17 +171,17 @@ public function getTestsPath($suffix = ''): string return __DIR__.$suffix; } - public function getTempDirectory($suffix = ''): string + public function getTempDirectory(string $suffix = ''): string { return __DIR__.'/TestSupport/temp'.($suffix == '' ? '' : '/'.$suffix); } - public function getMediaDirectory($suffix = ''): string + public function getMediaDirectory(string $suffix = ''): string { return $this->getTempDirectory().'/media'.($suffix == '' ? '' : '/'.$suffix); } - public function getTestFilesDirectory($suffix = ''): string + public function getTestFilesDirectory(string $suffix = ''): string { return $this->getTempDirectory().'/testfiles'.($suffix == '' ? '' : '/'.$suffix); } diff --git a/tests/TestSupport/TestImageGeneratorWithConfig.php b/tests/TestSupport/TestImageGeneratorWithConfig.php index 7e54eb504..365223b8c 100644 --- a/tests/TestSupport/TestImageGeneratorWithConfig.php +++ b/tests/TestSupport/TestImageGeneratorWithConfig.php @@ -8,15 +8,10 @@ class TestImageGeneratorWithConfig extends ImageGenerator { - public string $firstName; - - public string $secondName; - - public function __construct(string $firstName, string $secondName) - { - $this->firstName = $firstName; - - $this->secondName = $secondName; + public function __construct( + public string $firstName, + public string $secondName + ) { } public function convert(string $file, Conversion $conversion = null): string