| 1 | <?php |
||
| 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 |