Completed
Push — master ( af09d7...7599bb )
by Dorian
02:06
created

AssetsExtension::getAssetPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 3
nop 3
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;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
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