diff --git a/src/mibew/libs/classes/Mibew/Handlebars/Helper/AssetHelper.php b/src/mibew/libs/classes/Mibew/Handlebars/Helper/AssetHelper.php new file mode 100644 index 00000000..262dd7e0 --- /dev/null +++ b/src/mibew/libs/classes/Mibew/Handlebars/Helper/AssetHelper.php @@ -0,0 +1,138 @@ + + * {{asset "js/libs/super_lib.js"}} + * + * + * One can use locations passed to class constructor as a prefixes in relative + * paths. Lets assume that the following array is passed to the constructor: + * + * $helper = new AssetHelper( + * $generator, + * array('CustomStorage' => 'custom/files/storage') + * ); + * + * + * Then in a template you can do something like the following: + * + * {{asset "@CustomStorage/images/the_best_logo.png"}} + * + */ +class AssetHelper implements HelperInterface, AssetUrlGeneratorAwareInterface +{ + /** + * @var array + */ + protected $locations = null; + + /** + * @var AssetUrlGeneratorInterface|null + */ + protected $generator = null; + + /** + * Class constructor. + * + * @param AssetUrlGeneratorInterface $generator An instance of URL generator + * @param array $locations Associative array of locations that can be used + * as prefixes for asset relative paths. The keys are prefixes and the + * values are locations relative paths. These paths must not content + * neither leading nor trailing slashes. + */ + public function __construct(AssetUrlGeneratorInterface $generator, $locations = array()) + { + $this->generator = $generator; + + // Strip slashes from location paths. + foreach ($locations as $name => $path) { + $this->locations[$name] = trim($path, '/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAssetUrlGenerator() + { + return $this->generator; + } + + /** + * {@inheritdoc} + */ + public function setAssetUrlGenerator(AssetUrlGeneratorInterface $generator) + { + $this->generator = $generator; + } + + /** + * {@inheritdoc} + */ + public function execute(Template $template, Context $context, $args, $source) + { + $parsed_args = $template->parseArguments($args); + if (empty($parsed_args)) { + return ''; + } + $relative_path = $context->get($parsed_args[0]); + + if (preg_match("/^@(\w+)\//", $relative_path, $matches)) { + // Resolve locations + $relative_path = substr_replace( + $relative_path, + $this->resolveLocation($matches[1]), + 0, + strlen($matches[0]) - 1 // Leave the slash in place + ); + } + + return $this->generator->generate($relative_path); + } + + /** + * Resolves location by it's name + * + * @param string $name Location name + * @return string Relative path of the location. + * @throws \InvalidArgumentException + */ + protected function resolveLocation($name) + { + foreach ($this->locations as $current_name => $location) { + if ($name == $current_name) { + return $location; + } + } + + throw new \InvalidArgumentException(sprintf('Unknown location %s', $name)); + } +}