FontAwesomeLoader::parseIdent()   B
last analyzed

Complexity

Conditions 7
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 21
ccs 12
cts 12
cp 1
rs 8.8333
cc 7
nc 3
nop 1
crap 7
1
<?php
2
3
/*
4
 * This file is part of ocubom/twig-svg-extension
5
 *
6
 * © Oscar Cubo Medina <https://ocubom.github.io>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ocubom\Twig\Extension\Svg\Provider\FontAwesome;
13
14
use Ocubom\Twig\Extension\Svg\Exception\LoaderException;
15
use Ocubom\Twig\Extension\Svg\Provider\FileSystem\FileSystemLoader;
16
use Ocubom\Twig\Extension\Svg\Svg;
17
use Ocubom\Twig\Extension\Svg\Util\PathCollection;
18
19
class FontAwesomeLoader extends FileSystemLoader
20
{
21 20
    public function __construct(PathCollection $searchPath)
22
    {
23 20
        parent::__construct($searchPath);
24
    }
25
26 6
    public function resolve(string $ident, iterable $options = null): Svg
27
    {
28 6
        $errors = [];
29
30 6
        foreach (self::parseIdent(preg_split('@\s+@', mb_strtolower($ident))) as $path) {
31 6
            if (array_key_exists($path, $errors)) {
32 1
                continue;
33
            }
34
35
            try {
36 6
                return new FontAwesomeSvg($this->findPath($path), $options);
37 4
            } catch (LoaderException $err) {
38 4
                $errors[$path] = $err;
39
            }
40
        }
41
42
        // Could not resolve
43 4
        throw new LoaderException($ident, new \ReflectionClass(__CLASS__), null, 0, $errors);
44
    }
45
46 6
    private static function parseIdent(array $ident): iterable
47
    {
48 6
        $ident[] = FontAwesome::DEFAULT_PREFIX; // Add default prefix as fallback
49
50 6
        foreach ($ident as $prefix) {
51 6
            $style = FontAwesome::PREFIXES[$prefix] ?? null;
52 6
            if (null === $style) {
53 5
                continue; // Ignore tokens that are *not* a known prefix
54
            }
55
56 6
            foreach ($ident as $name) {
57 6
                if (isset(FontAwesome::PREFIXES[$name])) {
58 5
                    continue; // Ignore tokens that are a known prefix
59
                }
60
61 6
                $name = (0 === mb_strpos($name, 'fa-')) ? mb_substr($name, 3) : $name;
62 6
                if (empty($name)) {
63
                    continue; // @codeCoverageIgnore
64
                }
65
66 6
                yield sprintf('%s/%s', $style, $name);
67
            }
68
        }
69
    }
70
}
71