Passed
Branch master (609f2f)
by Dorian
08:59
created

AssetsExtension::getAssetPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 18
rs 9.9332
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gnutix\Twig\Extension;
6
7
use Symfony\Component\Finder\Finder;
8
use Symfony\Component\HttpFoundation\Request;
9
use Twig\Extension\AbstractExtension;
10
use Twig\TwigFunction;
11
12
final class AssetsExtension extends AbstractExtension
13
{
14
    protected string $publicDir;
15
16
    public function __construct(string $publicDir)
17
    {
18
        $this->publicDir = $publicDir;
19
    }
20
21
    public function getName(): string
22
    {
23
        return 'gnutix_twig_assets_extension';
24
    }
25
26
    public function getFunctions(): array
27
    {
28
        return [new TwigFunction('asset', [$this, 'getAssetPath'])];
29
    }
30
31
    public function getAssetPath(Request $request, string $asset, bool $throwException = true): string
32
    {
33
        $finder = new Finder();
34
35
        $assetFound = $finder->in(rtrim($this->publicDir, '/').'/'.ltrim(pathinfo($asset, PATHINFO_DIRNAME), '/'))
36
            ->files()
37
            ->name(pathinfo($asset, PATHINFO_FILENAME).'.'.pathinfo($asset, PATHINFO_EXTENSION))
38
            ->count();
39
40
        if (0 < $assetFound) {
41
            return rtrim($request->getBasePath(), '/').'/'.ltrim($asset, '/');
42
        }
43
44
        if ($throwException) {
45
            throw new \InvalidArgumentException('The asset "'.$asset.'" could not be found in "'.$this->publicDir.'".');
46
        }
47
48
        return '';
49
    }
50
}
51