| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Assetic package, an OpenSky project. |
| 5 |
* |
| 6 |
* (c) 2010-2014 OpenSky Project Inc |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Assetic; |
| 13 |
|
| 14 |
use Assetic\Asset\AssetInterface; |
| 15 |
use Assetic\Util\VarUtils; |
| 16 |
|
| 17 |
/** |
| 18 |
* Writes assets to the filesystem. |
| 19 |
* |
| 20 |
* @author Kris Wallsmith <[email protected]> |
| 21 |
* @author Johannes M. Schmitt <[email protected]> |
| 22 |
*/ |
| 23 |
class AssetWriter |
| 24 |
{ |
| 25 |
private $dir; |
| 26 |
private $values; |
| 27 |
|
| 28 |
/** |
| 29 |
* Constructor. |
| 30 |
* |
| 31 |
* @param string $dir The base web directory |
| 32 |
* @param array $values Variable values |
| 33 |
* |
| 34 |
* @throws \InvalidArgumentException if a variable value is not a string |
| 35 |
*/ |
| 36 |
public function __construct($dir, array $values = array()) |
| 37 |
{ |
| 38 |
foreach ($values as $var => $vals) { |
| 39 |
foreach ($vals as $value) { |
| 40 |
if (!is_string($value)) { |
| 41 |
throw new \InvalidArgumentException(sprintf('All variable values must be strings, but got %s for variable "%s".', json_encode($value), $var)); |
| 42 |
} |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
$this->dir = $dir; |
| 47 |
$this->values = $values; |
| 48 |
} |
| 49 |
|
| 50 |
public function writeManagerAssets(AssetManager $am) |
| 51 |
{ |
| 52 |
foreach ($am->getNames() as $name) { |
| 53 |
$this->writeAsset($am->get($name)); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
public function writeAsset(AssetInterface $asset) |
| 58 |
{ |
| 59 |
foreach (VarUtils::getCombinations($asset->getVars(), $this->values) as $combination) { |
| 60 |
$asset->setValues($combination); |
| 61 |
|
| 62 |
static::write( |
| 63 |
$this->dir.'/'.VarUtils::resolve( |
| 64 |
$asset->getTargetPath(), |
| 65 |
$asset->getVars(), |
| 66 |
$asset->getValues() |
| 67 |
), |
| 68 |
$asset->dump() |
| 69 |
); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
protected static function write($path, $contents) |
| 74 |
{ |
| 75 |
if (!is_dir($dir = dirname($path)) && false === @mkdir($dir, 0777, true)) { |
| 76 |
throw new \RuntimeException('Unable to create directory '.$dir); |
| 77 |
} |
| 78 |
|
| 79 |
if (false === @file_put_contents($path, $contents)) { |
| 80 |
throw new \RuntimeException('Unable to write file '.$path); |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Not used. |
| 86 |
* |
| 87 |
* This method is provided for backward compatibility with certain versions |
| 88 |
* of AsseticBundle. |
| 89 |
*/ |
| 90 |
private function getCombinations(array $vars) |
| 91 |
{ |
| 92 |
return VarUtils::getCombinations($vars, $this->values); |
| 93 |
} |
| 94 |
} |
| 95 |
|