Skip to content
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
5 changes: 2 additions & 3 deletions src/Icons/src/IconRegistryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\UX\Icons;

use Symfony\UX\Icons\Exception\IconNotFoundException;
use Symfony\UX\Icons\Svg\Icon;

/**
* @author Kevin Bond <kevinbond@gmail.com>
Expand All @@ -23,9 +24,7 @@
interface IconRegistryInterface extends \IteratorAggregate, \Countable
{
/**
* @return array{0: string, 1: array<string, string|bool>}
*
* @throws IconNotFoundException
*/
public function get(string $name): array;
public function get(string $name): Icon;
}
35 changes: 8 additions & 27 deletions src/Icons/src/IconRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,15 @@ public function __construct(
*/
public function renderIcon(string $name, array $attributes = []): string
{
[$content, $iconAttr] = $this->registry->get($name);
// TODO generate class name(s)
// TODO add role/aria

$iconAttr = array_merge($iconAttr, $this->defaultIconAttributes);
// TODO catch IconNotFoundException
// --> only possible if we add a new method to IconRegistryInterface

return sprintf(
'<svg%s>%s</svg>',
self::normalizeAttributes([...$iconAttr, ...$attributes]),
$content,
);
}

/**
* @param array<string,string|bool> $attributes
*/
private static function normalizeAttributes(array $attributes): string
{
return array_reduce(
array_keys($attributes),
static function (string $carry, string $key) use ($attributes) {
$value = $attributes[$key];

return match ($value) {
true => "{$carry} {$key}",
false => $carry,
default => sprintf('%s %s="%s"', $carry, $key, $value),
};
},
''
);
return $this->registry->get($name)
->withAttributes([...$this->defaultIconAttributes, ...$attributes])
->toHtml()
;
}
}
9 changes: 7 additions & 2 deletions src/Icons/src/Registry/CacheIconRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\UX\Icons\Exception\IconNotFoundException;
use Symfony\UX\Icons\IconRegistryInterface;
use Symfony\UX\Icons\Svg\Icon;

/**
* @author Kevin Bond <kevinbond@gmail.com>
Expand All @@ -30,10 +31,14 @@ public function __construct(private \Traversable $registries, private CacheInter
{
}

public function get(string $name, bool $refresh = false): array
public function get(string $name, bool $refresh = false): Icon
{
if (!Icon::isValidName($name)) {
throw new IconNotFoundException(sprintf('The icon name "%s" is not valid.', $name));
}

return $this->cache->get(
sprintf('ux-icon-%s', str_replace([':', '/'], ['-', '-'], $name)),
sprintf('ux-icon-%s', Icon::nameToId($name)),
function () use ($name) {
foreach ($this->registries as $registry) {
try {
Expand Down
19 changes: 14 additions & 5 deletions src/Icons/src/Registry/LocalSvgIconRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\Finder\Finder;
use Symfony\UX\Icons\Exception\IconNotFoundException;
use Symfony\UX\Icons\IconRegistryInterface;
use Symfony\UX\Icons\Svg\Icon;

/**
* @author Kevin Bond <kevinbond@gmail.com>
Expand All @@ -26,13 +27,18 @@ public function __construct(private string $iconDir)
{
}

public function get(string $name): array
public function get(string $name): Icon
{
if (!Icon::isValidName($name)) {
throw new IconNotFoundException(sprintf('The icon name "%s" is not valid.', $name));
}

if (!file_exists($filename = sprintf('%s/%s.svg', $this->iconDir, str_replace(':', '/', $name)))) {
throw new IconNotFoundException(sprintf('The icon "%s" (%s) does not exist.', $name, $filename));
}

$svg = file_get_contents($filename) ?: throw new \RuntimeException(sprintf('The icon file "%s" could not be read.', $filename));

$doc = new \DOMDocument();
$doc->preserveWhiteSpace = false;

Expand All @@ -54,24 +60,27 @@ public function get(string $name): array

$svgElement = $svgElements->item(0) ?? throw new \RuntimeException(sprintf('The icon file "%s" does not contain a valid SVG.', $filename));

$html = '';
$innerSvg = '';

foreach ($svgElement->childNodes as $child) {
$html .= $doc->saveHTML($child);
$innerSvg .= $doc->saveHTML($child);
}

if (!$html) {
if (!$innerSvg) {
throw new \RuntimeException(sprintf('The icon file "%s" contains an empty SVG.', $filename));
}

// @todo: save all attributes in the local object ?
// allow us to defer the decision of which attributes to keep or not

$allAttributes = array_map(fn (\DOMAttr $a) => $a->value, [...$svgElement->attributes]);
$attributes = [];

if (isset($allAttributes['viewBox'])) {
$attributes['viewBox'] = $allAttributes['viewBox'];
}

return [$html, $attributes];
return new Icon($innerSvg, $attributes);
}

public function getIterator(): \Traversable
Expand Down
185 changes: 185 additions & 0 deletions src/Icons/src/Svg/Icon.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
<?php

namespace Symfony\UX\Icons\Svg;

/**
*
* @author Simon André <smn.andre@gmail.com>
*
* @internal
*/
final class Icon implements \Stringable, \Serializable, \ArrayAccess
{
/**
* Transforms a valid icon ID into an icon name.
*
* @throws \InvalidArgumentException if the ID is not valid
* @see isValidId()
*/
public static function idToName(string $id): string
Copy link
Owner

Choose a reason for hiding this comment

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

we need to actually use these new methods now, right?

Copy link
Author

Choose a reason for hiding this comment

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

Of course, i try to do micro step by micro step because the rebase dance is not my first talent :)

