Asset.php
73 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWP\League\Plates\Extension; |
| 4 | |
| 5 | use IAWP\League\Plates\Engine; |
| 6 | use IAWP\League\Plates\Template\Template; |
| 7 | use LogicException; |
| 8 | /** |
| 9 | * Extension that adds the ability to create "cache busted" asset URLs. |
| 10 | */ |
| 11 | class Asset implements ExtensionInterface |
| 12 | { |
| 13 | /** |
| 14 | * Instance of the current template. |
| 15 | * @var Template |
| 16 | */ |
| 17 | public $template; |
| 18 | /** |
| 19 | * Path to asset directory. |
| 20 | * @var string |
| 21 | */ |
| 22 | public $path; |
| 23 | /** |
| 24 | * Enables the filename method. |
| 25 | * @var boolean |
| 26 | */ |
| 27 | public $filenameMethod; |
| 28 | /** |
| 29 | * Create new Asset instance. |
| 30 | * @param string $path |
| 31 | * @param boolean $filenameMethod |
| 32 | */ |
| 33 | public function __construct($path, $filenameMethod = \false) |
| 34 | { |
| 35 | $this->path = \rtrim($path, '/'); |
| 36 | $this->filenameMethod = $filenameMethod; |
| 37 | } |
| 38 | /** |
| 39 | * Register extension function. |
| 40 | * @param Engine $engine |
| 41 | * @return null |
| 42 | */ |
| 43 | public function register(Engine $engine) |
| 44 | { |
| 45 | $engine->registerFunction('asset', array($this, 'cachedAssetUrl')); |
| 46 | } |
| 47 | /** |
| 48 | * Create "cache busted" asset URL. |
| 49 | * @param string $url |
| 50 | * @return string |
| 51 | */ |
| 52 | public function cachedAssetUrl($url) |
| 53 | { |
| 54 | $filePath = $this->path . '/' . \ltrim($url, '/'); |
| 55 | if (!\file_exists($filePath)) { |
| 56 | throw new LogicException('Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.'); |
| 57 | } |
| 58 | $lastUpdated = \filemtime($filePath); |
| 59 | $pathInfo = \pathinfo($url); |
| 60 | if ($pathInfo['dirname'] === '.') { |
| 61 | $directory = ''; |
| 62 | } elseif ($pathInfo['dirname'] === \DIRECTORY_SEPARATOR) { |
| 63 | $directory = '/'; |
| 64 | } else { |
| 65 | $directory = $pathInfo['dirname'] . '/'; |
| 66 | } |
| 67 | if ($this->filenameMethod) { |
| 68 | return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension']; |
| 69 | } |
| 70 | return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated; |
| 71 | } |
| 72 | } |
| 73 |