diff --git a/config/services.yml b/config/services.yml
index 618b7c3..7e447ae 100644
--- a/config/services.yml
+++ b/config/services.yml
@@ -7,8 +7,10 @@ services:
alias: Pcm\IconBundle\Twig\Functions\IconExtension
public: true
+
Pcm\IconBundle\Twig\Functions\IconExtension:
+ tags: ['twig.extension']
public: false
arguments:
- # $dir:
- # - '%kernel.project_dir%/public/icons'
+ $directories:
+ - '%kernel.project_dir%/public/icons'
diff --git a/src/Twig/Functions/IconExtension.php b/src/Twig/Functions/IconExtension.php
index fea66b6..0cb5c8e 100644
--- a/src/Twig/Functions/IconExtension.php
+++ b/src/Twig/Functions/IconExtension.php
@@ -4,22 +4,98 @@ declare(strict_types=1);
namespace Pcm\IconBundle\Twig\Functions;
+use Exception;
+use InvalidArgumentException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
+use TypeError;
final class IconExtension extends AbstractExtension
{
+ public function __construct(private array $directories) {}
+
+ private const DEFAULT_OPTIONS = [
+ 'icon' => null,
+ 'title' => null,
+ ];
+
/**
* @inheritDoc
*/
public function getFunctions(): array
{
return [
- new TwigFunction('icon', [$this, 'render'], [
+ new TwigFunction('icon', [$this, 'renderIcon'], [
'is_safe' => ['html']
])
];
}
+
+ /**
+ * @param array $options
+ */
+ public function renderIcon(array $userOptions): string
+ {
+ $options = $this->mergeUserOptionsWithDefaults($userOptions);
+
+ $iconFilepath = $this->findSvgFilepath($options['icon']);
+ $rawSvgMarkup = $this->getSvgMarkup($iconFilepath);
+ $cleanSvgMarkup = $this->cleanSvgMarkup($rawSvgMarkup);
+
+ if ($this->titleIsANonEmptyString($options['title'])) {
+ $markup = $this->addTitleToMarkup($cleanSvgMarkup, $options['title']);
+ }
+
+ return $markup;
+ }
+
+ private function mergeUserOptionsWithDefaults(array $userOptions): array
+ {
+ return array_merge(self::DEFAULT_OPTIONS, $userOptions);
+ }
+
+ private function findSvgFilepath(string $iconName): string
+ {
+ foreach ($this->directories as $directory) {
+ $potentialFilepath = sprintf('%s/%s.svg', $directory, $iconName);
+ if (file_exists($potentialFilepath)) {
+ return $potentialFilepath;
+ }
+ }
+
+ throw new IconNotFound(sprintf('File "%s.svg" not found in %s', $iconName, implode(', ', $this->directories)));
+ }
+
+ private function getSvgMarkup(string $filepath): string
+ {
+ return file_get_contents($filepath);
+ }
+
+ private function cleanSvgMarkup(string $markup): string
+ {
+ return preg_replace('/
.*<\/title>/', '', $markup);
+ }
+
+ private function titleIsANonEmptyString(mixed $title): bool
+ {
+ if (!is_string($title) && null !== $title)
+ throw new TypeError('Title must be a string!');
+
+
+ if ('' === $title)
+ throw new InvalidArgumentException('Title string must not be empty!');
+
+ return true;
+ }
+
+ private function addTitleToMarkup(string $markup, ?string $title): string
+ {
+ if (null === $title) {
+ return $markup;
+ }
+
+ return preg_replace('/(