Copy link
Author

Choose a reason for hiding this comment

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

Better now :)

{
if (!self::isValidId($id)) {
throw new \InvalidArgumentException(sprintf('The id "%s" is not a valid id.', $id));
}

return str_replace('--', ':', $id);
}

/**
* Transforms a valid icon name into an ID.
*
* @throws \InvalidArgumentException if the name is not valid
* @see isValidName()
*/
public static function nameToId(string $name): string
{
if (!self::isValidName($name)) {
throw new \InvalidArgumentException(sprintf('The name "%s" is not a valid name.', $name));
}

return str_replace(':', '--', $name);
}

/**
* Returns whether the given string is a valid icon ID.
*
* An icon ID is a string that contains only lowercase letters, numbers, and hyphens.
* It must be composed of slugs separated by double hyphens.
*
* @see https://regex101.com/r/mmvl5t/1
*/
public static function isValidId(string $id): bool
{
return (bool) preg_match('#^([a-z0-9]+(-[a-z0-9]+)*)(--[a-z0-9]+(-[a-z0-9]+)*)*$#', $id);
}

/**
* Returns whether the given string is a valid icon name.
*
* An icon name is a string that contains only lowercase letters, numbers, and hyphens.
* It must be composed of slugs separated by colons.
*
* @see https://regex101.com/r/Gh2Z9s/1
*/
public static function isValidName(string $name): bool
{
return (bool) preg_match('#^([a-z0-9]+(-[a-z0-9]+)*)(:[a-z0-9]+(-[a-z0-9]+)*)*$#', $name);
}

public function __construct(
private readonly string $innerSvg,
private readonly array $attributes = [],
)
{
// @todo validate attributes (?)
// the main idea is to have a way to validate the attributes
// before the icon is cached to improve performances
// (avoiding to validate the attributes each time the icon is rendered)
}

public function toHtml(): string
{
$htmlAttributes = '';
foreach ($this->attributes as $name => $value) {
if (false === $value) {
continue;
}
$htmlAttributes .= ' '.$name;
if (true !== $value) {
$value = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$htmlAttributes .= '="'. $value .'"';
}
}

return '<svg'.$htmlAttributes.'>'.$this->innerSvg.'</svg>';
}

public function getInnerSvg(): string
{
return $this->innerSvg;
}

/**
* @return array<string, string|bool>
*/
public function getAttributes(): array
{
return $this->attributes;
}

/**
* @param array<string, string|bool> $attributes
* @return self
*/
public function withAttributes(array $attributes): self
{
foreach ($attributes as $name => $value) {
if (!is_string($name)) {
throw new \InvalidArgumentException(sprintf('Attribute names must be string, "%s" given.', get_debug_type($name)));
}
// @todo regexp would be better ?
if (!ctype_alnum($name) && !str_contains($name, '-')) {
throw new \InvalidArgumentException(sprintf('Invalid attribute name "%s".', $name));
}
if (!is_string($value) && !is_bool($value)) {
throw new \InvalidArgumentException(sprintf('Invalid value type for attribute "%s". Boolean or string allowed, "%s" provided. ', $name, get_debug_type($value)));
}
}

return new self($this->innerSvg, [...$this->attributes, ...$attributes]);
}

public function withInnerSvg(string $innerSvg): self
{
// @todo validate svg ?
// The main idea is to not validate the attributes for every icon
// when they come from a pack (and thus share a set of attributes)

return new self($innerSvg, $this->attributes);
}

public function __toString(): string
{
return $this->toHtml();
}

public function serialize(): string
{
return serialize([$this->innerSvg, $this->attributes]);
}

public function unserialize(string $data): void
{
[$this->innerSvg, $this->attributes] = unserialize($data);
}

public function __serialize(): array
{
return [$this->innerSvg, $this->attributes];
}

