AsseticController.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /*
  3. * This file is part of the Symfony framework.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\Bundle\AsseticBundle\Controller;
  11. use Assetic\Asset\AssetCache;
  12. use Assetic\Asset\AssetInterface;
  13. use Assetic\Factory\LazyAssetManager;
  14. use Assetic\Cache\CacheInterface;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  18. /**
  19. * Serves assets.
  20. *
  21. * @author Kris Wallsmith <kris@symfony.com>
  22. */
  23. class AsseticController
  24. {
  25. protected $request;
  26. protected $am;
  27. protected $cache;
  28. public function __construct(Request $request, LazyAssetManager $am, CacheInterface $cache)
  29. {
  30. $this->request = $request;
  31. $this->am = $am;
  32. $this->cache = $cache;
  33. }
  34. public function render($name, $pos = null)
  35. {
  36. if (!$this->am->has($name)) {
  37. throw new NotFoundHttpException(sprintf('The "%s" asset could not be found.', $name));
  38. }
  39. $asset = $this->am->get($name);
  40. if (null !== $pos && !$asset = $this->findAssetLeaf($asset, $pos)) {
  41. throw new NotFoundHttpException(sprintf('The "%s" asset does not include a leaf at position %d.', $name, $pos));
  42. }
  43. $response = $this->createResponse();
  44. // last-modified
  45. if (null !== $lastModified = $asset->getLastModified()) {
  46. $date = new \DateTime();
  47. $date->setTimestamp($lastModified);
  48. $response->setLastModified($date);
  49. }
  50. // etag
  51. if ($this->am->hasFormula($name)) {
  52. $formula = $this->am->getFormula($name);
  53. $formula['last_modified'] = $lastModified;
  54. $response->setETag(md5(serialize($formula)));
  55. }
  56. if ($response->isNotModified($this->request)) {
  57. return $response;
  58. }
  59. $response->setContent($this->cachifyAsset($asset)->dump());
  60. return $response;
  61. }
  62. protected function createResponse()
  63. {
  64. return new Response();
  65. }
  66. protected function cachifyAsset(AssetInterface $asset)
  67. {
  68. return new AssetCache($asset, $this->cache);
  69. }
  70. private function findAssetLeaf(\Traversable $asset, $pos)
  71. {
  72. $i = 0;
  73. foreach ($asset as $leaf) {
  74. if ($pos == $i++) {
  75. return $leaf;
  76. }
  77. }
  78. }
  79. }