Skip to content

[LazyImage] Abstract image content fetching #1781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 26, 2024
Merged
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
32 changes: 31 additions & 1 deletion src/LazyImage/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,38 @@ blurred, data-uri thumbnail of the image:

The ``data_uri_thumbnail`` function receives 3 arguments:

- the server path to the image to generate the data-uri thumbnail for ;
- the path to the image to generate the data-uri thumbnail for ;
- the width of the BlurHash to generate
- the height of the BlurHash to generate

Customizing images fetching
~~~~~~~~~~~~~~~~~~~~~~~~~~~

By default, ``data_uri_thumbnail`` fetches images using the `file_get_contents`_ function.
It works well for local files, but you may want to customize it to fetch images from a remote server, `Flysystem`_, etc.

To do so you can create a invokable class, the first argument is the filename to fetch:

.. ::

namespace App\BlurHash;

class FetchImageContent
{
public function __invoke(string $filename): string
{
// Your custom implementation here to fetch the image content
}
}

Then you must configure the service in your Symfony configuration:

.. code-block:: yaml

# config/packages/lazy_image.yaml
lazy_image:
fetch_image_content: 'App\BlurHash\FetchImageContent'

Performance considerations
~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down Expand Up @@ -190,3 +218,5 @@ https://symfony.com/doc/current/contributing/code/bc.html
.. _`BlurHash implementation`: https://blurha.sh
.. _`StimulusBundle`: https://symfony.com/bundles/StimulusBundle/current/index.html
.. _StimulusBundle configured in your app: https://symfony.com/bundles/StimulusBundle/current/index.html
.. _`file_get_contents`: https://www.php.net/manual/en/function.file-get-contents.php
.. _`Flysystem`: https://flysystem.thephpleague.com
13 changes: 11 additions & 2 deletions src/LazyImage/src/BlurHash/BlurHash.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,17 @@
*/
class BlurHash implements BlurHashInterface
{
private \Closure $fetchImageContent;

/**
* @param (callable(string): string)|null $fetchImageContent
*/
public function __construct(
private ?ImageManager $imageManager = null,
private ?CacheInterface $cache = null,
?callable $fetchImageContent = null,
) {
$this->fetchImageContent = $fetchImageContent ? $fetchImageContent(...) : file_get_contents(...);
}

public static function intervention3(): bool
Expand Down Expand Up @@ -74,8 +81,10 @@ private function doEncode(string $filename, int $encodingWidth = 75, int $encodi

private function generatePixels(string $filename, int $encodingWidth, int $encodingHeight): array
{
$imageContent = ($this->fetchImageContent)($filename);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe just a quick check on the result ?


if (self::intervention3()) {
$image = $this->imageManager->read($filename)->scale($encodingWidth, $encodingHeight);
$image = $this->imageManager->read($imageContent)->scale($encodingWidth, $encodingHeight);
$width = $image->width();
$height = $image->height();
$pixels = [];
Expand All @@ -93,7 +102,7 @@ private function generatePixels(string $filename, int $encodingWidth, int $encod
}

// Resize image to increase encoding performance
$image = $this->imageManager->make(file_get_contents($filename));
$image = $this->imageManager->make($imageContent);
$image->resize($encodingWidth, $encodingHeight, static function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
Expand Down
1 change: 1 addition & 0 deletions src/LazyImage/src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public function getConfigTreeBuilder(): TreeBuilder
$rootNode
->children()
->scalarNode('cache')->end()
->scalarNode('fetch_image_content')->defaultNull()->end()
->end()
;

Expand Down
13 changes: 12 additions & 1 deletion src/LazyImage/src/DependencyInjection/LazyImageExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ public function load(array $configs, ContainerBuilder $container)

$container
->setDefinition('lazy_image.blur_hash', new Definition(BlurHash::class))
->setArgument(0, new Reference('lazy_image.image_manager', ContainerInterface::NULL_ON_INVALID_REFERENCE))
->setArguments([
new Reference('lazy_image.image_manager', ContainerInterface::NULL_ON_INVALID_REFERENCE),
null, // $cache
null, // $fetchImageContent
])
Comment on lines +49 to +53
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like I can't set the 3rd argument if the 2nd argument has not been set, which can be the case if we have no cache configured, that's why I've changed to ->setArguments

;

if (isset($config['cache'])) {
Expand All @@ -56,6 +60,13 @@ public function load(array $configs, ContainerBuilder $container)
;
}

if (isset($config['fetch_image_content'])) {
$container
->getDefinition('lazy_image.blur_hash')
->setArgument(2, new Reference($config['fetch_image_content']))
;
}

$container->setAlias(BlurHashInterface::class, 'lazy_image.blur_hash')->setPublic(false);

$container
Expand Down
41 changes: 41 additions & 0 deletions src/LazyImage/tests/BlurHash/BlurHashTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\UX\LazyImage\BlurHash\BlurHash;
use Symfony\UX\LazyImage\BlurHash\BlurHashInterface;
use Symfony\UX\LazyImage\Tests\Fixtures\BlurHash\LoggedFetchImageContent;
use Symfony\UX\LazyImage\Tests\Kernel\TwigAppKernel;

/**
Expand All @@ -42,6 +44,45 @@ public function testEncode()
);
}

public function testWithCustomGetImageContent(): void
{
$kernel = new class('test', true) extends TwigAppKernel {
public function registerContainerConfiguration(LoaderInterface $loader)
{
parent::registerContainerConfiguration($loader);

$loader->load(static function (ContainerBuilder $container) {
$container->loadFromExtension('lazy_image', [
'fetch_image_content' => 'logged_get_image_content',
]);

$container
->setDefinition('logged_get_image_content', new Definition(LoggedFetchImageContent::class))
->setPublic('true')
;
});
}
};

$kernel->boot();
$container = $kernel->getContainer()->get('test.service_container');

/** @var BlurHashInterface $blurHash */
$blurHash = $container->get('test.lazy_image.blur_hash');

$loggedGetImageContent = $container->get('logged_get_image_content');
$this->assertInstanceOf(LoggedFetchImageContent::class, $loggedGetImageContent);
$this->assertEmpty($loggedGetImageContent->logs);

$this->assertSame(
BlurHash::intervention3() ? 'LnMtaO9FD%IU%MRjayRj~qIUM{of' : 'L54ec*~q_3?bofoffQWB9F9FD%IU',
$blurHash->encode(__DIR__.'/../Fixtures/logo.png')
);

$this->assertCount(1, $loggedGetImageContent->logs);
$this->assertSame(__DIR__.'/../Fixtures/logo.png', $loggedGetImageContent->logs[0]);
}

public function testEnsureCacheIsNotUsedWhenNotConfigured()
{
$kernel = new TwigAppKernel('test', true);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Symfony\UX\LazyImage\Tests\Fixtures\BlurHash;

final class LoggedFetchImageContent
{
public array $logs = [];

public function __invoke(string $filename): string
{
$this->logs[] = $filename;

return file_get_contents($filename);
}
}