Start writing unit tests

This commit is contained in:
Brabli
2022-07-24 17:13:11 +01:00
parent b5b51132f3
commit a0522a6700
6 changed files with 180 additions and 5 deletions

View File

@@ -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>.*<\/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('/(<svg(.|\n)*?>\n?)/', "$1<title>$title</title>", $markup);
}
}
class IconNotFound extends Exception {};