Throw exception if option is not recognised

This commit is contained in:
Brabli
2022-08-29 23:32:12 +01:00
parent eb2bea62a7
commit 03212310fd
2 changed files with 19 additions and 4 deletions

View File

@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Pcm\IconBundle\Twig\Functions;
use InvalidArgumentException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
@@ -23,7 +22,7 @@ final class IconExtension extends AbstractExtension
public function __construct(private array $directories, private array $palletes)
{
if (empty($this->directories))
throw new InvalidArgumentException('Directories array must contain at least one path!');
throw new \InvalidArgumentException('Directories array must contain at least one path!');
$dirsContainNonString = array_reduce($this->directories,
fn($notString, $path) => $notString || !is_string($path));
@@ -32,7 +31,7 @@ final class IconExtension extends AbstractExtension
throw new \TypeError('Directories array must only contain strings!');
if (empty($this->palletes))
throw new InvalidArgumentException('Palletes array must contain at least one pallet!');
throw new \InvalidArgumentException('Palletes array must contain at least one pallet!');
$pelletesContainNonarray = array_reduce($this->palletes,
fn($notArray, $path) => $notArray || !is_array($path));
@@ -82,13 +81,14 @@ final class IconExtension extends AbstractExtension
{
$options = $this->mergeUserOptionsWithDefaults($userOptions);
$this->throwIfUnrecognisedOptionExists($options);
$iconFilepath = $this->findSvgFilepath($options['icon']);
$rawSvgMarkup = $this->getSvgMarkup($iconFilepath);
$cleanSvgMarkup = $this->cleanSvgMarkup($rawSvgMarkup);
$mainPallete = $this->getPallete($options['colour']);
$colourClasses = "{$mainPallete['stroke']} {$mainPallete['fill']}";
if (null !== $options['hover']) {
@@ -121,6 +121,14 @@ final class IconExtension extends AbstractExtension
return array_merge(self::DEFAULT_OPTIONS, $userOptions);
}
private function throwIfUnrecognisedOptionExists(array $options): void
{
foreach (array_keys($options) as $key) {
if (!key_exists($key, self::DEFAULT_OPTIONS))
throw new \InvalidArgumentException("Unrecognised option '{$key}'!");
}
}
private function findSvgFilepath(string $iconName): string
{
foreach ($this->directories as $directory) {

View File

@@ -299,4 +299,11 @@ class IconExtensionTest extends TestCase
$this->assertMatchesRegularExpression('/<svg.+class=".*group-hover:fill-white.*".*>/', $contents);
$this->assertMatchesRegularExpression('/<svg.+class=".*group-hover:stroke-white.*".*>/', $contents);
}
public function testThrowsIfInvalidOptionPassed(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->icon->renderIcon(['icon' => self::ICON, 'fake-key-should-throw' => null]);
}
}