diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml index 082e33a6d..795a7b94b 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/phpunit.yml @@ -15,7 +15,7 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.1', '8.2', '8.3'] + php: ['8.1', '8.2', '8.3', '8.4', '8.5'] dependencies: [highest] symfony: ['*'] include: @@ -33,18 +33,12 @@ jobs: - php: '8.1' dependencies: highest symfony: '6.4.*' - - php: '8.2' dependencies: highest - symfony: '7.0.*' - - - php: '8.3' - dependencies: highest - symfony: '7.0.*' - + symfony: '7.4.*' - php: '8.4' dependencies: highest - symfony: '8.0.*' + symfony: '8.*' steps: - name: Checkout @@ -65,18 +59,21 @@ jobs: run: | composer global config --no-plugins allow-plugins.symfony/flex true composer global require --no-interaction --no-progress symfony/flex - composer config extra.symfony.require ${{ matrix.symfony }} - - name: Set minimum-stability - run: composer config minimum-stability ${{ matrix.stability }} + - name: Add asset mapper + # asset mapper support is optional in LiipImagineBundle. asset mapper was only added in Symfony 6 + if: ${{ matrix.symfony >= '6.4' }} + run: composer require --no-update symfony/asset-mapper --dev - name: Update project dependencies uses: ramsey/composer-install@v2 with: dependency-versions: ${{ matrix.dependencies }} + env: + SYMFONY_REQUIRE: "${{ matrix.symfony }}" - name: Lint container - run: ./Tests/Functional/app/bin/console lint:container + run: ./tests/Functional/app/bin/console lint:container - name: Cache PHPUnit uses: actions/cache@v3 @@ -92,26 +89,3 @@ jobs: SYMFONY_DEPRECATIONS_HELPER: max[self]=0 run: vendor/bin/simple-phpunit -v - - name: Install php-coveralls - run: composer global require --no-interaction --no-progress php-coveralls/php-coveralls - - - name: Upload coverage results to Coveralls - uses: nick-invision/retry@v2 - env: - COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} - COVERALLS_PARALLEL: true - COVERALLS_FLAG_NAME: "PHP ${{ matrix.php }} + ${{ matrix.dependencies }} dependencies + Symfony ${{ matrix.symfony }}" - with: - timeout_seconds: 60 - max_attempts: 3 - command: php-coveralls -x var/build/clover.xml -o var/build/upload.json -v - - coveralls-finish: - needs: [phpunit] - runs-on: ubuntu-latest - steps: - - name: Notify Coveralls when build is finished - uses: coverallsapp/github-action@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - parallel-finished: true diff --git a/composer.json b/composer.json index 71f0de884..07c98addb 100644 --- a/composer.json +++ b/composer.json @@ -32,6 +32,7 @@ "symfony/framework-bundle": "^6.4|^7.3|^8.0", "symfony/mime": "^6.4|^7.3|^8.0", "symfony/options-resolver": "^6.4|^7.3|^8.0", + "symfony/polyfill-mbstring": "^1.31", "symfony/process": "^6.4|^7.3|^8.0", "twig/twig": "^2.9|^3.0" }, diff --git a/doc/data-loader/asset_mapper.rst b/doc/data-loader/asset_mapper.rst new file mode 100644 index 000000000..4f04917cc --- /dev/null +++ b/doc/data-loader/asset_mapper.rst @@ -0,0 +1,29 @@ + +.. _data-loaders-asset-mapper: + +Asset Mapper Loader (for dev) +============================= + +The ``AssetMapper`` data loader allows for loading images using Symfony's AssetMapper component. + +Configuration +------------- + +To enable the Asset Mapper loader, you need to configure it in your loaders section. +A common use case is to use it in combination with the default filesystem loader using a chain loader, +especially in development environment. + +.. code-block:: yaml + + # config/packages/liip_imagine.yaml + when@dev: + liip_imagine: + loaders: + asset_mapper: + asset_mapper: ~ + chain: + chain: + loaders: [ asset_mapper, default ] + data_loader: chain + +This configuration creates an ``asset_mapper`` loader and a ``chain`` loader that first tries to find the asset via AssetMapper, and then falls back to the ``default`` loader. Finally, it sets the global ``data_loader`` to use this new ``chain`` loader. diff --git a/doc/events.rst b/doc/events.rst new file mode 100644 index 000000000..fb5d56877 --- /dev/null +++ b/doc/events.rst @@ -0,0 +1,202 @@ + + +Events +====== + +The bundle dispatches the following events around the cache lifecycle: + +* ``PRE_RESOLVE`` and ``POST_RESOLVE``, both receiving a CacheResolveEvent. +* ``PRE_STORE`` and ``POST_STORE``, both receiving a CacheStoreEvent. +* ``PRE_REMOVE`` and ``POST_REMOVE``, both receiving a CacheRemoveEvent. +* ``PRE_FILTER`` and ``POST_FILTER``, both receiving a FilterEvent. +* ``PRE_POST_PROCESSOR`` and ``POST_POST_PROCESSOR``, both receiving a FilterEvent. + +PRE_RESOLVE +----------- + +Called before url to the cached filtered image is generated. + + +POST_RESOLVE +------------ + +Called after url to the cached filtered image is generated. + +PRE_STORE +--------- + +Called before the filtered image is handed over to its cache resolver. The +CacheStoreEvent gives access to the binary about to be stored, the path it is +stored under, the filter name and the resolver name that was passed to the +cache manager - the latter being ``null`` when the filter default is used. + +POST_STORE +---------- + +Called after the filtered image has been handed over to its cache resolver, +for example to inspect the image that was just written. + +PRE_REMOVE +---------- + +Called before cached images are removed from their cache resolvers. The +CacheRemoveEvent gives access to the paths and the filter names the removal +applies to. An empty list of paths means every cached path of those filters is +removed. With ``webp_generate`` enabled, the paths also contain the ``.webp`` +companion of every removed path. + +POST_REMOVE +----------- + +Called after the cached images have been removed from their cache resolvers. + +PRE_FILTER and POST_FILTER +-------------------------- + +Called immediately before and after each configured image filter runs. The +FilterEvent exposes the filter name and its configured options. These events +are informational and cannot change the filter operation. + +PRE_POST_PROCESSOR and POST_POST_PROCESSOR +------------------------------------------ + +Called immediately before and after each configured post-processor runs. The +FilterEvent exposes the post-processor name and its configured options. These +events are informational and cannot change the post-processing operation. + +Example: Signed URLs +-------------------- +Here is an implementation example about users media with differents filters and an S3 as IONOS. At the end we will update the url to get a temporary signed url to a private resource: + +First, we need to configure the adapters and the filesystem where will be loaded the images. Normally no need to configure where the cached images will be stored, but we will need it in the next step to generate a signed url. + +.. code-block:: yaml + #oneup_flysystem.yaml + + oneup_flysystem: + adapters: + # Original image addapter + user_adapter: + awss3v3: + client: Aws\S3\S3Client + bucket: '%env(IONOS_S3_BUCKET_NAME)%' + prefix: "users" # Original image location + + # One adapter per filter and the location of the generated images, with the cache_prefix + user_thumbnail_adapter: + awss3v3: + client: Aws\S3\S3Client + bucket: '%env(IONOS_S3_BUCKET_NAME)%' + prefix: "cache/user_thumbnail" + user_medium_adapter: + awss3v3: + client: Aws\S3\S3Client + bucket: '%env(IONOS_S3_BUCKET_NAME)%' + prefix: "cache/user_medium" + + filesystems: + user: + adapter: user_adapter + mount: user + userThumbnail: + adapter: user_thumbnail_adapter + mount: userThumbnail + userMedium: + adapter: user_medium_adapter + mount: userMedium + +To get a cached resource as private we need to configure the acl of the resolver to private, or the generated image will be in public, it's not what we want in this example. + +.. code-block:: yaml + liip_imagine: + driver: "gd" + loaders: + user_loader: + flysystem: + filesystem_service: oneup_flysystem.user_filesystem + + resolvers: + aws_s3_resolver: + aws_s3: + bucket: '%env(IONOS_S3_BUCKET_NAME)%' + client_config: + credentials: + key: '%env(IONOS_S3_ACCESS_ID)%' + secret: '%env(IONOS_S3_ACCESS_SECRET)%' + endpoint: '%env(IONOS_S3_ENDPOINT)%' + region: '%env(IONOS_S3_REGION)%' + version: '%env(IONOS_S3_VERSION)%' + acl: private + cache_prefix: cache + + get_options: + Scheme: 'https' + put_options: + CacheControl: 'max-age=86400' + cache: aws_s3_resolver + filter_sets: + cache: ~ + user_thumbnail: + cache: aws_s3_resolver + quality: 75 + filters: + thumbnail: { size: [ 130, 130 ], mode: outbound } + data_loader: user_loader + user_medium: + cache: aws_s3_resolver + quality: 75 + filters: + thumbnail: { size: [ 302, 180 ], mode: outbound } + data_loader: user_loader + +Finally we create a post resolve subscriber to update the url to the private resource location. + +.. code-block:: php + + namespace App\EventSubscriber; + + use App\Enum\MediaFilterEnum; + use App\Repository\MediaRepository; + use League\Flysystem\FilesystemOperator; + use Liip\ImagineBundle\Events\CacheResolveEvent; + use Symfony\Component\EventDispatcher\EventSubscriberInterface; + + class LiipImagineFilterSubscriber implements EventSubscriberInterface + { + public function __construct( + private readonly FilesystemOperator $userThumbnailFilesystem, + private readonly FilesystemOperator $userMediumFilesystem + ) + { + } + + public function onPostResolve(CacheResolveEvent $event): void + { + $path = $event->getPath(); + $filter = $event->getFilter(); + + $date = new \DateTime(); + // We set the expiration in 10 minutes for example. + $date = $date->add(new \DateInterval('PT10M')); + + if ($filter === MediaFilterEnum::USER_THUMBNAIL->value) { + $url = $this->userThumbnailFilesystem->temporaryUrl($path, $date); + } + else if ($filter === MediaFilterEnum::USER_MEDIUM->value) { + $url = $this->userMediumFilesystem->temporaryUrl($path, $date); + } + + if (isset($url)) { + $event->setUrl($url); + } + } + + public static function getSubscribedEvents(): array + { + return [ + 'liip_imagine.post_resolve' => 'onPostResolve' + ]; + } + } + +Now, you will get a proper signed url to get your private resource. diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 5c96010a6..21e686a4a 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -16,3 +16,6 @@ parameters: # Depending on aws sdk version, this method has 2 or 4 parameters. The extra parameters will just be ignored. # https://github.com/liip/LiipImagineBundle/issues/1457 - '#^Method Aws\\S3\\S3Client::getObjectUrl\(\) invoked with 4 parameters, 2 required\.$#' + # phpstan-symfony 1.x does not understand the generic NodeBuilder/ExprBuilder types of symfony/config 7.4+. + # The errors are gone with phpstan 2 and phpstan-symfony 2. + - '#^Call to method [a-zA-Z]+\(\) on an unknown class Symfony\\Component\\Config\\Definition\\Builder\\(NodeBuilder|ExprBuilder)<.+>\.$#' diff --git a/src/Binary/Locator/AssetMapperLocator.php b/src/Binary/Locator/AssetMapperLocator.php new file mode 100644 index 000000000..20d3418e0 --- /dev/null +++ b/src/Binary/Locator/AssetMapperLocator.php @@ -0,0 +1,61 @@ +assetMapper->allAssets() as $assetCandidate) { + if ($path === $assetCandidate->publicPath) { + return $assetCandidate->sourcePath; + } + } + throw new NotLoadableException(\sprintf('Asset with public path "%s" not found.', $path)); + } +} diff --git a/src/DependencyInjection/Factory/Loader/AssetMapperLoaderFactory.php b/src/DependencyInjection/Factory/Loader/AssetMapperLoaderFactory.php new file mode 100644 index 000000000..fd5c1ce99 --- /dev/null +++ b/src/DependencyInjection/Factory/Loader/AssetMapperLoaderFactory.php @@ -0,0 +1,46 @@ + $config + */ + public function create(ContainerBuilder $container, string $name, array $config): string + { + $locatorDefinition = new ChildDefinition('liip_imagine.binary.locator.asset_mapper'); + $locatorDefinition->replaceArgument(0, new Reference('asset_mapper')); + + $definition = $this->getChildLoaderDefinition('filesystem'); + $definition->replaceArgument(2, $locatorDefinition); + + return $this->setTaggedLoaderDefinition($name, $definition, $container); + } + + public function getName(): string + { + return 'asset_mapper'; + } + + public function addConfiguration(ArrayNodeDefinition $builder): void + { + $builder + ->children() + ->end(); + } +} diff --git a/src/Imagine/Cache/Resolver/AwsS3Resolver.php b/src/Imagine/Cache/Resolver/AwsS3Resolver.php index 59f01f528..6d44228b0 100644 --- a/src/Imagine/Cache/Resolver/AwsS3Resolver.php +++ b/src/Imagine/Cache/Resolver/AwsS3Resolver.php @@ -48,7 +48,7 @@ public function __construct(S3Client $storage, string $bucket, string $acl = 'pu { $this->storage = $storage; $this->bucket = $bucket; - $this->acl = $acl ?? ''; + $this->acl = $acl; $this->getOptions = $getOptions; $this->putOptions = $putOptions; } diff --git a/src/Resources/config/imagine.php b/src/Resources/config/imagine.php index 4af23d4b3..ef6a8c815 100644 --- a/src/Resources/config/imagine.php +++ b/src/Resources/config/imagine.php @@ -52,7 +52,6 @@ use Liip\ImagineBundle\Form\Type\ImageType; use Liip\ImagineBundle\Imagine\Cache\CacheManager; use Liip\ImagineBundle\Imagine\Cache\Resolver\AwsS3Resolver; -use Liip\ImagineBundle\Imagine\Cache\Resolver\CacheResolver; use Liip\ImagineBundle\Imagine\Cache\Resolver\FlysystemResolver; use Liip\ImagineBundle\Imagine\Cache\Resolver\FlysystemV2Resolver; use Liip\ImagineBundle\Imagine\Cache\Resolver\NoCacheWebPathResolver; @@ -87,6 +86,9 @@ use Liip\ImagineBundle\Imagine\Filter\PostProcessor\OptiPngPostProcessor; use Liip\ImagineBundle\Imagine\Filter\PostProcessor\PngquantPostProcessor; use Liip\ImagineBundle\Service\FilterService; +use Symfony\Component\Mime\MimeTypeGuesserInterface; +use Symfony\Component\Mime\MimeTypes; +use Symfony\Component\Mime\MimeTypesInterface; return static function (ContainerConfigurator $container) { $services = $container->services(); @@ -325,22 +327,6 @@ ]) ->tag('liip_imagine.filter.loader', ['loader' => 'paste_image']); - // not officially deprecated because still injected and appears "used" - $services->set('liip_imagine.filter.loader.paste', PasteFilterLoader::class) - ->args([ - service('liip_imagine'), - '%kernel.root_dir%', - ]) - ->tag('liip_imagine.filter.loader', ['loader' => 'paste']); - - // not officially deprecated because still injected and appears "used" - $services->set('liip_imagine.filter.loader.watermark', WatermarkFilterLoader::class) - ->args([ - service('liip_imagine'), - '%kernel.root_dir%', - ]) - ->tag('liip_imagine.filter.loader', ['loader' => 'watermark']); - $services->set('liip_imagine.filter.loader.watermark_image', WatermarkFilterLoader::class) ->args([ service('liip_imagine'), @@ -469,15 +455,6 @@ '', // will be injected by AwsS3ResolverFactory ]); - $services->set('liip_imagine.cache.resolver.prototype.cache', CacheResolver::class) - ->public() - ->abstract() - ->args([ - // args will be injected by a ResolverFactory - '', - '', - ]); - $services->set('liip_imagine.cache.resolver.prototype.flysystem', FlysystemResolver::class) ->public() ->abstract() @@ -526,11 +503,11 @@ ->tag('form.type', ['alias' => 'liip_imagine_image']); // Guessers - $services->set('liip_imagine.mime_type_guesser', 'Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface') - ->factory(['Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser', 'getInstance']); + $services->set('liip_imagine.mime_type_guesser', MimeTypeGuesserInterface::class) + ->factory([MimeTypes::class, 'getDefault']); - $services->set('liip_imagine.extension_guesser', 'Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface') - ->factory(['Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser', 'getInstance']); + $services->set('liip_imagine.extension_guesser', MimeTypesInterface::class) + ->factory([MimeTypes::class, 'getDefault']); $services->set('liip_imagine.binary.mime_type_guesser', SimpleMimeTypeGuesser::class) ->args([service('liip_imagine.mime_type_guesser')]); diff --git a/tests/AbstractTest.php b/tests/AbstractTest.php index 86d607bf9..81fe44c30 100644 --- a/tests/AbstractTest.php +++ b/tests/AbstractTest.php @@ -50,9 +50,6 @@ protected function getVisibilityRestrictedMethod(object $object, string $name): { $r = new \ReflectionObject($object); - $m = $r->getMethod($name); - $m->setAccessible(true); - - return $m; + return $r->getMethod($name); } } diff --git a/tests/Binary/Locator/AssetMapperLocatorTest.php b/tests/Binary/Locator/AssetMapperLocatorTest.php new file mode 100644 index 000000000..3c755b19a --- /dev/null +++ b/tests/Binary/Locator/AssetMapperLocatorTest.php @@ -0,0 +1,75 @@ +markTestSkipped('symfony/asset-mapper is required for this test.'); + } + } + + public function testImplementsLocatorInterface(): void + { + $assetMapper = $this->createMock(AssetMapperInterface::class); + $this->assertInstanceOf(LocatorInterface::class, new AssetMapperLocator($assetMapper)); + } + + public function testLocateWithoutCache(): void + { + $path = 'images/logo.png'; + $pathInfo = '/images/logo.png'; + $sourcePath = '/path/to/logo.png'; + $logicalPath = 'logo.png'; + + $asset = new MappedAsset($logicalPath, $sourcePath, $pathInfo, $pathInfo); + + $assetMapper = $this->createMock(AssetMapperInterface::class); + $assetMapper->expects($this->once()) + ->method('allAssets') + ->willReturn([$asset]); + + $locator = new AssetMapperLocator($assetMapper); + $result = $locator->locate($path); + + $this->assertSame($sourcePath, $result); + } + + public function testThrowsIfAssetNotFound(): void + { + $path = 'images/logo.png'; + + $assetMapper = $this->createMock(AssetMapperInterface::class); + $assetMapper->expects($this->once()) + ->method('allAssets') + ->willReturn([]); + + $locator = new AssetMapperLocator($assetMapper); + + $this->expectException(NotLoadableException::class); + $this->expectExceptionMessage('Asset with public path "/images/logo.png" not found.'); + + $locator->locate($path); + } +} diff --git a/tests/DependencyInjection/Factory/Loader/AssetMapperLoaderFactoryTest.php b/tests/DependencyInjection/Factory/Loader/AssetMapperLoaderFactoryTest.php new file mode 100644 index 000000000..9ac658da5 --- /dev/null +++ b/tests/DependencyInjection/Factory/Loader/AssetMapperLoaderFactoryTest.php @@ -0,0 +1,59 @@ + + */ +class AssetMapperLoaderFactoryTest extends FactoryTestCase +{ + protected function setUp(): void + { + if (!interface_exists(AssetMapperInterface::class)) { + $this->markTestSkipped('symfony/asset-mapper is required for this test.'); + } + } + + public function testImplementsLoaderFactoryInterface(): void + { + $this->assertInstanceOf(LoaderFactoryInterface::class, new AssetMapperLoaderFactory()); + } + + public function testReturnsExpectedName(): void + { + $this->assertSame('asset_mapper', (new AssetMapperLoaderFactory())->getName()); + } + + public function testCreateLoaderDefinition(): void + { + $container = new ContainerBuilder(); + + $loader = new AssetMapperLoaderFactory(); + $loader->create($container, 'the_loader_name', [ + ]); + + $this->assertTrue($container->hasDefinition('liip_imagine.binary.loader.the_loader_name')); + + /** @var ChildDefinition $loaderDefinition */ + $loaderDefinition = $container->getDefinition('liip_imagine.binary.loader.the_loader_name'); + + $this->assertInstanceOfChildDefinition($loaderDefinition); + $this->assertSame('liip_imagine.binary.loader.prototype.filesystem', $loaderDefinition->getParent()); + } +} diff --git a/tests/DependencyInjection/Factory/Resolver/AwsS3ResolverFactoryTest.php b/tests/DependencyInjection/Factory/Resolver/AwsS3ResolverFactoryTest.php index dd603929e..86917b29f 100644 --- a/tests/DependencyInjection/Factory/Resolver/AwsS3ResolverFactoryTest.php +++ b/tests/DependencyInjection/Factory/Resolver/AwsS3ResolverFactoryTest.php @@ -298,7 +298,7 @@ public function testThrowClientConfigNotArrayOnAddConfiguration(): void public function testThrowClientConfigAmbiguousOnAddConfiguration(): void { $this->expectException(\Symfony\Component\Config\Definition\Exception\InvalidConfigurationException::class); - $this->expectExceptionMessageMatchesBC('/Children config "client_id" and "client_config" cannot be configured at the same time./'); + $this->expectExceptionMessageMatches('/Children config "client_id" and "client_config" cannot be configured at the same time./'); $treeBuilder = new TreeBuilder('aws_s3'); $rootNode = $treeBuilder->getRootNode(); diff --git a/Tests/Functional/app/bin/console b/tests/Functional/app/bin/console similarity index 100% rename from Tests/Functional/app/bin/console rename to tests/Functional/app/bin/console