Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 10 additions & 36 deletions .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
29 changes: 29 additions & 0 deletions doc/data-loader/asset_mapper.rst
Original file line number Diff line number Diff line change
@@ -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.
202 changes: 202 additions & 0 deletions doc/events.rst
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -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)<.+>\.$#'
61 changes: 61 additions & 0 deletions src/Binary/Locator/AssetMapperLocator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

/*
* This file is part of the `liip/LiipImagineBundle` project.
*
* (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/

namespace Liip\ImagineBundle\Binary\Locator;

use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
use Symfony\Component\AssetMapper\AssetMapperInterface;

/**
* Resolves asset paths using the Symfony AssetMapper component.
*
* In a development environment, AssetMapper serves assets from their source directories (typically `/assets`)
* without versioning. However, Twig's `asset()` helper generates public paths that include version hashes.
* Since these versioned files do not physically exist on disk during development, this locator is used
* to map the requested public versioned path back to the actual source file on the filesystem.
*
* In production, AssetMapper compiles and copies assets to the public directory with their version hashes
* included in the filenames. Consequently, this locator is no longer necessary as the files exist at
* their versioned paths.
*/
class AssetMapperLocator implements LocatorInterface
{
public function __construct(
private AssetMapperInterface $assetMapper,
) {
}

/**
* Locates the physical source file for a given public asset path.
*
* This method iterates through all registered assets in the AssetMapper to find a match
* for the provided public path (which may contain a version hash). If a match is found,
* it returns the absolute path to the original source file.
*
* Inspired by Symfony's AssetMapper component @see https://github.com/symfony/asset-mapper/blob/7.3/AssetMapperDevServerSubscriber.php#L179.
*
* @param string $path the public path of the asset (e.g., as generated by Twig's asset() helper)
*
* @throws NotLoadableException if the public path cannot be resolved to a source asset
*
* @return string the absolute path to the source asset file
*/
public function locate(string $path): string
{
$path = '/'.mb_ltrim($path, '/');
foreach ($this->assetMapper->allAssets() as $assetCandidate) {
if ($path === $assetCandidate->publicPath) {
return $assetCandidate->sourcePath;
}
}
throw new NotLoadableException(\sprintf('Asset with public path "%s" not found.', $path));
}
}
Loading
Loading