public function __unserialize(array $data): void
{
[$this->innerSvg, $this->attributes] = $data;
}

public function offsetExists(mixed $offset): bool
{
return isset($this->attributes[$offset]);
}

public function offsetGet(mixed $offset): mixed
{
return $this->attributes[$offset];
}

public function offsetSet(mixed $offset, mixed $value): void
{
throw new \LogicException('The Icon object is immutable.');
}

public function offsetUnset(mixed $offset): void
{
throw new \LogicException('The Icon object is immutable.');
}
}
2 changes: 0 additions & 2 deletions src/Icons/tests/Integration/Twig/UXIconExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ public function testRenderIcons(): void
<li id="first">{{ ux_icon('user', {class: 'h-6 w-6'}) }}</li>
<li id="second">{{ ux_icon('user') }}</li>
<li id="third">{{ ux_icon('sub:check') }}</li>
<li id="forth">{{ ux_icon('sub/check') }}</li>
<li id="fifth"><twig:Icon name="user" class="h-6 w-6" /></li>
<li id="sixth"><twig:Icon name="sub:check" /></li>
</ul>
Expand All @@ -38,7 +37,6 @@ public function testRenderIcons(): void
<li id="first"><svg viewBox="0 0 24 24" fill="currentColor" class="h-6 w-6"><path fill-rule="evenodd" d="M7.5 6a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM3.751 20.105a8.25 8.25 0 0 1 16.498 0 .75.75 0 0 1-.437.695A18.683 18.683 0 0 1 12 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 0 1-.437-.695Z" clip-rule="evenodd"></path></svg></li>
<li id="second"><svg viewBox="0 0 24 24" fill="currentColor"><path fill-rule="evenodd" d="M7.5 6a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM3.751 20.105a8.25 8.25 0 0 1 16.498 0 .75.75 0 0 1-.437.695A18.683 18.683 0 0 1 12 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 0 1-.437-.695Z" clip-rule="evenodd"></path></svg></li>
<li id="third"><svg viewBox="0 0 24 24" fill="currentColor"><path fill-rule="evenodd" d="M19.916 4.626a.75.75 0 0 1 .208 1.04l-9 13.5a.75.75 0 0 1-1.154.114l-6-6a.75.75 0 0 1 1.06-1.06l5.353 5.353 8.493-12.74a.75.75 0 0 1 1.04-.207Z" clip-rule="evenodd"></path></svg></li>
<li id="forth"><svg viewBox="0 0 24 24" fill="currentColor"><path fill-rule="evenodd" d="M19.916 4.626a.75.75 0 0 1 .208 1.04l-9 13.5a.75.75 0 0 1-1.154.114l-6-6a.75.75 0 0 1 1.06-1.06l5.353 5.353 8.493-12.74a.75.75 0 0 1 1.04-.207Z" clip-rule="evenodd"></path></svg></li>
<li id="fifth"><svg viewBox="0 0 24 24" fill="currentColor" class="h-6 w-6"><path fill-rule="evenodd" d="M7.5 6a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM3.751 20.105a8.25 8.25 0 0 1 16.498 0 .75.75 0 0 1-.437.695A18.683 18.683 0 0 1 12 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 0 1-.437-.695Z" clip-rule="evenodd"></path></svg></li>
<li id="sixth"><svg viewBox="0 0 24 24" fill="currentColor"><path fill-rule="evenodd" d="M19.916 4.626a.75.75 0 0 1 .208 1.04l-9 13.5a.75.75 0 0 1-1.154.114l-6-6a.75.75 0 0 1 1.06-1.06l5.353 5.353 8.493-12.74a.75.75 0 0 1 1.04-.207Z" clip-rule="evenodd"></path></svg></li>
</ul>
Expand Down
9 changes: 5 additions & 4 deletions src/Icons/tests/Unit/Registry/LocalSvgIconRegistryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\UX\Icons\Registry\LocalSvgIconRegistry;
use Symfony\UX\Icons\Svg\Icon;

/**
* @author Kevin Bond <kevinbond@gmail.com>
Expand All @@ -24,10 +25,10 @@ final class LocalSvgIconRegistryTest extends TestCase
*/
public function testValidSvgs(string $name, array $expectedAttributes, string $expectedContent): void
{
[$content, $attributes] = $this->registry()->get($name);

$this->assertSame($expectedContent, $content);
$this->assertSame($expectedAttributes, $attributes);
$icon = $this->registry()->get($name);
$this->assertInstanceOf(Icon::class, $icon);
$this->assertSame($expectedContent, $icon->getInnerSvg());
$this->assertSame($expectedAttributes, $icon->getAttributes());
}

public static function validSvgProvider(): iterable
Expand Down
Loading