From a1823c02936d53ac441471cc57298e30d5908bbf Mon Sep 17 00:00:00 2001 From: Freek Van der Herten Date: Thu, 14 Dec 2023 15:18:03 +0100 Subject: [PATCH] Use image v3 (#3451) * v11 * Fix styling * wip * Fix styling * wip * fix tests * Fix styling * fix tests * remove unneeded test * fix tests * update test config * Refactor code to set default extension to 'jpg' * wip * Fix styling * skip * Fix styling * simplify service provider * Fix styling * update deps * cs * Fix styling * rename events * rename config file * nitpick * wip * wip * update deps * Exclude PHP 8.3 and Laravel 9.* from the test matrix * Update Laravel dependencies to version 10.0 * Update requirements for Laravel Media Library to PHP 8.2+ and Laravel 10+. * Update laravel dependency version in run-tests.yml to 10.*. * Update test workflow badge in README.md * Refactor package to allow usage of any filesystem * prep --------- Co-authored-by: freekmurze --- .../workflows/{php-cs-fixer.yml => pint.yml} | 8 +-- .github/workflows/run-tests.yml | 9 +-- .php_cs.dist.php | 35 ---------- README.md | 4 +- UPGRADING.md | 6 ++ composer.json | 48 ++++++------- config/media-library.php | 2 +- docs/_index.md | 2 +- docs/advanced-usage/consuming-events.md | 16 ++--- .../handling-uploads-with-livewire-2.md | 2 +- .../handling-uploads-with-livewire-3.md | 2 +- docs/requirements.md | 2 +- phpunit.xml.dist | 17 ++--- .../Actions/PerformConversionAction.php | 8 +-- .../Actions/PerformManipulationsAction.php | 25 +++++-- .../Commands/RegenerateCommand.php | 2 +- src/Conversions/Conversion.php | 34 ++++----- src/Conversions/ConversionCollection.php | 5 +- ...hp => ConversionHasBeenCompletedEvent.php} | 2 +- ...Start.php => ConversionWillStartEvent.php} | 9 ++- src/Conversions/FileManipulator.php | 2 +- src/Conversions/ImageGenerators/Avif.php | 2 +- src/Conversions/ImageGenerators/Image.php | 2 +- .../ImageGenerators/ImageGenerator.php | 2 +- src/Conversions/ImageGenerators/Pdf.php | 5 +- src/Conversions/ImageGenerators/Svg.php | 4 +- src/Conversions/ImageGenerators/Video.php | 2 +- src/Conversions/ImageGenerators/Webp.php | 2 +- .../Jobs/PerformConversionsJob.php | 2 +- src/Conversions/Manipulations.php | 70 +++++++++++++++++++ src/Downloaders/DefaultDownloader.php | 4 +- src/HasMedia.php | 4 +- src/InteractsWithMedia.php | 32 +++------ ....php => CollectionHasBeenClearedEvent.php} | 2 +- ...enAdded.php => MediaHasBeenAddedEvent.php} | 2 +- .../Exceptions/FileIsTooBig.php | 2 +- .../Exceptions/FunctionalityNotAvailable.php | 2 +- src/MediaCollections/FileAdder.php | 9 +-- src/MediaCollections/Filesystem.php | 12 ++-- src/MediaCollections/HtmlableMedia.php | 2 +- src/MediaCollections/MediaRepository.php | 8 --- .../Models/Concerns/IsSorted.php | 4 +- src/MediaCollections/Models/Media.php | 21 +++--- src/MediaLibraryServiceProvider.php | 69 ++++++------------ ...php => ResponsiveImagesGeneratedEvent.php} | 2 +- .../Jobs/GenerateResponsiveImagesJob.php | 2 +- .../ResponsiveImageGenerator.php | 8 +-- .../FileRemover/FileBaseFileRemover.php | 2 +- src/Support/FileRemover/FileRemover.php | 1 - src/Support/ImageFactory.php | 7 +- .../PathGenerator/DefaultPathGenerator.php | 2 +- .../PathGenerator/PathGeneratorFactory.php | 2 +- src/Support/UrlGenerator/UrlGenerator.php | 5 +- tests/ArchTest.php | 5 ++ .../Conversions/Commands/CleanCommandTest.php | 15 ++-- .../Conversions/ConversionCollectionTest.php | 50 +++++++------ tests/Conversions/ConversionFileNamerTest.php | 8 +-- tests/Conversions/ConversionTest.php | 44 ++++-------- tests/Conversions/EventTest.php | 12 ++-- tests/Conversions/ImageGenerators/SvgTest.php | 4 +- .../TestImageGeneratorWithConfigTest.php | 2 +- tests/Feature/FileAdder/IntegrationTest.php | 15 ++-- .../MediaConversions/AddMediaTest.php | 20 +++--- .../MediaConversions/MediaCollectionTest.php | 37 ++++++---- .../InteractsWithMedia/DeleteMediaTest.php | 2 +- .../InteractsWithMedia/GetMediaTest.php | 4 +- .../InteractsWithMedia/HasMediaTest.php | 2 - .../InteractsWithMedia/UpdateMediaTest.php | 2 - tests/Feature/Media/CustomHeadersTest.php | 2 - tests/Feature/Media/CustomPropertyTest.php | 2 - tests/Feature/Media/DeleteTest.php | 18 ++--- tests/Feature/Media/GetAvailableUrlTest.php | 8 +-- .../Feature/Media/GetMediaConversionsTest.php | 2 - .../Media/GetOriginalUrlAttributeTest.php | 2 - tests/Feature/Media/GetPathTest.php | 8 +-- .../Media/GetPreviewUrlAttributeTest.php | 2 - tests/Feature/Media/GetTypeTest.php | 2 - tests/Feature/Media/RenameTest.php | 2 - tests/Feature/Media/ResponsableTest.php | 2 - tests/Feature/Media/ToHtmlTest.php | 6 +- .../Feature/Media/UpdateManipulationsTest.php | 10 +-- .../S3Integration/S3TestPathGenerator.php | 2 +- tests/Image/ImageFactoryTest.php | 10 +-- tests/MediaCollections/EventTest.php | 4 +- tests/Pest.php | 14 ++++ .../ResponsiveImageFileNamerTest.php | 6 +- .../ResponsiveImageGeneratorFileNamerTest.php | 4 +- .../ResponsiveImageGeneratorTest.php | 55 ++++++--------- .../ResponsiveImages/ResponsiveImageTest.php | 22 +++--- .../CustomDirectoryStructurePathGenerator.php | 4 +- tests/TestCase.php | 10 ++- tests/TestSupport/TestImageGenerator.php | 2 +- .../TestImageGeneratorWithConfig.php | 2 +- .../TestModels/TestModelWithConversion.php | 9 ++- .../TestModelWithConversionQueued.php | 11 +-- ...tModelWithConversionUsingModelInstance.php | 2 +- .../TestModelWithConversionsOnOtherDisk.php | 5 +- .../TestModelWithCustomLoadingAttribute.php | 2 +- .../TestModelWithMultipleConversions.php | 11 +-- .../TestModelWithPreviewConversion.php | 9 +-- .../TestModelWithResponsiveImages.php | 32 +++++---- .../TestModelWithoutMediaConversions.php | 2 + 102 files changed, 513 insertions(+), 528 deletions(-) rename .github/workflows/{php-cs-fixer.yml => pint.yml} (58%) delete mode 100644 .php_cs.dist.php rename src/Conversions/Events/{ConversionHasBeenCompleted.php => ConversionHasBeenCompletedEvent.php} (89%) rename src/Conversions/Events/{ConversionWillStart.php => ConversionWillStartEvent.php} (56%) create mode 100644 src/Conversions/Manipulations.php rename src/MediaCollections/Events/{CollectionHasBeenCleared.php => CollectionHasBeenClearedEvent.php} (88%) rename src/MediaCollections/Events/{MediaHasBeenAdded.php => MediaHasBeenAddedEvent.php} (89%) rename src/ResponsiveImages/Events/{ResponsiveImagesGenerated.php => ResponsiveImagesGeneratedEvent.php} (87%) create mode 100644 tests/ArchTest.php diff --git a/.github/workflows/php-cs-fixer.yml b/.github/workflows/pint.yml similarity index 58% rename from .github/workflows/php-cs-fixer.yml rename to .github/workflows/pint.yml index fbec801bb..975ad1728 100644 --- a/.github/workflows/php-cs-fixer.yml +++ b/.github/workflows/pint.yml @@ -12,12 +12,10 @@ jobs: with: ref: ${{ github.head_ref }} - - name: Run PHP CS Fixer - uses: docker://oskarstark/php-cs-fixer-ga - with: - args: --config=.php_cs.dist.php --allow-risky=yes + - name: Fix styling issues + uses: aglipanci/laravel-pint-action@0.1.0 - name: Commit changes - uses: stefanzweifel/git-auto-commit-action@v5 + uses: stefanzweifel/git-auto-commit-action@v4 with: commit_message: Fix styling diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index cb8d5b596..0a11caff4 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -8,17 +8,12 @@ jobs: strategy: fail-fast: false matrix: - php: [8.3, 8.2, 8.1, 8.0] - laravel: [10.*, 9.*] + php: [8.3, 8.2] + laravel: [10.*] dependency-version: [prefer-lowest, prefer-stable] include: - laravel: 10.* testbench: ^8.0 - - laravel: 9.* - testbench: ^7.0 - exclude: - - laravel: 10.* - php: 8.0 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} diff --git a/.php_cs.dist.php b/.php_cs.dist.php deleted file mode 100644 index ea229dfc5..000000000 --- a/.php_cs.dist.php +++ /dev/null @@ -1,35 +0,0 @@ -in([ - __DIR__ . '/src', - __DIR__ . '/tests', - ]) - ->name('*.php') - ->notName('*.blade.php') - ->ignoreDotFiles(true) - ->ignoreVCS(true); - -return (new PhpCsFixer\Config()) - ->setRules([ - '@PSR12' => true, - 'array_syntax' => ['syntax' => 'short'], - 'ordered_imports' => ['sort_algorithm' => 'alpha'], - 'no_unused_imports' => true, - 'not_operator_with_successor_space' => true, - 'trailing_comma_in_multiline' => true, - 'phpdoc_scalar' => true, - 'unary_operator_spaces' => true, - 'binary_operator_spaces' => true, - 'blank_line_before_statement' => [ - 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], - ], - 'phpdoc_single_line_var_spacing' => true, - 'phpdoc_var_without_name' => true, - 'method_argument_space' => [ - 'on_multiline' => 'ensure_fully_multiline', - 'keep_multiple_spaces_after_comma' => true, - ], - 'single_trait_insert_per_statement' => true, - ]) - ->setFinder($finder); diff --git a/README.md b/README.md index 42ca00c3c..1032cb817 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # Associate files with Eloquent models [![Latest Version](https://img.shields.io/github/release/spatie/laravel-medialibrary.svg?style=flat-square)](https://github.com/spatie/laravel-medialibrary/releases) -![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/spatie/laravel-medialibrary/run-tests.yml?branch=master&style=flat-square&label=tests) +[![run-tests](https://github.com/spatie/laravel-medialibrary/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/laravel-medialibrary/actions/workflows/run-tests.yml) [![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-medialibrary.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-medialibrary) This package can associate all sorts of files with Eloquent models. It provides a @@ -30,7 +30,7 @@ $newsItem->addMedia($bigFile)->toMediaCollection('downloads', 's3'); ``` The storage of the files is handled by [Laravel's Filesystem](https://laravel.com/docs/filesystem), -so you can use any filesystem you like. Additionally the package can create image manipulations +so you can use any filesystem you like. Additionally, the package can create image manipulations on images and pdfs that have been added in the media library. Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource). diff --git a/UPGRADING.md b/UPGRADING.md index a63b41dbf..6e62f08ce 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -2,6 +2,12 @@ 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 v10 to v11 + +- Image v3 is now used. Make sure to update your image conversions to the new syntax. See [the image docs](https://spatie.be/docs/image/v3) for more info. +- All event names have gained the `Event` suffix. For example `Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAdded` is now `Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent`. + + ## 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. diff --git a/composer.json b/composer.json index 7a381ff4f..cba50e5d2 100644 --- a/composer.json +++ b/composer.json @@ -22,37 +22,38 @@ ], "homepage": "https://github.com/spatie/laravel-medialibrary", "require": { - "php": "^8.0", + "php": "^8.2", "ext-exif": "*", "ext-fileinfo": "*", "ext-json": "*", - "illuminate/bus": "^9.18|^10.0", - "illuminate/conditionable": "^9.18|^10.0", - "illuminate/console": "^9.18|^10.0", - "illuminate/database": "^9.18|^10.0", - "illuminate/pipeline": "^9.18|^10.0", - "illuminate/support": "^9.18|^10.0", - "maennchen/zipstream-php": "^2.0|^3.0", - "spatie/image": "^2.2.7", - "spatie/temporary-directory": "^2.0", - "symfony/console": "^6.0" + "illuminate/bus": "^10.0", + "illuminate/conditionable": "^10.0", + "illuminate/console": "^10.0", + "illuminate/database": "^10.0", + "illuminate/pipeline": "^10.0", + "illuminate/support": "^10.0", + "maennchen/zipstream-php": "^3.1", + "spatie/image": "^3.0", + "spatie/laravel-package-tools": "^1.16.1", + "spatie/temporary-directory": "^2.2", + "symfony/console": "^6.4.1|^7.0" }, "require-dev": { "ext-imagick": "*", "ext-pdo_sqlite": "*", "ext-zip": "*", - "aws/aws-sdk-php": "^3.133.11", - "doctrine/dbal": "^2.13", - "guzzlehttp/guzzle": "^7.4", - "league/flysystem-aws-s3-v3": "^3.0", - "mockery/mockery": "^1.4", - "nunomaduro/larastan": "^2.0", - "orchestra/testbench": "^7.0|^8.0", - "pestphp/pest": "^1.21", - "phpstan/extension-installer": "^1.1", - "spatie/laravel-ray": "^1.28", - "spatie/pdf-to-image": "^2.1", - "spatie/phpunit-snapshot-assertions": "^4.2" + "aws/aws-sdk-php": "^3.293.10", + "doctrine/dbal": "^2.13.9", + "guzzlehttp/guzzle": "^7.8.1", + "league/flysystem-aws-s3-v3": "^3.22", + "mockery/mockery": "^1.6.7", + "larastan/larastan": "^2.7", + "orchestra/testbench": "^7.0|^8.17", + "pestphp/pest": "^2.28", + "phpstan/extension-installer": "^1.3.1", + "spatie/laravel-ray": "^1.33", + "spatie/pdf-to-image": "^2.2", + "spatie/pest-plugin-snapshots": "^2.1" }, "conflict": { "php-ffmpeg/php-ffmpeg": "<0.6.1" @@ -91,7 +92,6 @@ "scripts": { "analyse": "vendor/bin/phpstan analyse", "baseline": "vendor/bin/phpstan analyse --generate-baseline", - "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes", "test": "vendor/bin/pest" } } diff --git a/config/media-library.php b/config/media-library.php index a5fc86764..e369db782 100644 --- a/config/media-library.php +++ b/config/media-library.php @@ -39,7 +39,7 @@ /* * When enabled, media collections will be serialised using the default * laravel model serialization behaviour. - * + * * Keep this option disabled if using Media Library Pro components (https://medialibrary.pro) */ 'use_default_collection_serialization' => false, diff --git a/docs/_index.md b/docs/_index.md index 7362a6936..edc1d983b 100644 --- a/docs/_index.md +++ b/docs/_index.md @@ -1,5 +1,5 @@ --- -title: v10 +title: v11 slogan: Associate files with Eloquent models. githubUrl: https://github.com/spatie/laravel-medialibrary branch: main diff --git a/docs/advanced-usage/consuming-events.md b/docs/advanced-usage/consuming-events.md index 5567a512a..93e552279 100644 --- a/docs/advanced-usage/consuming-events.md +++ b/docs/advanced-usage/consuming-events.md @@ -5,12 +5,12 @@ weight: 8 The media library will fire the following events that your handlers can listen for: -### MediaHasBeenAdded +### MediaHasBeenAddedEvent This event is fired after a file has been saved to disk. The event has a property `media` that holds the `\Spatie\MediaLibrary\Models\Media`-object of which the file has been stored. -### ConversionWillStart +### ConversionWillStartEvent This event is fired right before a conversion will start. The event has two public properties: @@ -18,7 +18,7 @@ The event has two public properties: - `media`: the `\Spatie\MediaLibrary\Models\Media`-object of which a conversion will be started - `conversion`: the conversion (an instance of `\Spatie\MediaLibrary\Conversion\Conversion`) that will start -### ConversionHasBeenCompleted +### ConversionHasBeenCompletedEvent This event is fired when a conversion has been completed. The event has two public properties: @@ -26,7 +26,7 @@ The event has two public properties: - `media`: the `\Spatie\MediaLibrary\Models\Media`-object of which a conversion has been completed - `conversion`: the conversion (an instance of `\Spatie\MediaLibrary\Conversion\Conversion`) that has just been completed -### CollectionHasBeenCleared +### CollectionHasBeenClearedEvent This event will be fired after a collection has been cleared. The event has two public properties: @@ -42,11 +42,11 @@ First you must create a listener class. Here's one that will log the paths of ad namespace App\Listeners; use Log; -use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAdded; +use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent; class MediaLogger { - public function handle(MediaHasBeenAdded $event) + public function handle(MediaHasBeenAddedEvent $event) { $media = $event->media; $path = $media->getPath(); @@ -59,8 +59,8 @@ Hook it up in `app/Providers/EventServiceProvider.php` to let Laravel know that ```php protected $listen = [ - 'Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAdded' => [ - 'App\Listeners\MediaLogger' + Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent::class => [ + App\Listeners\MediaLogger::class ], ]; ``` diff --git a/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-2.md b/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-2.md index dcbe63ddc..e1f6271a6 100644 --- a/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-2.md +++ b/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-2.md @@ -317,7 +317,7 @@ blade view that will be used to display all form elements on a row in the compon In this example we're going to add a custom property form field called `extra_field`. ```html -@include('media-library::livewire.partials.collection.fields') +@include('medialibrary::livewire.partials.collection.fields')
diff --git a/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-3.md b/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-3.md index 1dc56ea6a..5a673794d 100644 --- a/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-3.md +++ b/docs/handling-uploads-with-media-library-pro/handling-uploads-with-livewire-3.md @@ -304,7 +304,7 @@ blade view that will be used to display all form elements on a row in the compon In this example we're going to add a custom property form field called `extra_field`. ```html -@include('media-library::livewire.partials.collection.fields') +@include('medialibrary::livewire.partials.collection.fields')
diff --git a/docs/requirements.md b/docs/requirements.md index 658db3816..6ca3c4dee 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -3,7 +3,7 @@ title: Requirements weight: 5 --- -Laravel Media Library requires **PHP 8+** and **Laravel 9+**. +Laravel Media Library requires **PHP 8.2+** and **Laravel 10+**. 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/phpunit.xml.dist b/phpunit.xml.dist index 3663181f9..e9f469cff 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,16 +1,17 @@ - - - - src/ - - + + tests - + - + + + + src/ + + diff --git a/src/Conversions/Actions/PerformConversionAction.php b/src/Conversions/Actions/PerformConversionAction.php index d904b9685..d134aef66 100644 --- a/src/Conversions/Actions/PerformConversionAction.php +++ b/src/Conversions/Actions/PerformConversionAction.php @@ -3,8 +3,8 @@ namespace Spatie\MediaLibrary\Conversions\Actions; use Spatie\MediaLibrary\Conversions\Conversion; -use Spatie\MediaLibrary\Conversions\Events\ConversionHasBeenCompleted; -use Spatie\MediaLibrary\Conversions\Events\ConversionWillStart; +use Spatie\MediaLibrary\Conversions\Events\ConversionHasBeenCompletedEvent; +use Spatie\MediaLibrary\Conversions\Events\ConversionWillStartEvent; use Spatie\MediaLibrary\Conversions\ImageGenerators\ImageGeneratorFactory; use Spatie\MediaLibrary\MediaCollections\Filesystem; use Spatie\MediaLibrary\MediaCollections\Models\Media; @@ -25,7 +25,7 @@ public function execute( return; } - event(new ConversionWillStart($media, $conversion, $copiedOriginalFile)); + event(new ConversionWillStartEvent($media, $conversion, $copiedOriginalFile)); $manipulationResult = (new PerformManipulationsAction())->execute($media, $conversion, $copiedOriginalFile); @@ -48,7 +48,7 @@ public function execute( $media->markAsConversionGenerated($conversion->getName()); - event(new ConversionHasBeenCompleted($media, $conversion)); + event(new ConversionHasBeenCompletedEvent($media, $conversion)); } protected function renameInLocalDirectory( diff --git a/src/Conversions/Actions/PerformManipulationsAction.php b/src/Conversions/Actions/PerformManipulationsAction.php index eaa2b3ef2..4c00bf482 100644 --- a/src/Conversions/Actions/PerformManipulationsAction.php +++ b/src/Conversions/Actions/PerformManipulationsAction.php @@ -4,17 +4,18 @@ use Illuminate\Support\Facades\File; use Illuminate\Support\Str; +use Spatie\Image\Image; use Spatie\MediaLibrary\Conversions\Conversion; use Spatie\MediaLibrary\MediaCollections\Models\Media; -use Spatie\MediaLibrary\Support\ImageFactory; class PerformManipulationsAction { public function execute( Media $media, Conversion $conversion, - string $imageFile + string $imageFile, ): string { + if ($conversion->getManipulations()->isEmpty()) { return $imageFile; } @@ -28,9 +29,13 @@ public function execute( $conversion->format($media->extension); } - ImageFactory::load($conversionTempFile) - ->manipulate($conversion->getManipulations()) - ->save(); + $image = Image::useImageDriver(config('media-library.image_driver')) + ->loadFile($conversionTempFile) + ->format('jpg'); + + $conversion->getManipulations()->apply($image); + + $image->save(); return $conversionTempFile; } @@ -38,11 +43,17 @@ public function execute( protected function getConversionTempFileName( Media $media, Conversion $conversion, - string $imageFile + string $imageFile, ): string { $directory = pathinfo($imageFile, PATHINFO_DIRNAME); - $fileName = Str::random(32)."{$conversion->getName()}.{$media->extension}"; + $extension = $media->extension; + + if ($extension === '') { + $extension = 'jpg'; + } + + $fileName = Str::random(32)."{$conversion->getName()}.{$extension}"; return "{$directory}/{$fileName}"; } diff --git a/src/Conversions/Commands/RegenerateCommand.php b/src/Conversions/Commands/RegenerateCommand.php index f2fa13448..50f583019 100644 --- a/src/Conversions/Commands/RegenerateCommand.php +++ b/src/Conversions/Commands/RegenerateCommand.php @@ -81,7 +81,7 @@ public function getMediaToBeRegenerated(): Collection // Get this arg first as it can also be passed to the greater-than-id branch $modelType = $this->argument('modelType'); - $startingFromId = (int)$this->option('starting-from-id'); + $startingFromId = (int) $this->option('starting-from-id'); if ($startingFromId !== 0) { $excludeStartingId = (bool) $this->option('exclude-starting-id') ?: false; diff --git a/src/Conversions/Conversion.php b/src/Conversions/Conversion.php index 8bb99b6ad..045692be3 100644 --- a/src/Conversions/Conversion.php +++ b/src/Conversions/Conversion.php @@ -2,13 +2,13 @@ namespace Spatie\MediaLibrary\Conversions; -use BadMethodCallException; +use Illuminate\Support\Arr; use Illuminate\Support\Traits\Conditionable; -use Spatie\Image\Manipulations; +use Spatie\ImageOptimizer\OptimizerChainFactory; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Spatie\MediaLibrary\Support\FileNamer\FileNamer; -/** @mixin \Spatie\Image\Manipulations */ +/** @mixin \Spatie\Image\Drivers\ImageDriver */ class Conversion { use Conditionable; @@ -32,11 +32,13 @@ class Conversion protected int $pdfPageNumber = 1; public function __construct( - protected string $name + protected string $name, ) { + $optimizerChain = OptimizerChainFactory::create(config('media-library.image_optimizers')); + $this->manipulations = (new Manipulations()) - ->optimize(config('media-library.image_optimizers')) - ->format(Manipulations::FORMAT_JPG); + ->optimize($optimizerChain) + ->format('jpg'); $this->fileNamer = app(config('media-library.file_namer')); @@ -45,7 +47,7 @@ public function __construct( $this->performOnQueue = config('media-library.queue_conversions_by_default', true); } - public static function create(string $name) + public static function create(string $name): self { return new static($name); } @@ -107,12 +109,8 @@ public function withoutManipulations(): self return $this; } - public function __call($name, $arguments) + public function __call($name, $arguments): self { - if (! method_exists($this->manipulations, $name)) { - throw new BadMethodCallException("Manipulation `{$name}` does not exist"); - } - $this->manipulations->$name(...$arguments); return $this; @@ -133,11 +131,13 @@ public function setManipulations($manipulations): self public function addAsFirstManipulations(Manipulations $manipulations): self { - $manipulationSequence = $manipulations->getManipulationSequence()->toArray(); + $newManipulations = $manipulations->toArray(); + + $currentManipulations = $this->manipulations->toArray(); + + $allManipulations = array_merge($currentManipulations, $newManipulations); - $this->manipulations - ->getManipulationSequence() - ->mergeArray($manipulationSequence); + $this->manipulations = new Manipulations($allManipulations); return $this; } @@ -209,7 +209,7 @@ public function getResultExtension(string $originalFileExtension = ''): string } } - if ($manipulationArgument = $this->manipulations->getManipulationArgument('format')) { + if ($manipulationArgument = Arr::get($this->manipulations->getManipulationArgument('format'), 0)) { return $manipulationArgument; } diff --git a/src/Conversions/ConversionCollection.php b/src/Conversions/ConversionCollection.php index 22f4bdae7..a2a89d12b 100644 --- a/src/Conversions/ConversionCollection.php +++ b/src/Conversions/ConversionCollection.php @@ -5,7 +5,6 @@ use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Arr; use Illuminate\Support\Collection; -use Spatie\Image\Manipulations; use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidConversion; use Spatie\MediaLibrary\MediaCollections\Models\Media; @@ -75,10 +74,10 @@ protected function addConversionsFromRelatedModel(Media $media): void $this->items = $model->mediaConversions; } - protected function addManipulationsFromDb(Media $media) + protected function addManipulationsFromDb(Media $media): void { collect($media->manipulations)->each(function ($manipulation, $conversionName) { - $manipulations = new Manipulations([$manipulation]); + $manipulations = new Manipulations($manipulation); $this->addManipulationToConversion($manipulations, $conversionName); }); diff --git a/src/Conversions/Events/ConversionHasBeenCompleted.php b/src/Conversions/Events/ConversionHasBeenCompletedEvent.php similarity index 89% rename from src/Conversions/Events/ConversionHasBeenCompleted.php rename to src/Conversions/Events/ConversionHasBeenCompletedEvent.php index 20a8da06d..901657cf0 100644 --- a/src/Conversions/Events/ConversionHasBeenCompleted.php +++ b/src/Conversions/Events/ConversionHasBeenCompletedEvent.php @@ -6,7 +6,7 @@ use Spatie\MediaLibrary\Conversions\Conversion; use Spatie\MediaLibrary\MediaCollections\Models\Media; -class ConversionHasBeenCompleted +class ConversionHasBeenCompletedEvent { use SerializesModels; diff --git a/src/Conversions/Events/ConversionWillStart.php b/src/Conversions/Events/ConversionWillStartEvent.php similarity index 56% rename from src/Conversions/Events/ConversionWillStart.php rename to src/Conversions/Events/ConversionWillStartEvent.php index 99292d677..649171b1a 100644 --- a/src/Conversions/Events/ConversionWillStart.php +++ b/src/Conversions/Events/ConversionWillStartEvent.php @@ -6,11 +6,14 @@ use Spatie\MediaLibrary\Conversions\Conversion; use Spatie\MediaLibrary\MediaCollections\Models\Media; -class ConversionWillStart +class ConversionWillStartEvent { use SerializesModels; - public function __construct(public Media $media, public Conversion $conversion, public string $copiedOriginalFile) - { + public function __construct( + public Media $media, + public Conversion $conversion, + public string $copiedOriginalFile, + ) { } } diff --git a/src/Conversions/FileManipulator.php b/src/Conversions/FileManipulator.php index c7141ea69..840832215 100644 --- a/src/Conversions/FileManipulator.php +++ b/src/Conversions/FileManipulator.php @@ -54,7 +54,7 @@ public function performConversions( $copiedOriginalFile = app(Filesystem::class)->copyFromMediaLibrary( $media, - $temporaryDirectory->path(Str::random(32) . '.' . $media->extension) + $temporaryDirectory->path(Str::random(32).'.'.$media->extension) ); $conversions diff --git a/src/Conversions/ImageGenerators/Avif.php b/src/Conversions/ImageGenerators/Avif.php index a3c70361d..aec16a0a1 100644 --- a/src/Conversions/ImageGenerators/Avif.php +++ b/src/Conversions/ImageGenerators/Avif.php @@ -7,7 +7,7 @@ class Avif extends ImageGenerator { - public function convert(string $file, Conversion $conversion = null): string + public function convert(string $file, ?Conversion $conversion = null): string { $pathToImageFile = pathinfo($file, PATHINFO_DIRNAME).'/'.pathinfo($file, PATHINFO_FILENAME).'.png'; diff --git a/src/Conversions/ImageGenerators/Image.php b/src/Conversions/ImageGenerators/Image.php index c57402697..2b3add9c9 100644 --- a/src/Conversions/ImageGenerators/Image.php +++ b/src/Conversions/ImageGenerators/Image.php @@ -7,7 +7,7 @@ class Image extends ImageGenerator { - public function convert(string $path, Conversion $conversion = null): string + public function convert(string $path, ?Conversion $conversion = null): string { return $path; } diff --git a/src/Conversions/ImageGenerators/ImageGenerator.php b/src/Conversions/ImageGenerators/ImageGenerator.php index 6fc16b7e0..750a175cf 100644 --- a/src/Conversions/ImageGenerators/ImageGenerator.php +++ b/src/Conversions/ImageGenerators/ImageGenerator.php @@ -11,7 +11,7 @@ abstract class ImageGenerator /* * This function should return a path to an image representation of the given file. */ - abstract public function convert(string $file, Conversion $conversion = null): ?string; + abstract public function convert(string $file, ?Conversion $conversion = null): ?string; public function canConvert(Media $media): bool { diff --git a/src/Conversions/ImageGenerators/Pdf.php b/src/Conversions/ImageGenerators/Pdf.php index 8cde3736b..9d745ebbc 100644 --- a/src/Conversions/ImageGenerators/Pdf.php +++ b/src/Conversions/ImageGenerators/Pdf.php @@ -3,11 +3,12 @@ namespace Spatie\MediaLibrary\Conversions\ImageGenerators; use Illuminate\Support\Collection; +use Imagick; use Spatie\MediaLibrary\Conversions\Conversion; class Pdf extends ImageGenerator { - public function convert(string $file, Conversion $conversion = null): string + public function convert(string $file, ?Conversion $conversion = null): string { $imageFile = pathinfo($file, PATHINFO_DIRNAME).'/'.pathinfo($file, PATHINFO_FILENAME).'.jpg'; @@ -20,7 +21,7 @@ public function convert(string $file, Conversion $conversion = null): string public function requirementsAreInstalled(): bool { - if (! class_exists(\Imagick::class)) { + if (! class_exists(Imagick::class)) { return false; } diff --git a/src/Conversions/ImageGenerators/Svg.php b/src/Conversions/ImageGenerators/Svg.php index 19c5fda4c..7963eb7c1 100644 --- a/src/Conversions/ImageGenerators/Svg.php +++ b/src/Conversions/ImageGenerators/Svg.php @@ -9,7 +9,7 @@ class Svg extends ImageGenerator { - public function convert(string $file, Conversion $conversion = null): string + public function convert(string $file, ?Conversion $conversion = null): string { $imageFile = pathinfo($file, PATHINFO_DIRNAME).'/'.pathinfo($file, PATHINFO_FILENAME).'.jpg'; @@ -25,7 +25,7 @@ public function convert(string $file, Conversion $conversion = null): string public function requirementsAreInstalled(): bool { - return class_exists(\Imagick::class); + return class_exists(Imagick::class); } public function supportedExtensions(): Collection diff --git a/src/Conversions/ImageGenerators/Video.php b/src/Conversions/ImageGenerators/Video.php index ff83bfa28..47d7c76c2 100644 --- a/src/Conversions/ImageGenerators/Video.php +++ b/src/Conversions/ImageGenerators/Video.php @@ -10,7 +10,7 @@ class Video extends ImageGenerator { - public function convert(string $file, Conversion $conversion = null): ?string + public function convert(string $file, ?Conversion $conversion = null): ?string { $ffmpeg = FFMpeg::create([ 'ffmpeg.binaries' => config('media-library.ffmpeg_path'), diff --git a/src/Conversions/ImageGenerators/Webp.php b/src/Conversions/ImageGenerators/Webp.php index 24b88529b..76b8ac188 100644 --- a/src/Conversions/ImageGenerators/Webp.php +++ b/src/Conversions/ImageGenerators/Webp.php @@ -7,7 +7,7 @@ class Webp extends ImageGenerator { - public function convert(string $file, Conversion $conversion = null): string + public function convert(string $file, ?Conversion $conversion = null): string { $pathToImageFile = pathinfo($file, PATHINFO_DIRNAME).'/'.pathinfo($file, PATHINFO_FILENAME).'.png'; diff --git a/src/Conversions/Jobs/PerformConversionsJob.php b/src/Conversions/Jobs/PerformConversionsJob.php index 8c94b7608..352b99c64 100644 --- a/src/Conversions/Jobs/PerformConversionsJob.php +++ b/src/Conversions/Jobs/PerformConversionsJob.php @@ -13,8 +13,8 @@ class PerformConversionsJob implements ShouldQueue { use InteractsWithQueue; - use SerializesModels; use Queueable; + use SerializesModels; public $deleteWhenMissingModels = true; diff --git a/src/Conversions/Manipulations.php b/src/Conversions/Manipulations.php new file mode 100644 index 000000000..b83f80ba3 --- /dev/null +++ b/src/Conversions/Manipulations.php @@ -0,0 +1,70 @@ +manipulations = $manipulations; + } + + public function __call(string $method, array $parameters): self + { + $this->addManipulation($method, $parameters); + + return $this; + } + + public function addManipulation(string $name, array $parameters = []): self + { + $this->manipulations[$name] = $parameters; + + return $this; + } + + public function getManipulationArgument(string $manipulationName): null|string|array + { + return $this->manipulations[$manipulationName] ?? null; + } + + public function getFirstManipulationArgument(string $manipulationName): null|string|int + { + $manipulationArgument = $this->getManipulationArgument($manipulationName); + + if (! is_array($manipulationArgument)) { + return null; + } + + return $manipulationArgument[0]; + } + + public function isEmpty(): bool + { + return count($this->manipulations) === 0; + } + + public function apply(ImageDriver $image): void + { + foreach ($this->manipulations as $manipulationName => $parameters) { + $image->$manipulationName(...$parameters); + } + } + + public function removeManipulation(string $name): self + { + unset($this->manipulations[$name]); + + return $this; + } + + public function toArray(): array + { + return $this->manipulations; + } +} diff --git a/src/Downloaders/DefaultDownloader.php b/src/Downloaders/DefaultDownloader.php index c5dca09d2..24067e1b2 100644 --- a/src/Downloaders/DefaultDownloader.php +++ b/src/Downloaders/DefaultDownloader.php @@ -9,8 +9,8 @@ class DefaultDownloader implements Downloader public function getTempFile(string $url): string { $context = stream_context_create([ - "http" => [ - "header" => "User-Agent: Spatie MediaLibrary", + 'http' => [ + 'header' => 'User-Agent: Spatie MediaLibrary', ], ]); diff --git a/src/HasMedia.php b/src/HasMedia.php index d98c17dc3..9fe44fcbf 100644 --- a/src/HasMedia.php +++ b/src/HasMedia.php @@ -11,7 +11,9 @@ /** * @mixin \Illuminate\Database\Eloquent\Model + * * @method void prepareToAttachMedia(Media $media, FileAdder $fileAdder) + * * @property bool $registerMediaConversionsUsingModelInstance * @property ?\Spatie\MediaLibrary\MediaCollections\MediaCollection $mediaCollections */ @@ -37,7 +39,7 @@ public function loadMedia(string $collectionName); public function addMediaConversion(string $name): Conversion; - public function registerMediaConversions(Media $media = null): void; + public function registerMediaConversions(?Media $media = null): void; public function registerMediaCollections(): void; diff --git a/src/InteractsWithMedia.php b/src/InteractsWithMedia.php index 9393e995a..a811c9f8f 100644 --- a/src/InteractsWithMedia.php +++ b/src/InteractsWithMedia.php @@ -12,7 +12,7 @@ use Illuminate\Support\Str; use Spatie\MediaLibrary\Conversions\Conversion; use Spatie\MediaLibrary\Downloaders\DefaultDownloader; -use Spatie\MediaLibrary\MediaCollections\Events\CollectionHasBeenCleared; +use Spatie\MediaLibrary\MediaCollections\Events\CollectionHasBeenClearedEvent; use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidBase64Data; use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidUrl; use Spatie\MediaLibrary\MediaCollections\Exceptions\MediaCannotBeDeleted; @@ -63,8 +63,6 @@ public function media(): MorphMany /** * Add a file to the media library. - * - * */ public function addMedia(string|UploadedFile $file): FileAdder { @@ -78,10 +76,8 @@ public function addMediaFromRequest(string $key): FileAdder /** * Add a file from the given disk. - * - * */ - public function addMediaFromDisk(string $key, string $disk = null): FileAdder + public function addMediaFromDisk(string $key, ?string $disk = null): FileAdder { return app(FileAdderFactory::class)->createFromDisk($this, $key, $disk ?: config('filesystems.default')); } @@ -111,8 +107,7 @@ public function syncFromMediaLibraryRequest(?array $mediaLibraryRequestItems): P /** * Add multiple files from a request by keys. * - * @param string[] $keys - * + * @param string[] $keys * @return \Spatie\MediaLibrary\MediaCollections\FileAdder[] */ public function addMultipleMediaFromRequest(array $keys): Collection @@ -165,7 +160,6 @@ public function addMediaFromUrl(string $url, array|string ...$allowedMimeTypes): ->usingFileName($filename); } - /** * Add a file to the media library that contains the given string. * @@ -189,7 +183,6 @@ public function addMediaFromString(string $text): FileAdder * * * @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\FileCannotBeAdded - * * @throws InvalidBase64Data */ public function addMediaFromBase64(string $base64data, array|string ...$allowedMimeTypes): FileAdder @@ -203,7 +196,7 @@ public function addMediaFromBase64(string $base64data, array|string ...$allowedM // strict mode filters for non-base64 alphabet characters $binaryData = base64_decode($base64data, true); - if (false === $binaryData) { + if ($binaryData === false) { throw InvalidBase64Data::create(); } @@ -225,8 +218,6 @@ public function addMediaFromBase64(string $base64data, array|string ...$allowedM /** * Add a file to the media library from a stream. - * - * @param $stream */ public function addMediaFromStream($stream): FileAdder { @@ -243,8 +234,6 @@ public function addMediaFromStream($stream): FileAdder /** * Copy a file to the media library. - * - * */ public function copyMedia(string|UploadedFile $file): FileAdder { @@ -261,9 +250,6 @@ public function hasMedia(string $collectionName = 'default', array $filters = [] /** * Get media collection by its collectionName. - * - * @param array|callable $filters - * */ public function getMedia(string $collectionName = 'default', array|callable $filters = []): MediaCollections\Models\Collections\MediaCollection { @@ -443,7 +429,7 @@ public function clearMediaCollection(string $collectionName = 'default'): HasMed ->getMedia($collectionName) ->each(fn (Media $media) => $media->delete()); - event(new CollectionHasBeenCleared($this, $collectionName)); + event(new CollectionHasBeenClearedEvent($this, $collectionName)); if ($this->mediaIsPreloaded()) { unset($this->media); @@ -476,7 +462,7 @@ public function clearMediaCollectionExcept( } if ($this->getMedia($collectionName)->isEmpty()) { - event(new CollectionHasBeenCleared($this, $collectionName)); + event(new CollectionHasBeenClearedEvent($this, $collectionName)); } return $this; @@ -577,7 +563,7 @@ protected function guardAgainstInvalidMimeType(string $file, ...$allowedMimeType $validation = Validator::make( ['file' => new File($file)], - ['file' => 'mimetypes:' . implode(',', $allowedMimeTypes)] + ['file' => 'mimetypes:'.implode(',', $allowedMimeTypes)] ); if ($validation->fails()) { @@ -585,7 +571,7 @@ protected function guardAgainstInvalidMimeType(string $file, ...$allowedMimeType } } - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { } @@ -593,7 +579,7 @@ public function registerMediaCollections(): void { } - public function registerAllMediaConversions(Media $media = null): void + public function registerAllMediaConversions(?Media $media = null): void { $this->registerMediaCollections(); diff --git a/src/MediaCollections/Events/CollectionHasBeenCleared.php b/src/MediaCollections/Events/CollectionHasBeenClearedEvent.php similarity index 88% rename from src/MediaCollections/Events/CollectionHasBeenCleared.php rename to src/MediaCollections/Events/CollectionHasBeenClearedEvent.php index 203947592..e75907540 100644 --- a/src/MediaCollections/Events/CollectionHasBeenCleared.php +++ b/src/MediaCollections/Events/CollectionHasBeenClearedEvent.php @@ -5,7 +5,7 @@ use Illuminate\Queue\SerializesModels; use Spatie\MediaLibrary\HasMedia; -class CollectionHasBeenCleared +class CollectionHasBeenClearedEvent { use SerializesModels; diff --git a/src/MediaCollections/Events/MediaHasBeenAdded.php b/src/MediaCollections/Events/MediaHasBeenAddedEvent.php similarity index 89% rename from src/MediaCollections/Events/MediaHasBeenAdded.php rename to src/MediaCollections/Events/MediaHasBeenAddedEvent.php index 3c816ac07..8c47cbe78 100644 --- a/src/MediaCollections/Events/MediaHasBeenAdded.php +++ b/src/MediaCollections/Events/MediaHasBeenAddedEvent.php @@ -5,7 +5,7 @@ use Illuminate\Queue\SerializesModels; use Spatie\MediaLibrary\MediaCollections\Models\Media; -class MediaHasBeenAdded +class MediaHasBeenAddedEvent { use SerializesModels; diff --git a/src/MediaCollections/Exceptions/FileIsTooBig.php b/src/MediaCollections/Exceptions/FileIsTooBig.php index de1569faa..ecb1e1509 100644 --- a/src/MediaCollections/Exceptions/FileIsTooBig.php +++ b/src/MediaCollections/Exceptions/FileIsTooBig.php @@ -6,7 +6,7 @@ class FileIsTooBig extends FileCannotBeAdded { - public static function create(string $path, int $size = null): self + public static function create(string $path, ?int $size = null): self { $fileSize = File::getHumanReadableSize($size ?: filesize($path)); diff --git a/src/MediaCollections/Exceptions/FunctionalityNotAvailable.php b/src/MediaCollections/Exceptions/FunctionalityNotAvailable.php index 91cac6ca2..18bc71ed4 100644 --- a/src/MediaCollections/Exceptions/FunctionalityNotAvailable.php +++ b/src/MediaCollections/Exceptions/FunctionalityNotAvailable.php @@ -8,6 +8,6 @@ class FunctionalityNotAvailable extends Exception { public static function mediaLibraryProRequired() { - return new static("You need to have media library pro installed to make this work."); + return new static('You need to have media library pro installed to make this work.'); } } diff --git a/src/MediaCollections/FileAdder.php b/src/MediaCollections/FileAdder.php index 4d02351e9..459cded13 100644 --- a/src/MediaCollections/FileAdder.php +++ b/src/MediaCollections/FileAdder.php @@ -74,13 +74,6 @@ public function setSubject(Model $subject): self return $this; } - /* - * Set the file that needs to be imported. - * - * @param string|UploadedFile $file - * - * @return $this - */ public function setFile($file): self { $this->file = $file; @@ -545,7 +538,7 @@ protected function toMediaCollectionFromTemporaryUpload(string $collectionName, protected function appendExtension(string $file, ?string $extension): string { return $extension - ? $file . '.' . $extension + ? $file.'.'.$extension : $file; } } diff --git a/src/MediaCollections/Filesystem.php b/src/MediaCollections/Filesystem.php index 58a63f54c..be3f3f2f6 100644 --- a/src/MediaCollections/Filesystem.php +++ b/src/MediaCollections/Filesystem.php @@ -7,7 +7,7 @@ use Illuminate\Support\Str; use Spatie\MediaLibrary\Conversions\ConversionCollection; use Spatie\MediaLibrary\Conversions\FileManipulator; -use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAdded; +use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent; use Spatie\MediaLibrary\MediaCollections\Exceptions\DiskCannotBeAccessed; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Spatie\MediaLibrary\Support\File; @@ -28,11 +28,11 @@ public function add(string $file, Media $media, ?string $targetFileName = null): { try { $this->copyToMediaLibrary($file, $media, null, $targetFileName); - } catch(DiskCannotBeAccessed $exception) { + } catch (DiskCannotBeAccessed $exception) { return false; } - event(new MediaHasBeenAdded($media)); + event(new MediaHasBeenAddedEvent($media)); app(FileManipulator::class)->createDerivedFiles($media); @@ -43,11 +43,11 @@ public function addRemote(RemoteFile $file, Media $media, ?string $targetFileNam { try { $this->copyToMediaLibraryFromRemote($file, $media, null, $targetFileName); - } catch(DiskCannotBeAccessed $exception) { + } catch (DiskCannotBeAccessed $exception) { return false; } - event(new MediaHasBeenAdded($media)); + event(new MediaHasBeenAddedEvent($media)); app(FileManipulator::class)->createDerivedFiles($media); @@ -185,7 +185,7 @@ public function addCustomRemoteHeaders(array $customRemoteHeaders): void public function getRemoteHeadersForFile( string $file, array $mediaCustomHeaders = [], - string $mimeType = null + ?string $mimeType = null ): array { $mimeTypeHeader = ['ContentType' => $mimeType ?: File::getMimeType($file)]; diff --git a/src/MediaCollections/HtmlableMedia.php b/src/MediaCollections/HtmlableMedia.php index a545ba091..e6e849854 100644 --- a/src/MediaCollections/HtmlableMedia.php +++ b/src/MediaCollections/HtmlableMedia.php @@ -8,7 +8,7 @@ use Spatie\MediaLibrary\Conversions\ImageGenerators\ImageGeneratorFactory; use Spatie\MediaLibrary\MediaCollections\Models\Media; -class HtmlableMedia implements Htmlable, \Stringable +class HtmlableMedia implements \Stringable, Htmlable { protected string $conversionName = ''; diff --git a/src/MediaCollections/MediaRepository.php b/src/MediaCollections/MediaRepository.php index 3601f15b6..f0b6d62f6 100644 --- a/src/MediaCollections/MediaRepository.php +++ b/src/MediaCollections/MediaRepository.php @@ -19,9 +19,6 @@ public function __construct( /** * Get all media in the collection. - * - * @param array|callable $filter - * */ public function getCollection( HasMedia $model, @@ -33,11 +30,6 @@ public function getCollection( /** * Apply given filters on media. - * - * @param Collection $media - * @param array|callable $filter - * - * @return Collection */ protected function applyFilterToMediaCollection( Collection $media, diff --git a/src/MediaCollections/Models/Concerns/IsSorted.php b/src/MediaCollections/Models/Concerns/IsSorted.php index 945fc3082..f3cbb1170 100644 --- a/src/MediaCollections/Models/Concerns/IsSorted.php +++ b/src/MediaCollections/Models/Concerns/IsSorted.php @@ -16,8 +16,8 @@ public function setHighestOrderNumber(): void public function getHighestOrderNumber(): int { return (int) static::where('model_type', $this->model_type) - ->where('model_id', $this->model_id) - ->max($this->determineOrderColumnName()); + ->where('model_id', $this->model_id) + ->max($this->determineOrderColumnName()); } public function scopeOrdered(Builder $query): Builder diff --git a/src/MediaCollections/Models/Media.php b/src/MediaCollections/Models/Media.php index 6978d676e..013e43fa2 100644 --- a/src/MediaCollections/Models/Media.php +++ b/src/MediaCollections/Models/Media.php @@ -56,11 +56,11 @@ * @property-read ?\Illuminate\Support\Carbon $created_at * @property-read ?\Illuminate\Support\Carbon $updated_at */ -class Media extends Model implements Responsable, Htmlable, Attachable +class Media extends Model implements Attachable, Htmlable, Responsable { - use IsSorted; use CustomMediaProperties; use HasUuid; + use IsSorted; protected $table = 'media'; @@ -225,10 +225,7 @@ public function hasCustomProperty(string $propertyName): bool /** * Get the value of custom property with the given name. * - * @param string $propertyName - * @param mixed $default - * - * @return mixed + * @param mixed $default */ public function getCustomProperty(string $propertyName, $default = null): mixed { @@ -236,8 +233,7 @@ public function getCustomProperty(string $propertyName, $default = null): mixed } /** - * @param mixed $value - * + * @param mixed $value * @return $this */ public function setCustomProperty(string $name, $value): self @@ -274,7 +270,6 @@ public function getGeneratedConversions(): Collection return collect($this->generated_conversions ?? []); } - public function markAsConversionGenerated(string $conversionName): self { $generatedConversions = $this->generated_conversions; @@ -324,7 +319,7 @@ private function buildResponse($request, string $contentDispositionType) 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Content-Type' => $this->mime_type, 'Content-Length' => $this->size, - 'Content-Disposition' => $contentDispositionType . '; filename="' . $this->file_name . '"', + 'Content-Disposition' => $contentDispositionType.'; filename="'.$this->file_name.'"', 'Pragma' => 'public', ]; @@ -366,7 +361,7 @@ protected function originalUrl(): Attribute return Attribute::get(fn () => $this->getUrl()); } - /** @param string $collectionName */ + /** @param string $collectionName */ public function move(HasMedia $model, $collectionName = 'default', string $diskName = '', string $fileName = ''): self { $newMedia = $this->copy($model, $collectionName, $diskName, $fileName); @@ -376,12 +371,12 @@ public function move(HasMedia $model, $collectionName = 'default', string $diskN return $newMedia; } - /** @param string $collectionName */ + /** @param string $collectionName */ public function copy(HasMedia $model, $collectionName = 'default', string $diskName = '', string $fileName = ''): self { $temporaryDirectory = TemporaryDirectory::create(); - $temporaryFile = $temporaryDirectory->path('/') . DIRECTORY_SEPARATOR . $this->file_name; + $temporaryFile = $temporaryDirectory->path('/').DIRECTORY_SEPARATOR.$this->file_name; /** @var Filesystem $filesystem */ $filesystem = app(Filesystem::class); diff --git a/src/MediaLibraryServiceProvider.php b/src/MediaLibraryServiceProvider.php index bb003f7d9..30842c1cb 100644 --- a/src/MediaLibraryServiceProvider.php +++ b/src/MediaLibraryServiceProvider.php @@ -2,78 +2,49 @@ namespace Spatie\MediaLibrary; -use Illuminate\Support\ServiceProvider; +use Spatie\LaravelPackageTools\Package; +use Spatie\LaravelPackageTools\PackageServiceProvider; use Spatie\MediaLibrary\Conversions\Commands\RegenerateCommand; use Spatie\MediaLibrary\MediaCollections\Commands\CleanCommand; use Spatie\MediaLibrary\MediaCollections\Commands\ClearCommand; -use Spatie\MediaLibrary\MediaCollections\Filesystem; use Spatie\MediaLibrary\MediaCollections\MediaRepository; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Spatie\MediaLibrary\MediaCollections\Models\Observers\MediaObserver; use Spatie\MediaLibrary\ResponsiveImages\TinyPlaceholderGenerator\TinyPlaceholderGenerator; use Spatie\MediaLibrary\ResponsiveImages\WidthCalculator\WidthCalculator; -class MediaLibraryServiceProvider extends ServiceProvider +class MediaLibraryServiceProvider extends PackageServiceProvider { - public function boot() + public function configurePackage(Package $package): void { - $this->registerPublishables(); + $package + ->name('laravel-medialibrary') + ->hasConfigFile('media-library') + ->hasMigration('create_media_table') + ->hasViews('media-library') + ->hasCommands([ + RegenerateCommand::class, + ClearCommand::class, + CleanCommand::class, + ]); + } + public function packageBooted() + { $mediaClass = config('media-library.media_model', Media::class); $mediaClass::observe(new MediaObserver()); - - $this->loadViewsFrom(__DIR__.'/../resources/views', 'media-library'); } - public function register() + public function packageRegistered() { - $this->mergeConfigFrom(__DIR__.'/../config/media-library.php', 'media-library'); + $this->app->bind(WidthCalculator::class, config('media-library.responsive_images.width_calculator')); + $this->app->bind(TinyPlaceholderGenerator::class, config('media-library.responsive_images.tiny_placeholder_generator')); $this->app->scoped(MediaRepository::class, function () { $mediaClass = config('media-library.media_model'); return new MediaRepository(new $mediaClass()); }); - - $this->registerCommands(); - } - - protected function registerPublishables(): void - { - if (! $this->app->runningInConsole()) { - return; - } - - $this->publishes([ - __DIR__.'/../config/media-library.php' => config_path('media-library.php'), - ], 'config'); - - if (empty(glob(database_path('migrations/*_create_media_table.php')))) { - $this->publishes([ - __DIR__.'/../database/migrations/create_media_table.php.stub' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_media_table.php'), - ], 'migrations'); - } - - $this->publishes([ - __DIR__.'/../resources/views' => resource_path('views/vendor/media-library'), - ], 'views'); - } - - protected function registerCommands(): void - { - $this->app->bind(Filesystem::class, Filesystem::class); - $this->app->bind(WidthCalculator::class, config('media-library.responsive_images.width_calculator')); - $this->app->bind(TinyPlaceholderGenerator::class, config('media-library.responsive_images.tiny_placeholder_generator')); - - $this->app->bind('command.media-library:regenerate', RegenerateCommand::class); - $this->app->bind('command.media-library:clear', ClearCommand::class); - $this->app->bind('command.media-library:clean', CleanCommand::class); - - $this->commands([ - 'command.media-library:regenerate', - 'command.media-library:clear', - 'command.media-library:clean', - ]); } } diff --git a/src/ResponsiveImages/Events/ResponsiveImagesGenerated.php b/src/ResponsiveImages/Events/ResponsiveImagesGeneratedEvent.php similarity index 87% rename from src/ResponsiveImages/Events/ResponsiveImagesGenerated.php rename to src/ResponsiveImages/Events/ResponsiveImagesGeneratedEvent.php index a364dfb69..9e3e2f1be 100644 --- a/src/ResponsiveImages/Events/ResponsiveImagesGenerated.php +++ b/src/ResponsiveImages/Events/ResponsiveImagesGeneratedEvent.php @@ -5,7 +5,7 @@ use Illuminate\Queue\SerializesModels; use Spatie\MediaLibrary\MediaCollections\Models\Media; -class ResponsiveImagesGenerated +class ResponsiveImagesGeneratedEvent { use SerializesModels; diff --git a/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php b/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php index 011c58714..f7ea883c5 100644 --- a/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php +++ b/src/ResponsiveImages/Jobs/GenerateResponsiveImagesJob.php @@ -12,8 +12,8 @@ class GenerateResponsiveImagesJob implements ShouldQueue { use InteractsWithQueue; - use SerializesModels; use Queueable; + use SerializesModels; public function __construct(protected Media $media) { diff --git a/src/ResponsiveImages/ResponsiveImageGenerator.php b/src/ResponsiveImages/ResponsiveImageGenerator.php index 3e092792b..8560377ab 100644 --- a/src/ResponsiveImages/ResponsiveImageGenerator.php +++ b/src/ResponsiveImages/ResponsiveImageGenerator.php @@ -6,7 +6,7 @@ use Spatie\MediaLibrary\Conversions\Conversion; use Spatie\MediaLibrary\MediaCollections\Filesystem; use Spatie\MediaLibrary\MediaCollections\Models\Media; -use Spatie\MediaLibrary\ResponsiveImages\Events\ResponsiveImagesGenerated; +use Spatie\MediaLibrary\ResponsiveImages\Events\ResponsiveImagesGeneratedEvent; use Spatie\MediaLibrary\ResponsiveImages\Exceptions\InvalidTinyJpg; use Spatie\MediaLibrary\ResponsiveImages\TinyPlaceholderGenerator\TinyPlaceholderGenerator; use Spatie\MediaLibrary\ResponsiveImages\WidthCalculator\WidthCalculator; @@ -45,7 +45,7 @@ public function generateResponsiveImages(Media $media): void $this->generateResponsiveImage($media, $baseImage, 'media_library_original', $width, $temporaryDirectory); } - event(new ResponsiveImagesGenerated($media)); + event(new ResponsiveImagesGeneratedEvent($media)); $this->generateTinyJpg($media, $baseImage, 'media_library_original', $temporaryDirectory); @@ -69,7 +69,7 @@ public function generateResponsiveImagesForConversion(Media $media, Conversion $ private function getConversionQuality(Conversion $conversion): int { - return $conversion->getManipulations()->getManipulationArgument('quality') ?: self::DEFAULT_CONVERSION_QUALITY; + return $conversion->getManipulations()->getFirstManipulationArgument('quality') ?: self::DEFAULT_CONVERSION_QUALITY; } public function generateResponsiveImage( @@ -144,7 +144,7 @@ public function generateTinyJpg( ResponsiveImage::registerTinySvg($media, $base64Svg, $conversionName); } - protected function appendToFileName(string $filePath, string $suffix, string $extensionFilePath = null): string + protected function appendToFileName(string $filePath, string $suffix, ?string $extensionFilePath = null): string { $baseName = pathinfo($filePath, PATHINFO_FILENAME); diff --git a/src/Support/FileRemover/FileBaseFileRemover.php b/src/Support/FileRemover/FileBaseFileRemover.php index 9119ab682..b69e5904c 100644 --- a/src/Support/FileRemover/FileBaseFileRemover.php +++ b/src/Support/FileRemover/FileBaseFileRemover.php @@ -14,7 +14,7 @@ public function __construct(protected Filesystem $mediaFileSystem, protected Fac public function removeAllFiles(Media $media): void { - $this->removeFile($this->mediaFileSystem->getMediaDirectory($media). $media->file_name, $media->disk); + $this->removeFile($this->mediaFileSystem->getMediaDirectory($media).$media->file_name, $media->disk); $this->removeConvertedImages($media); } diff --git a/src/Support/FileRemover/FileRemover.php b/src/Support/FileRemover/FileRemover.php index 46d80f46b..6d3e2e1ec 100644 --- a/src/Support/FileRemover/FileRemover.php +++ b/src/Support/FileRemover/FileRemover.php @@ -24,5 +24,4 @@ public function removeResponsiveImages(Media $media, string $conversionName): vo * Remove a file relating to the media model. */ public function removeFile(string $path, string $disk): void; - } diff --git a/src/Support/ImageFactory.php b/src/Support/ImageFactory.php index 191baef91..b943fbaa3 100644 --- a/src/Support/ImageFactory.php +++ b/src/Support/ImageFactory.php @@ -2,13 +2,14 @@ namespace Spatie\MediaLibrary\Support; +use Spatie\Image\Drivers\ImageDriver; use Spatie\Image\Image; class ImageFactory { - public static function load(string $path): Image + public static function load(string $path): ImageDriver { - return Image::load($path)->useImageDriver(config('media-library.image_driver')) - ->setTemporaryDirectory(config('media-library.temporary_directory_path') ?? storage_path('media-library/temp')); + return Image::useImageDriver(config('media-library.image_driver')) + ->loadFile($path); } } diff --git a/src/Support/PathGenerator/DefaultPathGenerator.php b/src/Support/PathGenerator/DefaultPathGenerator.php index c7a6ef92f..0e6d1401d 100644 --- a/src/Support/PathGenerator/DefaultPathGenerator.php +++ b/src/Support/PathGenerator/DefaultPathGenerator.php @@ -38,7 +38,7 @@ protected function getBasePath(Media $media): string $prefix = config('media-library.prefix', ''); if ($prefix !== '') { - return $prefix . '/' . $media->getKey(); + return $prefix.'/'.$media->getKey(); } return $media->getKey(); diff --git a/src/Support/PathGenerator/PathGeneratorFactory.php b/src/Support/PathGenerator/PathGeneratorFactory.php index 63d770e6b..f59a61156 100644 --- a/src/Support/PathGenerator/PathGeneratorFactory.php +++ b/src/Support/PathGenerator/PathGeneratorFactory.php @@ -41,7 +41,7 @@ protected static function mediaBelongToModelClass(Media $media, string $modelCla return true; } // config is set via morphMap class name - if (is_a((string)Relation::getMorphedModel($media->model_type), $modelClass, true)) { + if (is_a((string) Relation::getMorphedModel($media->model_type), $modelClass, true)) { return true; } diff --git a/src/Support/UrlGenerator/UrlGenerator.php b/src/Support/UrlGenerator/UrlGenerator.php index c108e4fbf..f8d3e42f4 100644 --- a/src/Support/UrlGenerator/UrlGenerator.php +++ b/src/Support/UrlGenerator/UrlGenerator.php @@ -20,10 +20,7 @@ public function setConversion(Conversion $conversion): self; public function setPathGenerator(PathGenerator $pathGenerator): self; /** - * @param DateTimeInterface $expiration - * @param array $options - * - * @return string + * @param array $options */ public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string; diff --git a/tests/ArchTest.php b/tests/ArchTest.php new file mode 100644 index 000000000..fd6a1e4c3 --- /dev/null +++ b/tests/ArchTest.php @@ -0,0 +1,5 @@ +expect(['dd', 'dump', 'ray']) + ->not->toBeUsed(); diff --git a/tests/Conversions/Commands/CleanCommandTest.php b/tests/Conversions/Commands/CleanCommandTest.php index 1ccadb75e..11c526c4d 100644 --- a/tests/Conversions/Commands/CleanCommandTest.php +++ b/tests/Conversions/Commands/CleanCommandTest.php @@ -184,9 +184,9 @@ it('can clean responsive images for active conversions without responsive images', function () { $media = $this->testModelWithConversion - ->addMedia($this->getTestJpg()) - ->preservingOriginal() - ->toMediaCollection(); + ->addMedia($this->getTestJpg()) + ->preservingOriginal() + ->toMediaCollection(); $thumbResponsiveImageFileName = "{$media->file_name}___thumb_340_280.jpg"; $thumbReponsiveImagesPath = $this->getMediaDirectory("{$media->id}/responsive-images/{$thumbResponsiveImageFileName}"); @@ -195,7 +195,7 @@ $originalResponsiveImagesContent = $media->responsive_images; $newResponsiveImages = $originalResponsiveImagesContent; - $newResponsiveImages['thumb']['base64svg'] = "data:image/svg+xml;base64,PCPg=="; + $newResponsiveImages['thumb']['base64svg'] = 'data:image/svg+xml;base64,PCPg=='; $newResponsiveImages['thumb']['urls'][0] = $thumbResponsiveImageFileName; $media->responsive_images = $newResponsiveImages; $media->save(); @@ -235,7 +235,7 @@ ->preservingOriginal() ->toMediaCollection(); - $deprecatedImage = $this->getMediaDirectory(md5($media->id) . "/c/test-deprecated.jpg"); + $deprecatedImage = $this->getMediaDirectory(md5($media->id).'/c/test-deprecated.jpg'); touch($deprecatedImage); expect($deprecatedImage)->toBeFile(); @@ -243,7 +243,7 @@ $this->artisan('media-library:clean'); $this->assertFileDoesNotExist($deprecatedImage); - expect($this->getMediaDirectory(md5($media->id) . "/c/test-thumb.jpg"))->toBeFile(); + expect($this->getMediaDirectory(md5($media->id).'/c/test-thumb.jpg'))->toBeFile(); }); it('can clean deprecated conversion files in same path as original image', function () { @@ -355,7 +355,8 @@ }); it('will not clean media items on soft deleted models', function () { - $testModelClass = new class () extends TestModel { + $testModelClass = new class() extends TestModel + { use SoftDeletes; }; diff --git a/tests/Conversions/ConversionCollectionTest.php b/tests/Conversions/ConversionCollectionTest.php index 755e00ca7..80e6450d6 100644 --- a/tests/Conversions/ConversionCollectionTest.php +++ b/tests/Conversions/ConversionCollectionTest.php @@ -8,7 +8,7 @@ ->preservingOriginal() ->toMediaCollection(); - $media->manipulations = ['thumb' => ['filter' => 'greyscale', 'height' => 10]]; + $media->manipulations = ['thumb' => ['greyscale' => [], 'height' => [10]]]; $media->save(); $secondMedia = $this->testModelWithConversion @@ -16,7 +16,7 @@ ->preservingOriginal() ->toMediaCollection(); - $secondMedia->manipulations = ['thumb' => ['filter' => 'greyscale', 'height' => 20]]; + $secondMedia->manipulations = ['thumb' => ['greyscale' => [], 'height' => [20]]]; $secondMedia->save(); $this->media = $media->fresh(); @@ -25,8 +25,8 @@ it('will prepend the manipulation saved on the model and the wildmark manipulations', function () { $this->media->manipulations = [ - '*' => ['brightness' => '-80'], - 'thumb' => ['filter' => 'greyscale', 'height' => 10], + '*' => ['brightness' => ['-80']], + 'thumb' => ['greyscale' => [], 'height' => [10]], ]; $conversionCollection = ConversionCollection::createForMedia($this->media); @@ -35,46 +35,44 @@ expect($conversion->getName())->toEqual('thumb'); - $manipulationSequence = $conversion + $manipulations = $conversion ->getManipulations() - ->getManipulationSequence() ->toArray(); - $this->assertArrayHasKey('optimize', $manipulationSequence[0]); + $this->assertArrayHasKey('optimize', $manipulations); - unset($manipulationSequence[0]['optimize']); + unset($manipulations['optimize']); - $this->assertEquals([[ - 'brightness' => '-80', - 'filter' => 'greyscale', - 'height' => 10, - 'width' => 50, - 'format' => 'jpg', - ]], $manipulationSequence); + $this->assertEquals([ + 'greyscale' => [], + 'height' => [10], + 'brightness' => ['-80'], + 'format' => ['jpg'], + 'width' => [50], + ], $manipulations); }); it('will prepend the manipulation saved on the model', function () { $conversionCollection = ConversionCollection::createForMedia($this->media); - $conversion = $conversionCollection->getConversions()[0]; + $conversion = $conversionCollection->getConversions()->first(); expect($conversion->getName())->toEqual('thumb'); - $manipulationSequence = $conversion + $manipulations = $conversion ->getManipulations() - ->getManipulationSequence() ->toArray(); - $this->assertArrayHasKey('optimize', $manipulationSequence[0]); + $this->assertArrayHasKey('optimize', $manipulations); - unset($manipulationSequence[0]['optimize']); + unset($manipulations['optimize']); - $this->assertEquals([[ - 'filter' => 'greyscale', - 'height' => 10, - 'width' => 50, - 'format' => 'jpg', - ]], $manipulationSequence); + $this->assertEquals([ + 'greyscale' => [], + 'height' => [10], + 'format' => ['jpg'], + 'width' => [50], + ], $manipulations); }); it('will apply the manipulation on the equally named conversion of every model', function () { diff --git a/tests/Conversions/ConversionFileNamerTest.php b/tests/Conversions/ConversionFileNamerTest.php index 62c0ab2c6..8003e863f 100644 --- a/tests/Conversions/ConversionFileNamerTest.php +++ b/tests/Conversions/ConversionFileNamerTest.php @@ -3,19 +3,19 @@ use Spatie\MediaLibrary\Tests\TestSupport\TestFileNamer; it('can use a custom file namer', function () { - $fileName = "prefix_test_suffix"; + $fileName = 'prefix_test_suffix'; - config()->set("media-library.file_namer", TestFileNamer::class); + config()->set('media-library.file_namer', TestFileNamer::class); $this ->testModelWithConversion ->addMedia($this->getTestJpg()) ->toMediaCollection(); - $path = $this->testModelWithConversion->refresh()->getFirstMediaPath("default", "thumb"); + $path = $this->testModelWithConversion->refresh()->getFirstMediaPath('default', 'thumb'); expect($path)->toEndWith("{$fileName}---thumb.jpg"); expect($path)->toBeFile(); - expect($this->testModelWithConversion->getFirstMediaUrl("default", "thumb"))->toEqual("/media/1/conversions/{$fileName}---thumb.jpg"); + 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 aff29838d..34b2cb835 100644 --- a/tests/Conversions/ConversionTest.php +++ b/tests/Conversions/ConversionTest.php @@ -1,7 +1,7 @@ conversionName = 'test'; @@ -15,13 +15,13 @@ it('will add a format parameter if it was not given', function () { $this->conversion->width(10); - expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual('jpg'); + 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'); + expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual(['png']); }); it('will be performed on the given collection names', function () { @@ -80,7 +80,7 @@ }); it('can remove a previously set manipulation', function () { - expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual('jpg'); + expect($this->conversion->getManipulations()->getManipulationArgument('format'))->toEqual(['jpg']); $this->conversion->removeManipulation('format'); @@ -101,24 +101,6 @@ 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); @@ -126,17 +108,16 @@ $manipulations = $this->conversion ->getManipulations() - ->getManipulationSequence() ->toArray(); - $this->assertArrayHasKey('optimize', $manipulations[0]); + $this->assertArrayHasKey('optimize', $manipulations); - unset($manipulations[0]['optimize']); + unset($manipulations['optimize']); - $this->assertEquals([[ - 'width' => 10, - 'format' => 'jpg', - ]], $manipulations); + $this->assertEquals([ + 'width' => [10], + 'format' => ['jpg'], + ], $manipulations); }); it('will optimize the converted image by default', function () { @@ -145,17 +126,16 @@ ->getManipulationSequence() ->toArray(); - $this->assertArrayHasKey('optimize', $manipulations[0]); + $this->assertArrayHasKey('optimize', $manipulations); }); it('can remove the optimization', function () { $manipulations = (new Conversion('test')) ->nonOptimized() ->getManipulations() - ->getManipulationSequence() ->toArray(); - $this->assertArrayNotHasKey('optimize', $manipulations[0]); + $this->assertArrayNotHasKey('optimize', $manipulations); }); it('will use the pdf page number parameter if it was given', function () { diff --git a/tests/Conversions/EventTest.php b/tests/Conversions/EventTest.php index ac93051dc..af7a6b230 100644 --- a/tests/Conversions/EventTest.php +++ b/tests/Conversions/EventTest.php @@ -1,9 +1,9 @@ testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - Event::assertDispatched(ConversionWillStart::class); + Event::assertDispatched(ConversionWillStartEvent::class); }); it('will fire the conversion complete event', function () { $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - Event::assertDispatched(ConversionHasBeenCompleted::class); + Event::assertDispatched(ConversionHasBeenCompletedEvent::class); }); it('will fire the collection cleared event', function () { @@ -29,5 +29,5 @@ $this->testModel->clearMediaCollection('images'); - Event::assertDispatched(CollectionHasBeenCleared::class); + Event::assertDispatched(CollectionHasBeenClearedEvent::class); }); diff --git a/tests/Conversions/ImageGenerators/SvgTest.php b/tests/Conversions/ImageGenerators/SvgTest.php index 23144d8e0..660afb0d3 100644 --- a/tests/Conversions/ImageGenerators/SvgTest.php +++ b/tests/Conversions/ImageGenerators/SvgTest.php @@ -3,6 +3,8 @@ use Spatie\MediaLibrary\Conversions\ImageGenerators\Svg; it('can convert a svg', function () { + config()->set('media-library.image_driver', 'imagick'); + $imageGenerator = new Svg(); if (! $imageGenerator->requirementsAreInstalled()) { @@ -16,4 +18,4 @@ $imageFile = $imageGenerator->convert($media->getPath()); expect(mime_content_type($imageFile))->toEqual('image/jpeg'); -}); +})->skipWhenRunningLocally(); diff --git a/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php b/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php index a2626f21b..73f7fdaed 100644 --- a/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php +++ b/tests/Conversions/ImageGenerators/TestImageGeneratorWithConfigTest.php @@ -20,7 +20,7 @@ test('image generators will receive config parameters by name', function () { config()->set('media-library.image_generators', [ - TestImageGeneratorWithConfig::class => ['secondName' => 'secondValue', 'firstName' => 'firstValue', ], + TestImageGeneratorWithConfig::class => ['secondName' => 'secondValue', 'firstName' => 'firstValue'], ]); $imageGenerators = ImageGeneratorFactory::getImageGenerators(); diff --git a/tests/Feature/FileAdder/IntegrationTest.php b/tests/Feature/FileAdder/IntegrationTest.php index 9bc4f2182..211b28370 100644 --- a/tests/Feature/FileAdder/IntegrationTest.php +++ b/tests/Feature/FileAdder/IntegrationTest.php @@ -445,10 +445,10 @@ $media = $this->testModelWithConversion ->addMedia($this->getTestJpg()) ->preservingOriginal() - ->withManipulations(['thumb' => ['width' => '10']]) + ->withManipulations(['thumb' => ['width' => ['10']]]) ->toMediaCollection(); - expect($media->manipulations['thumb']['width'])->toEqual('10'); + expect($media->manipulations['thumb']['width'])->toEqual(['10']); }); it('can add file to model with morph map', function () { @@ -592,8 +592,8 @@ it('will throw an exception and revert database when file cannot be added', function () { $this->testModel - ->addMedia($this->getTestPng()) - ->toMediaCollection(); + ->addMedia($this->getTestPng()) + ->toMediaCollection(); expect(Media::count())->toBe(1); @@ -615,7 +615,8 @@ }); it('will throw an exception and revert database when file cannot be added and model uses softdeletes', function () { - $testModelClass = new class () extends TestModel { + $testModelClass = new class() extends TestModel + { use SoftDeletes; }; @@ -623,8 +624,8 @@ $testModel = $testModelClass::find($this->testModel->id); $testModel - ->addMedia($this->getTestPng()) - ->toMediaCollection(); + ->addMedia($this->getTestPng()) + ->toMediaCollection(); expect(Media::count())->toBe(1); diff --git a/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php b/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php index ec96dabb0..9a33996f9 100644 --- a/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php +++ b/tests/Feature/FileAdder/MediaConversions/AddMediaTest.php @@ -1,8 +1,8 @@ addMediaConversion('my-conversion') ->setManipulations(function (Manipulations $manipulations) { @@ -66,6 +67,8 @@ public function registerMediaConversions(Media $media = null): void }); it('can create a derived version of a pdf if imagick exists', function () { + config()->set('media-library.image_driver', 'imagick'); + $media = $this->testModelWithConversion ->addMedia($this->getTestFilesDirectory('test.pdf')) ->toMediaCollection('images'); @@ -95,7 +98,8 @@ class_exists(Imagick::class) }); it('will have access the model instance when register media conversions using model instance has been set', function () { - $modelClass = new class () extends TestModel { + $modelClass = new class() extends TestModel + { public bool $registerMediaConversionsUsingModelInstance = true; /** @@ -103,7 +107,7 @@ class_exists(Imagick::class) * * @return array */ - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { $this->addMediaConversion('thumb') ->width($this->width) @@ -122,14 +126,14 @@ public function registerMediaConversions(Media $media = null): void $conversionCollection = ConversionCollection::createForMedia($media); - $conversion = $conversionCollection->getConversions()[0]; + $conversion = $conversionCollection->getConversions()->first(); $conversionManipulations = $conversion ->getManipulations() ->getManipulationSequence() - ->toArray()[0]; + ->toArray(); - expect($conversionManipulations['width'])->toEqual(123); + expect($conversionManipulations['width'])->toEqual([123]); }); it('can set filesize', function () { diff --git a/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php b/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php index ba4225096..22f803d80 100644 --- a/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php +++ b/tests/Feature/FileAdder/MediaConversions/MediaCollectionTest.php @@ -7,7 +7,8 @@ use Spatie\MediaLibrary\Tests\TestSupport\TestModels\TestModelWithoutMediaConversions; it('will use the disk from a media collection', function () { - $testModel = new class () extends TestModelWithConversion { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this->addMediaCollection('images') @@ -29,7 +30,8 @@ public function registerMediaCollections(): void }); it('will not use the disk name of the collection if a diskname is specified while adding', function () { - $testModel = new class () extends TestModelWithConversion { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this->addMediaCollection('images') @@ -47,7 +49,8 @@ public function registerMediaCollections(): void }); it('can register media conversions when defining media collections', function () { - $testModel = new class () extends TestModelWithoutMediaConversions { + $testModel = new class() extends TestModelWithoutMediaConversions + { public function registerMediaCollections(): void { $this @@ -68,7 +71,8 @@ public function registerMediaCollections(): void }); it('will not use media conversions from an unrelated collection', function () { - $testModel = new class () extends TestModelWithoutMediaConversions { + $testModel = new class() extends TestModelWithoutMediaConversions + { public function registerMediaCollections(): void { $this @@ -89,8 +93,9 @@ public function registerMediaCollections(): void }); 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 + $testModel = new class() extends TestModelWithoutMediaConversions + { + public function registerMediaConversions(?Media $media = null): void { $this ->addMediaConversion('another-thumb') @@ -101,7 +106,7 @@ public function registerMediaCollections(): void { $this ->addMediaCollection('images') - ->registerMediaConversions(function (Media $media = null) { + ->registerMediaConversions(function (?Media $media = null) { $this ->addMediaConversion('thumb') ->greyscale(); @@ -119,7 +124,8 @@ public function registerMediaCollections(): void }); it('can accept certain files', function () { - $testModel = new class () extends TestModelWithConversion { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this @@ -138,7 +144,8 @@ public function registerMediaCollections(): void }); it('can guard against invalid mimetypes', function () { - $testModel = new class () extends TestModelWithConversion { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this @@ -157,7 +164,8 @@ public function registerMediaCollections(): void }); it('can generate responsive images', function () { - $testModel = new class () extends TestModelWithConversion { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this @@ -182,7 +190,8 @@ public function registerMediaCollections(): void }); it('can generate responsive images on condition', function () { - $testModel = new class () extends TestModelWithConversion { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this @@ -207,7 +216,8 @@ public function registerMediaCollections(): void }); 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 { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this @@ -226,7 +236,8 @@ public function registerMediaCollections(): void }); 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 { + $testModel = new class() extends TestModelWithConversion + { public function registerMediaCollections(): void { $this diff --git a/tests/Feature/InteractsWithMedia/DeleteMediaTest.php b/tests/Feature/InteractsWithMedia/DeleteMediaTest.php index 8be889660..6817a6fcc 100644 --- a/tests/Feature/InteractsWithMedia/DeleteMediaTest.php +++ b/tests/Feature/InteractsWithMedia/DeleteMediaTest.php @@ -49,7 +49,7 @@ it('will remove the files when using a custom model and deleting it', function () { config()->set('media-library.media_model', TestCustomMediaModel::class); - (new MediaLibraryServiceProvider(app()))->boot(); + (new MediaLibraryServiceProvider(app()))->register()->boot(); $testModel = TestModel::create(['name' => 'test']); diff --git a/tests/Feature/InteractsWithMedia/GetMediaTest.php b/tests/Feature/InteractsWithMedia/GetMediaTest.php index 071967d03..08b2f15ae 100644 --- a/tests/Feature/InteractsWithMedia/GetMediaTest.php +++ b/tests/Feature/InteractsWithMedia/GetMediaTest.php @@ -274,7 +274,7 @@ ], $preloadedTestModel ->getMedia('images') ->pluck('order_column', 'id') - ->map(fn ($value) => (int)$value) + ->map(fn ($value) => (int) $value) ->toArray()); $firstMedia->order_column = 3; @@ -290,7 +290,7 @@ ], $preloadedTestModel ->getMedia('images') ->pluck('order_column', 'id') - ->map(fn ($value) => (int)$value) + ->map(fn ($value) => (int) $value) ->toArray()); }); diff --git a/tests/Feature/InteractsWithMedia/HasMediaTest.php b/tests/Feature/InteractsWithMedia/HasMediaTest.php index 47e6948cf..e5d5baf7f 100644 --- a/tests/Feature/InteractsWithMedia/HasMediaTest.php +++ b/tests/Feature/InteractsWithMedia/HasMediaTest.php @@ -1,7 +1,5 @@ testModel->hasMedia())->toBeFalse(); }); diff --git a/tests/Feature/InteractsWithMedia/UpdateMediaTest.php b/tests/Feature/InteractsWithMedia/UpdateMediaTest.php index 8fa5871e3..0c1d26294 100644 --- a/tests/Feature/InteractsWithMedia/UpdateMediaTest.php +++ b/tests/Feature/InteractsWithMedia/UpdateMediaTest.php @@ -1,7 +1,5 @@ testModel->addMedia($this->getTestJpg())->usingName('test1')->preservingOriginal()->toMediaCollection(); $this->testModel->addMedia($this->getTestJpg())->usingName('test2')->preservingOriginal()->toMediaCollection(); diff --git a/tests/Feature/Media/CustomHeadersTest.php b/tests/Feature/Media/CustomHeadersTest.php index 6cdcde455..20c3d7626 100644 --- a/tests/Feature/Media/CustomHeadersTest.php +++ b/tests/Feature/Media/CustomHeadersTest.php @@ -1,7 +1,5 @@ testModel ->addMedia($this->getTestJpg()) diff --git a/tests/Feature/Media/CustomPropertyTest.php b/tests/Feature/Media/CustomPropertyTest.php index 5ac9e4c50..ff7c4c162 100644 --- a/tests/Feature/Media/CustomPropertyTest.php +++ b/tests/Feature/Media/CustomPropertyTest.php @@ -1,7 +1,5 @@ media = $this->testModel ->addMedia($this->getTestJpg()) diff --git a/tests/Feature/Media/DeleteTest.php b/tests/Feature/Media/DeleteTest.php index 746552ea9..7588a084c 100644 --- a/tests/Feature/Media/DeleteTest.php +++ b/tests/Feature/Media/DeleteTest.php @@ -68,7 +68,6 @@ $media = $this->testModelWithConversion->addMedia($this->getTestJpg())->toMediaCollection('images'); - expect(File::exists($media->getPath()))->toBeTrue(); expect(File::exists($media->getPath('thumb')))->toBeTrue(); expect(File::exists($media->getPath('keep_original_format')))->toBeTrue(); @@ -88,12 +87,12 @@ $pathGenerator = new CustomDirectoryStructurePathGenerator(); expect(File::exists($media->getPath()))->toBeTrue(); - expect(Storage::disk($media->disk)->exists($pathGenerator->getPathForResponsiveImages($media). 'test___thumb_50_63.jpg'))->toBeTrue(); + expect(Storage::disk($media->disk)->exists($pathGenerator->getPathForResponsiveImages($media).'test___thumb_50_63.jpg'))->toBeTrue(); $media->delete(); expect(File::exists($media->getPath()))->toBeFalse(); - expect(Storage::disk($media->disk)->exists($pathGenerator->getPathForResponsiveImages($media). 'test___thumb_50_63.jpg'))->toBeFalse(); + expect(Storage::disk($media->disk)->exists($pathGenerator->getPathForResponsiveImages($media).'test___thumb_50_63.jpg'))->toBeFalse(); }); @@ -101,7 +100,6 @@ config(['media-library.path_generator' => CustomDirectoryStructurePathGenerator::class]); config(['media-library.file_remover_class' => FileBaseFileRemover::class]); - $media = $this->testModel->addMedia($this->getTestJpg())->toMediaCollection('images'); $media2 = $this->testModel->addMedia($this->getTestPng())->toMediaCollection('images'); @@ -115,7 +113,8 @@ }); it('will not remove the files when should delete preserving media returns true', function () { - $testModelClass = new class () extends TestModel { + $testModelClass = new class() extends TestModel + { public function shouldDeletePreservingMedia(): bool { return true; @@ -134,7 +133,8 @@ public function shouldDeletePreservingMedia(): bool }); it('will remove the files when should delete preserving media returns false', function () { - $testModelClass = new class () extends TestModel { + $testModelClass = new class() extends TestModel + { public function shouldDeletePreservingMedia(): bool { return false; @@ -153,7 +153,8 @@ public function shouldDeletePreservingMedia(): bool }); it('will not remove the file when model uses softdelete', function () { - $testModelClass = new class () extends TestModel { + $testModelClass = new class() extends TestModel + { use SoftDeletes; }; @@ -172,7 +173,8 @@ public function shouldDeletePreservingMedia(): bool }); it('will remove the file when model uses softdelete with force', function () { - $testModelClass = new class () extends TestModel { + $testModelClass = new class() extends TestModel + { use SoftDeletes; }; diff --git a/tests/Feature/Media/GetAvailableUrlTest.php b/tests/Feature/Media/GetAvailableUrlTest.php index 3cd7e877f..ad1edc7fd 100644 --- a/tests/Feature/Media/GetAvailableUrlTest.php +++ b/tests/Feature/Media/GetAvailableUrlTest.php @@ -9,19 +9,19 @@ expect($media->getAvailableUrl(['small', 'medium', 'large']))->toEqual("/media/{$media->id}/conversions/test-large.jpg"); expect($media->getAvailableFullUrl(['small', 'medium', 'large']))->toEqual("http://localhost/media/{$media->id}/conversions/test-large.jpg"); - expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/conversions/test-large.jpg")); + expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory()."/{$media->id}/conversions/test-large.jpg")); $media->markAsConversionGenerated('medium'); expect($media->getAvailableUrl(['small', 'medium', 'large']))->toEqual("/media/{$media->id}/conversions/test-medium.jpg"); expect($media->getAvailableFullUrl(['small', 'medium', 'large']))->toEqual("http://localhost/media/{$media->id}/conversions/test-medium.jpg"); - expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/conversions/test-medium.jpg")); + expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory()."/{$media->id}/conversions/test-medium.jpg")); $media->markAsConversionGenerated('small'); expect($media->getAvailableUrl(['small', 'medium', 'large']))->toEqual("/media/{$media->id}/conversions/test-small.jpg"); expect($media->getAvailableFullUrl(['small', 'medium', 'large']))->toEqual("http://localhost/media/{$media->id}/conversions/test-small.jpg"); - expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/conversions/test-small.jpg")); + expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory()."/{$media->id}/conversions/test-small.jpg")); }); it('uses original url if no conversion has been generated yet', function () { @@ -32,5 +32,5 @@ expect($media->getAvailableUrl(['small', 'medium', 'large']))->toEqual("/media/{$media->id}/test.jpg"); expect($media->getAvailableFullUrl(['small', 'medium', 'large']))->toEqual("http://localhost/media/{$media->id}/test.jpg"); - expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory() . "/{$media->id}/test.jpg")); + expect($media->getAvailablePath(['small', 'medium', 'large']))->toEqual($this->makePathOsSafe($this->getMediaDirectory()."/{$media->id}/test.jpg")); }); diff --git a/tests/Feature/Media/GetMediaConversionsTest.php b/tests/Feature/Media/GetMediaConversionsTest.php index d0f7d5b0d..166e03cb1 100644 --- a/tests/Feature/Media/GetMediaConversionsTest.php +++ b/tests/Feature/Media/GetMediaConversionsTest.php @@ -1,7 +1,5 @@ testModel ->addMedia($this->getTestJpg()) diff --git a/tests/Feature/Media/GetOriginalUrlAttributeTest.php b/tests/Feature/Media/GetOriginalUrlAttributeTest.php index 74e2566e7..dfa26b4d2 100644 --- a/tests/Feature/Media/GetOriginalUrlAttributeTest.php +++ b/tests/Feature/Media/GetOriginalUrlAttributeTest.php @@ -1,7 +1,5 @@ testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); diff --git a/tests/Feature/Media/GetPathTest.php b/tests/Feature/Media/GetPathTest.php index 7f06c105d..1de1e417f 100644 --- a/tests/Feature/Media/GetPathTest.php +++ b/tests/Feature/Media/GetPathTest.php @@ -5,7 +5,7 @@ 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()); @@ -17,7 +17,7 @@ $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)); @@ -37,7 +37,7 @@ $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()); @@ -51,7 +51,7 @@ $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)); diff --git a/tests/Feature/Media/GetPreviewUrlAttributeTest.php b/tests/Feature/Media/GetPreviewUrlAttributeTest.php index 818c692f7..837cf8307 100644 --- a/tests/Feature/Media/GetPreviewUrlAttributeTest.php +++ b/tests/Feature/Media/GetPreviewUrlAttributeTest.php @@ -1,7 +1,5 @@ testModelWithPreviewConversion->addMedia($this->getTestJpg())->toMediaCollection(); diff --git a/tests/Feature/Media/GetTypeTest.php b/tests/Feature/Media/GetTypeTest.php index eb55275ae..6223054cd 100644 --- a/tests/Feature/Media/GetTypeTest.php +++ b/tests/Feature/Media/GetTypeTest.php @@ -1,7 +1,5 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection(); diff --git a/tests/Feature/Media/RenameTest.php b/tests/Feature/Media/RenameTest.php index ee6565019..db02ab62e 100644 --- a/tests/Feature/Media/RenameTest.php +++ b/tests/Feature/Media/RenameTest.php @@ -1,7 +1,5 @@ getTestFilesDirectory('test.jpg'); diff --git a/tests/Feature/Media/ResponsableTest.php b/tests/Feature/Media/ResponsableTest.php index 23b1b11fc..1997d4bbd 100644 --- a/tests/Feature/Media/ResponsableTest.php +++ b/tests/Feature/Media/ResponsableTest.php @@ -1,7 +1,5 @@ get('/upload', fn () => $this->testModel ->addMedia($this->getTestJpg()) diff --git a/tests/Feature/Media/ToHtmlTest.php b/tests/Feature/Media/ToHtmlTest.php index 1e964b96a..c73a68b44 100644 --- a/tests/Feature/Media/ToHtmlTest.php +++ b/tests/Feature/Media/ToHtmlTest.php @@ -55,6 +55,8 @@ }); it('can render pdf thumbnail as an image', function () { + config()->set('media-library.image_driver', 'imagick'); + $media = $this->testModelWithConversion ->addMedia($this->getTestPdf()) ->toMediaCollection(); @@ -84,8 +86,8 @@ $image = $media->refresh()->img('thumb'); - expect((string)$image)->toContain('/media/2/responsive-images/'); - expect((string)$image)->toContain('data:image/svg+xml;base64,'); + expect((string) $image)->toContain('/media/2/responsive-images/'); + expect((string) $image)->toContain('data:image/svg+xml;base64,'); }); it('will not render extra javascript or include base64 svg when tiny placeholders are turned off', function () { diff --git a/tests/Feature/Media/UpdateManipulationsTest.php b/tests/Feature/Media/UpdateManipulationsTest.php index 1d3ef6455..4d6175de5 100644 --- a/tests/Feature/Media/UpdateManipulationsTest.php +++ b/tests/Feature/Media/UpdateManipulationsTest.php @@ -4,8 +4,9 @@ use Spatie\MediaLibrary\Tests\TestSupport\TestModels\TestModel; it('will create derived files when manipulations have changed', function () { - $testModelClass = new class () extends TestModel { - public function registerMediaConversions(Media $media = null): void + $testModelClass = new class() extends TestModel + { + public function registerMediaConversions(?Media $media = null): void { $this->addMediaConversion('update_test'); } @@ -35,8 +36,9 @@ public function registerMediaConversions(Media $media = null): void }); it('will not create derived files when manipulations have not changed', function () { - $testModelClass = new class () extends TestModel { - public function registerMediaConversions(Media $media = null): void + $testModelClass = new class() extends TestModel + { + public function registerMediaConversions(?Media $media = null): void { $this->addMediaConversion('update_test'); } diff --git a/tests/Feature/S3Integration/S3TestPathGenerator.php b/tests/Feature/S3Integration/S3TestPathGenerator.php index b77822097..e4bb5c6ff 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 (getS3BaseTestDirectory()).'/'.$media->getKey(); + return getS3BaseTestDirectory().'/'.$media->getKey(); } } diff --git a/tests/Image/ImageFactoryTest.php b/tests/Image/ImageFactoryTest.php index 8fcf82ae7..4a4cba189 100644 --- a/tests/Image/ImageFactoryTest.php +++ b/tests/Image/ImageFactoryTest.php @@ -7,13 +7,5 @@ $image = ImageFactory::load($this->getTestJpg()); - $reflection = new ReflectionClass($image); - - $imageDriver = $reflection->getProperty('imageDriver'); - - $imageDriver->setAccessible(true); - - $imageDriverValue = $imageDriver->getValue($image); - - expect($imageDriverValue)->toEqual('imagick'); + expect($image->driverName())->toBe('imagick'); }); diff --git a/tests/MediaCollections/EventTest.php b/tests/MediaCollections/EventTest.php index eb9e23a50..043007c9c 100644 --- a/tests/MediaCollections/EventTest.php +++ b/tests/MediaCollections/EventTest.php @@ -1,12 +1,12 @@ testModel->addMedia($this->getTestJpg())->toMediaCollection(); - Event::assertDispatched(MediaHasBeenAdded::class); + Event::assertDispatched(MediaHasBeenAddedEvent::class); }); diff --git a/tests/Pest.php b/tests/Pest.php index 4a75f472f..a7ee56ca0 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -55,3 +55,17 @@ function unserializeAndSerializeModel($model) { return unserialize(serialize($model)); } + +function skipWhenRunningOnGitHub(): void +{ + if (getenv('GITHUB_ACTIONS') !== false) { + test()->markTestSkipped('This test cannot run on GitHub actions'); + } +} + +function skipWhenRunningLocally(): void +{ + if (getenv('GITHUB_ACTIONS') === false) { + test()->markTestSkipped('This test cannot run locally'); + } +} diff --git a/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php b/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php index 6c30ce2a0..39d209551 100644 --- a/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php +++ b/tests/ResponsiveImages/ResponsiveImageFileNamerTest.php @@ -3,8 +3,8 @@ use Spatie\MediaLibrary\Tests\TestSupport\TestFileNamer; beforeEach(function () { - config()->set("media-library.file_namer", TestFileNamer::class); + 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 d074f2753..5d11ced1c 100644 --- a/tests/ResponsiveImages/ResponsiveImageGeneratorFileNamerTest.php +++ b/tests/ResponsiveImages/ResponsiveImageGeneratorFileNamerTest.php @@ -3,7 +3,7 @@ use Spatie\MediaLibrary\Tests\TestSupport\TestFileNamer; beforeEach(function () { - config()->set("media-library.file_namer", TestFileNamer::class); + 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 1dbe205cd..2496614db 100644 --- a/tests/ResponsiveImages/ResponsiveImageGeneratorTest.php +++ b/tests/ResponsiveImages/ResponsiveImageGeneratorTest.php @@ -1,7 +1,7 @@ fileName = 'test'; @@ -9,9 +9,9 @@ it('can generate responsive images', function () { $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); + ->addMedia($this->getTestJpg()) + ->withResponsiveImages() + ->toMediaCollection(); 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(); @@ -20,9 +20,9 @@ it('will generate responsive images if with responsive images if returns true', function () { $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImagesIf(fn () => true) - ->toMediaCollection(); + ->addMedia($this->getTestJpg()) + ->withResponsiveImagesIf(fn () => true) + ->toMediaCollection(); 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(); @@ -31,67 +31,58 @@ it('will not generate responsive images if with responsive images if returns false', function () { $this->testModel - ->addMedia($this->getTestJpg()) - ->withResponsiveImagesIf(fn () => false) - ->toMediaCollection(); + ->addMedia($this->getTestJpg()) + ->withResponsiveImagesIf(fn () => false) + ->toMediaCollection(); $this->assertFileDoesNotExist($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg")); }); test('its conversions can have responsive images', function () { $this->testModelWithResponsiveImages - ->addMedia($this->getTestJpg()) - ->withResponsiveImages() - ->toMediaCollection(); - - 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()) + ->addMedia($this->getTestJpg()) ->withResponsiveImages() ->toMediaCollection(); - expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___pngtojpg_700_883.jpg"))->toBeFile(); + expect($this->getTempDirectory("media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg"))->toBeFile(); }); it('triggers an event when the responsive images are generated', function () { - Event::fake(ResponsiveImagesGenerated::class); + Event::fake(ResponsiveImagesGeneratedEvent::class); $this->testModelWithResponsiveImages ->addMedia($this->getTestJpg()) ->withResponsiveImages() ->toMediaCollection(); - Event::assertDispatched(ResponsiveImagesGenerated::class); + Event::assertDispatched(ResponsiveImagesGeneratedEvent::class); }); it('cleans the responsive images urls from the db before regeneration', function () { $media = $this->testModelWithResponsiveImages - ->addMedia($this->getTestFilesDirectory("test.jpg")) + ->addMedia($this->getTestFilesDirectory('test.jpg')) ->withResponsiveImages() ->toMediaCollection(); - expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(1); + expect($media->fresh()->responsive_images['thumb']['urls'])->toHaveCount(1); - $this->artisan("media-library:regenerate"); - 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")) + ->addMedia($this->getTestFilesDirectory('test.jpg')) ->withResponsiveImages() ->toMediaCollection(); // remove all responsive image db entries $responsiveImages = $media->responsive_images; - $responsiveImages["thumb"]["urls"] = []; + $responsiveImages['thumb']['urls'] = []; $media->responsive_images = $responsiveImages; $media->save(); - expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(0); + expect($media->fresh()->responsive_images['thumb']['urls'])->toHaveCount(0); - $this->artisan("media-library:regenerate"); - expect($media->fresh()->responsive_images["thumb"]["urls"])->toHaveCount(1); + $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 77bdd15cc..66cf6e560 100644 --- a/tests/ResponsiveImages/ResponsiveImageTest.php +++ b/tests/ResponsiveImages/ResponsiveImageTest.php @@ -22,9 +22,9 @@ $this->assertEquals([ "/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls("thumb")); + ], $media->getResponsiveImageUrls('thumb')); - expect($media->getResponsiveImageUrls("non-existing-conversion"))->toEqual([]); + expect($media->getResponsiveImageUrls('non-existing-conversion'))->toEqual([]); }); test('a media instance can generate the contents of scrset', function () { @@ -39,13 +39,13 @@ "/media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg 340w, /media/1/responsive-images/{$this->fileName}___media_library_original_284_234.jpg 284w, /media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg 237w", $media->getSrcset() ); - expect($media->getSrcset())->toContain("data:image/svg+xml;base64"); + expect($media->getSrcset())->toContain('data:image/svg+xml;base64'); $this->assertStringContainsString( "/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg 50w", - $media->getSrcset("thumb") + $media->getSrcset('thumb') ); - expect($media->getSrcset("thumb"))->toContain("data:image/svg+xml;base64,"); + expect($media->getSrcset('thumb'))->toContain('data:image/svg+xml;base64,'); }); test('a responsive image can return some properties', function () { @@ -58,7 +58,7 @@ $responsiveImage = $media->responsiveImages()->files->first(); - expect($responsiveImage->generatedFor())->toEqual("media_library_original"); + expect($responsiveImage->generatedFor())->toEqual('media_library_original'); expect($responsiveImage->width())->toEqual(340); @@ -69,7 +69,7 @@ $this->testModelWithResponsiveImages ->addMedia($this->getTestJpg()) ->preservingOriginal() - ->toMediaCollection("default"); + ->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"); @@ -81,14 +81,14 @@ $this->testModelWithResponsiveImages ->addMedia($this->getTestJpg()) ->withResponsiveImages() - ->storingConversionsOnDisk("secondMediaDisk") + ->storingConversionsOnDisk('secondMediaDisk') ->toMediaCollection(); $media = $this->testModelWithResponsiveImages->getFirstMedia(); $this->assertEquals([ "/media2/1/responsive-images/{$this->fileName}___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls("thumb")); + ], $media->getResponsiveImageUrls('thumb')); }); it('can handle file names with underscore', function () { @@ -108,7 +108,7 @@ $this->assertSame([ "/media/1/responsive-images/{$this->fileNameWithUnderscore}___thumb_50_41.jpg", - ], $media->getResponsiveImageUrls("thumb")); + ], $media->getResponsiveImageUrls('thumb')); - expect($media->getResponsiveImageUrls("non-existing-conversion"))->toBe([]); + expect($media->getResponsiveImageUrls('non-existing-conversion'))->toBe([]); }); diff --git a/tests/Support/PathGenerator/CustomDirectoryStructurePathGenerator.php b/tests/Support/PathGenerator/CustomDirectoryStructurePathGenerator.php index ad10b3d29..417bf62a9 100644 --- a/tests/Support/PathGenerator/CustomDirectoryStructurePathGenerator.php +++ b/tests/Support/PathGenerator/CustomDirectoryStructurePathGenerator.php @@ -14,11 +14,11 @@ public function getPath(Media $media): string public function getPathForConversions(Media $media): string { - return $this->getPath($media) . 'c/'; + return $this->getPath($media).'c/'; } public function getPathForResponsiveImages(Media $media): string { - return $this->getPath($media) . 'cri/'; + return $this->getPath($media).'cri/'; } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 7d2b9d7bf..13f4b1418 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -81,8 +81,7 @@ protected function loadEnvironmentVariables() } /** - * @param \Illuminate\Foundation\Application $app - * + * @param \Illuminate\Foundation\Application $app * @return array */ protected function getPackageProviders($app) @@ -95,7 +94,7 @@ protected function getPackageProviders($app) } /** - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app */ public function getEnvironmentSetUp($app) { @@ -131,7 +130,7 @@ public function getEnvironmentSetUp($app) } /** - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app */ protected function setUpDatabase($app) { @@ -144,13 +143,12 @@ protected function setUpDatabase($app) TestModel::create(['name' => 'test']); - if (MediaLibraryPro::isInstalled()) { include_once __DIR__.'/../vendor/spatie/laravel-medialibrary-pro/database/migrations/create_temporary_uploads_table.stub'; (new CreateTemporaryUploadsTable())->up(); } - $mediaTableMigration = require(__DIR__.'/../database/migrations/create_media_table.php.stub'); + $mediaTableMigration = require __DIR__.'/../database/migrations/create_media_table.php.stub'; $mediaTableMigration->up(); } diff --git a/tests/TestSupport/TestImageGenerator.php b/tests/TestSupport/TestImageGenerator.php index 5d3dbee3f..7506efaf6 100644 --- a/tests/TestSupport/TestImageGenerator.php +++ b/tests/TestSupport/TestImageGenerator.php @@ -36,7 +36,7 @@ public function shouldMatchBothExtensionsAndMimeTypes(): bool return $this->shouldMatchBothExtensionsAndMimeTypes; } - public function convert(string $path, Conversion $conversion = null): string + public function convert(string $path, ?Conversion $conversion = null): string { return $path; } diff --git a/tests/TestSupport/TestImageGeneratorWithConfig.php b/tests/TestSupport/TestImageGeneratorWithConfig.php index 365223b8c..f24d7c898 100644 --- a/tests/TestSupport/TestImageGeneratorWithConfig.php +++ b/tests/TestSupport/TestImageGeneratorWithConfig.php @@ -14,7 +14,7 @@ public function __construct( ) { } - public function convert(string $file, Conversion $conversion = null): string + public function convert(string $file, ?Conversion $conversion = null): string { // TODO: Implement convert() method. } diff --git a/tests/TestSupport/TestModels/TestModelWithConversion.php b/tests/TestSupport/TestModels/TestModelWithConversion.php index 098fbd8b9..a3f1a3ec9 100644 --- a/tests/TestSupport/TestModels/TestModelWithConversion.php +++ b/tests/TestSupport/TestModels/TestModelWithConversion.php @@ -6,13 +6,16 @@ class TestModelWithConversion extends TestModel { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { - $this->addMediaConversion('thumb') + $this + ->addMediaConversion('thumb') ->width(50) + ->height(50) ->nonQueued(); - $this->addMediaConversion('keep_original_format') + $this + ->addMediaConversion('keep_original_format') ->keepOriginalImageFormat() ->nonQueued(); } diff --git a/tests/TestSupport/TestModels/TestModelWithConversionQueued.php b/tests/TestSupport/TestModels/TestModelWithConversionQueued.php index 18a28688d..22ae334a9 100644 --- a/tests/TestSupport/TestModels/TestModelWithConversionQueued.php +++ b/tests/TestSupport/TestModels/TestModelWithConversionQueued.php @@ -6,16 +6,19 @@ class TestModelWithConversionQueued extends TestModel { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { - $this->addMediaConversion('thumb') + $this + ->addMediaConversion('thumb') ->width(50); - $this->addMediaConversion('avatar_thumb') + $this + ->addMediaConversion('avatar_thumb') ->performOnCollections('avatar') ->width(50); - $this->addMediaConversion('keep_original_format') + $this + ->addMediaConversion('keep_original_format') ->keepOriginalImageFormat(); } } diff --git a/tests/TestSupport/TestModels/TestModelWithConversionUsingModelInstance.php b/tests/TestSupport/TestModels/TestModelWithConversionUsingModelInstance.php index 99ac28dbd..1b52b5210 100644 --- a/tests/TestSupport/TestModels/TestModelWithConversionUsingModelInstance.php +++ b/tests/TestSupport/TestModels/TestModelWithConversionUsingModelInstance.php @@ -8,7 +8,7 @@ class TestModelWithConversionUsingModelInstance extends TestModelWithConversion { public $registerMediaConversionsUsingModelInstance = true; - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { $this ->addMediaConversion('lazy-conversion') diff --git a/tests/TestSupport/TestModels/TestModelWithConversionsOnOtherDisk.php b/tests/TestSupport/TestModels/TestModelWithConversionsOnOtherDisk.php index 91d6da063..ba8d36d92 100644 --- a/tests/TestSupport/TestModels/TestModelWithConversionsOnOtherDisk.php +++ b/tests/TestSupport/TestModels/TestModelWithConversionsOnOtherDisk.php @@ -6,9 +6,10 @@ class TestModelWithConversionsOnOtherDisk extends TestModel { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { - $this->addMediaConversion('thumb') + $this + ->addMediaConversion('thumb') ->withResponsiveImages() ->width(50) ->nonQueued(); diff --git a/tests/TestSupport/TestModels/TestModelWithCustomLoadingAttribute.php b/tests/TestSupport/TestModels/TestModelWithCustomLoadingAttribute.php index 984e9b701..cf370844c 100644 --- a/tests/TestSupport/TestModels/TestModelWithCustomLoadingAttribute.php +++ b/tests/TestSupport/TestModels/TestModelWithCustomLoadingAttribute.php @@ -6,7 +6,7 @@ class TestModelWithCustomLoadingAttribute extends TestModelWithConversion { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { $this ->addMediaConversion('lazy-conversion') diff --git a/tests/TestSupport/TestModels/TestModelWithMultipleConversions.php b/tests/TestSupport/TestModels/TestModelWithMultipleConversions.php index 9934bd45e..bea0def9d 100644 --- a/tests/TestSupport/TestModels/TestModelWithMultipleConversions.php +++ b/tests/TestSupport/TestModels/TestModelWithMultipleConversions.php @@ -6,17 +6,20 @@ class TestModelWithMultipleConversions extends TestModel { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { - $this->addMediaConversion('small') + $this + ->addMediaConversion('small') ->width(50) ->nonQueued(); - $this->addMediaConversion('medium') + $this + ->addMediaConversion('medium') ->width(100) ->nonQueued(); - $this->addMediaConversion('large') + $this + ->addMediaConversion('large') ->width(200) ->nonQueued(); } diff --git a/tests/TestSupport/TestModels/TestModelWithPreviewConversion.php b/tests/TestSupport/TestModels/TestModelWithPreviewConversion.php index 261ca7748..9fe1a00c0 100644 --- a/tests/TestSupport/TestModels/TestModelWithPreviewConversion.php +++ b/tests/TestSupport/TestModels/TestModelWithPreviewConversion.php @@ -2,15 +2,16 @@ namespace Spatie\MediaLibrary\Tests\TestSupport\TestModels; -use Spatie\Image\Manipulations; +use Spatie\Image\Enums\Fit; use Spatie\MediaLibrary\MediaCollections\Models\Media; class TestModelWithPreviewConversion extends TestModel { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { - $this->addMediaConversion('preview') - ->fit(Manipulations::FIT_CROP, 300, 300) + $this + ->addMediaConversion('preview') + ->fit(Fit::Contain, 300, 300) ->nonQueued(); } } diff --git a/tests/TestSupport/TestModels/TestModelWithResponsiveImages.php b/tests/TestSupport/TestModels/TestModelWithResponsiveImages.php index 177e7c8d1..40e574db8 100644 --- a/tests/TestSupport/TestModels/TestModelWithResponsiveImages.php +++ b/tests/TestSupport/TestModels/TestModelWithResponsiveImages.php @@ -2,35 +2,39 @@ namespace Spatie\MediaLibrary\Tests\TestSupport\TestModels; -use Spatie\Image\Manipulations; use Spatie\MediaLibrary\MediaCollections\Models\Media; class TestModelWithResponsiveImages extends TestModel { - public function registerMediaConversions(Media $media = null): void + public function registerMediaConversions(?Media $media = null): void { - $this->addMediaConversion('thumb') + $this + ->addMediaConversion('thumb') ->withResponsiveImages() ->width(50) ->nonQueued(); - $this->addMediaConversion('otherImageConversion') + $this + ->addMediaConversion('otherImageConversion') ->greyscale(); - $this->addMediaConversion('pngtojpg') + $this + ->addMediaConversion('pngtojpg') ->width(700) ->quality(1) - ->background('blue') - ->format(Manipulations::FORMAT_JPG) + ->background('#ff00ff') + ->format('jpg') ->withResponsiveImages(); - $this->addMediaConversion('lowerQuality') - ->withResponsiveImages() - ->quality(60) - ->nonQueued(); + $this + ->addMediaConversion('lowerQuality') + ->withResponsiveImages() + ->quality(60) + ->nonQueued(); - $this->addMediaConversion('standardQuality') - ->withResponsiveImages() - ->nonQueued(); + $this + ->addMediaConversion('standardQuality') + ->withResponsiveImages() + ->nonQueued(); } } diff --git a/tests/TestSupport/TestModels/TestModelWithoutMediaConversions.php b/tests/TestSupport/TestModels/TestModelWithoutMediaConversions.php index 8ca2c3069..20e82cd8d 100644 --- a/tests/TestSupport/TestModels/TestModelWithoutMediaConversions.php +++ b/tests/TestSupport/TestModels/TestModelWithoutMediaConversions.php @@ -11,6 +11,8 @@ class TestModelWithoutMediaConversions extends Model implements HasMedia use InteractsWithMedia; protected $table = 'test_models'; + protected $guarded = []; + public $timestamps = false; }