Skip to content

[Icons] Improve cache warmup by looking at every string #1594

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
Mar 10, 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
1 change: 1 addition & 0 deletions src/Icons/config/iconify.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

->set('.ux_icons.iconify', Iconify::class)
->args([
service('cache.system'),
abstract_arg('endpoint'),
service('http_client')->nullOnInvalid(),
])
Expand Down
16 changes: 16 additions & 0 deletions src/Icons/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,22 @@ In production, you can pre-warm the cache by running the following command:

This command looks in all your twig templates for ``ux_icon`` calls and caches the icons it finds.

.. caution::

Icons that have a name built dynamically will not be cached. It's advised to have the icon
name as a string literal in your templates.

.. code-block:: twig

{# This will be cached #}
{{ ux_icon('flag-fr') }}

{# This will NOT be cached #}
{{ ux_icon('flag-' ~ locale) }}

{% set flags = {fr: 'flag-fr', de: 'flag-de'} %} {# both "flag-fr" and "flag-de" will be cached #}
{{ ux_icon(flags[locale]) }}

.. note::

During development, if you modify an icon, you will need to clear the cache (``bin/console cache:clear``)
Expand Down
1 change: 0 additions & 1 deletion src/Icons/src/Command/WarmCacheCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$io->writeln(sprintf(' Warmed icon <comment>%s</comment>.', $name));
}
},
onFailure: fn (string $name) => $io->warning(sprintf('Icon <comment>%s</comment> not found.', $name))
);

$io->success('Icon cache warmed.');
Expand Down
2 changes: 1 addition & 1 deletion src/Icons/src/DependencyInjection/UXIconsExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ protected function loadInternal(array $mergedConfig, ContainerBuilder $container
$loader->load('iconify.php');

$container->getDefinition('.ux_icons.iconify')
->setArgument(0, $mergedConfig['iconify']['endpoint'])
->setArgument(1, $mergedConfig['iconify']['endpoint'])
;
}

Expand Down
24 changes: 21 additions & 3 deletions src/Icons/src/Iconify.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\HttpClient\Exception\JsonException;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\ScopingHttpClient;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\UX\Icons\Exception\IconNotFoundException;
use Symfony\UX\Icons\Svg\Icon;
Expand All @@ -26,8 +27,10 @@
final class Iconify
{
private HttpClientInterface $http;
private \ArrayObject $sets;

public function __construct(
private CacheInterface $cache,
string $endpoint = 'https://api.iconify.design',
?HttpClientInterface $http = null,
) {
Expand All @@ -40,13 +43,15 @@ public function __construct(

public function metadataFor(string $prefix): array
{
$response = $this->http->request('GET', sprintf('/collections?prefix=%s', $prefix));

return $response->toArray()[$prefix] ?? throw new \RuntimeException(sprintf('The icon prefix "%s" does not exist on iconify.design.', $prefix));
return $this->sets()[$prefix] ?? throw new \RuntimeException(sprintf('The icon prefix "%s" does not exist on iconify.design.', $prefix));
}

public function fetchIcon(string $prefix, string $name): Icon
{
if (!isset($this->sets()[$prefix])) {
throw new IconNotFoundException(sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name));
}

$response = $this->http->request('GET', sprintf('/%s.json?icons=%s', $prefix, $name));
Copy link
Member

Choose a reason for hiding this comment

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

If (i insist on if) this become the bottleneck, we have a card in hand: grouping icons per set https://iconify.design/docs/api/icon-data.html#query


try {
Expand All @@ -66,6 +71,10 @@ public function fetchIcon(string $prefix, string $name): Icon

public function fetchSvg(string $prefix, string $name): string
{
if (!isset($this->sets()[$prefix])) {
throw new IconNotFoundException(sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name));
}

$content = $this->http
->request('GET', sprintf('/%s/%s.svg', $prefix, $name))
->getContent()
Expand All @@ -77,4 +86,13 @@ public function fetchSvg(string $prefix, string $name): string

return $content;
}

private function sets(): \ArrayObject
{
return $this->sets ??= $this->cache->get('ux-iconify-sets', function () {
$response = $this->http->request('GET', '/collections');

return new \ArrayObject($response->toArray());
});
}
}
6 changes: 1 addition & 5 deletions src/Icons/src/Twig/IconFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ public function icons(): array
foreach ($this->files($this->twig->getLoader()) as $file) {
Copy link
Member

Choose a reason for hiding this comment

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

Should we exclude the Bundle ?

Copy link
Member Author

Choose a reason for hiding this comment

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

What bundle?

Copy link
Member

Choose a reason for hiding this comment

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

At this point, i think Twig loader has been registered with all the bundles of the app. So it contains all the files in "vendor/acme/*-bundle/Resources/templates" and we should (imho) not go there to extract things.

Imagine a twig file there with a list of icons (think any template using JS icons)... the probability to have 'bi:check' string is far from null.

We even could see this as a vector "attack", a single file in twig from a 3rd party bundle would make you downlaod icons locally / generate a lot of download.

Oh and i'll check something about that we may have a problem there.

So here i'd like us to only look in userland files :)

Copy link
Member Author

Choose a reason for hiding this comment

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

What if you had a bundle of that uses icons that you wanted to use? I prefer to keep it simple and adjust when/if we come across these type of problems.

$contents = file_get_contents($file);

if (preg_match_all('#ux_icon\(["\']([\w:-]+)["\']#', $contents, $matches)) {
$found[] = $matches[1];
}

if (preg_match_all('#name=["\']([\w:-]+)["\']#', $contents, $matches)) {
if (preg_match_all('#["\']([\w:-]+)["\']#', $contents, $matches)) {
$found[] = $matches[1];
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/Icons/tests/Fixtures/templates/template2.html.twig
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
{% set icon = 'flag:eu-4x3' %}

{{ ux_icon('something:invalid') }}
{{ ux_icon('invalid') }}
{{ ux_icon('iconamoon:invalid') }}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function testCanWarmCache(): void
->assertOutputContains('Warmed icon user.')
->assertOutputContains('Warmed icon sub:check.')
->assertOutputContains('Warmed icon iconamoon:3d-duotone.')
->assertOutputContains('Warmed icon flag:eu-4x3.')
->assertOutputContains('Icon cache warmed.')
;
}
Expand Down