1: <?php
2:
3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Minion\Twig;
12:
13: use Minion\Application;
14: use Minion\Utils;
15: use Symfony\Component\HttpFoundation\File\Exception\FileException;
16: use Symfony\Component\HttpFoundation\Request;
17:
18: 19: 20: 21: 22: 23:
24: class AssetExtension extends \Twig_Extension
25: {
26:
27: private $container;
28:
29: 30: 31: 32: 33: 34: 35: 36:
37: public function __construct(Application $app) {
38: $this->container = $app;
39: }
40:
41: 42: 43:
44: public function getName() {
45: return 'minion_twig_asset';
46: }
47:
48: 49: 50:
51: public function getFunctions() {
52: return [
53: new \Twig_Function('asset', [
54: $this,
55: 'assetFunction',
56: ]
57: ),
58: ];
59: }
60:
61: 62: 63: 64: 65: 66: 67: 68: 69: 70:
71: public function assetFunction($asset, $serverPath = false) {
72:
73: $request = isset($this->container['request']) ? $this->container['request'] : null;
74: $path = \ltrim($asset, '/\\');
75: $assetPath = Utils::fixPath($this->container->getRootDir() . '/web/' . $path);
76:
77: if(!\file_exists($assetPath))
78: throw new FileException("Asset '$asset' with path '$assetPath' not found");
79:
80: if(!$serverPath)
81: if($request instanceof Request)
82: $assetPath = $request->getSchemeAndHttpHost() . '/' . $path;
83: else
84: $assetPath = '/' . $path;
85:
86: return $assetPath;
87: }
88: }