好吧,我意識到如何解決我的問題:
我必須擴展AssetFactory並覆蓋parseInput方法。我想出了以下解決方案:
use Assetic\Asset\AssetInterface;
use Assetic\Factory\AssetFactory;
class MyAssetFactory extends AssetFactory
{
/**
* @var string[]
*/
private $rootFolders;
/**
* @param string[] $rootFolders
* @param bool $debug
*/
public function __construct($rootFolders, $debug = false)
{
if (empty($rootFolders)) {
throw new \Exception('there must be at least one folder');
}
parent::__construct($rootFolders[0], $debug);
$this->rootFolders = $rootFolders;
}
/**
* @param string $input
* @param array $options
* @return AssetInterface an asset
*/
protected function parseInput($input, array $options = array())
{
// let the parent handle references, http assets, absolute path and glob assets
if ('@' == $input[0] || false !== strpos($input, '://') || 0 === strpos($input, '//') || self::isAbsolutePath($input) || false !== strpos($input, '*')) {
return parent::parseInput($input, $options);
}
// now we have a relatve path eg js/file.js
// let's match it with the given rootFolders
$root = '';
$path = $input;
foreach ($this->rootFolders as $root) {
if (file_exists($root . DIRECTORY_SEPARATOR . $input)) {
$path = $input;
$input = $root . $path;
break;
}
}
// TODO: what to do, if the asset was not found..?
return $this->createFileAsset($input, $root, $path, $options['vars']);
}
/**
* copied from AssetFactory, as it was private
*
* @param string $path
* @return bool
*/
private static function isAbsolutePath($path)
{
return '/' == $path[0] || '\\' == $path[0] || (3 < strlen($path) && ctype_alpha($path[0]) && $path[1] == ':' && ('\\' == $path[2] || '/' == $path[2]));
}
}
現在我可以用不同的源文件夾創建一個新工廠。
$factory = new MyAssetFactory(array('/folder/alpha/', '/folder/beta/'));
// $factory->set some stuff
$twig->addExtension(new AsseticExtension($factory));
來源
2015-02-24 13:59:14
Tim