AssetWriter.php 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2012 OpenSky Project Inc
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Assetic;
  11. use Assetic\Asset\AssetInterface;
  12. /**
  13. * Writes assets to the filesystem.
  14. *
  15. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  16. */
  17. class AssetWriter
  18. {
  19. private $dir;
  20. /**
  21. * Constructor.
  22. *
  23. * @param string $dir The base web directory
  24. */
  25. public function __construct($dir)
  26. {
  27. $this->dir = $dir;
  28. }
  29. public function writeManagerAssets(AssetManager $am)
  30. {
  31. foreach ($am->getNames() as $name) {
  32. $this->writeAsset($am->get($name));
  33. }
  34. }
  35. public function writeAsset(AssetInterface $asset)
  36. {
  37. static::write($this->dir . '/' . $asset->getTargetPath(), $asset->dump());
  38. }
  39. protected static function write($path, $contents)
  40. {
  41. if (!is_dir($dir = dirname($path)) && false === @mkdir($dir, 0777, true)) {
  42. throw new \RuntimeException('Unable to create directory '.$dir);
  43. }
  44. if (false === @file_put_contents($path, $contents)) {
  45. throw new \RuntimeException('Unable to write file '.$path);
  46. }
  47. }
  48. }