RoutesCache.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /*
  3. * This file is part of the Sonata project.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  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 Sonata\AdminBundle\Route;
  11. use Sonata\AdminBundle\Admin\AdminInterface;
  12. use Symfony\Component\Config\ConfigCache;
  13. use Symfony\Component\Config\Resource\FileResource;
  14. class RoutesCache
  15. {
  16. /**
  17. * @var string
  18. */
  19. protected $cacheFolder;
  20. /**
  21. * @var boolean
  22. */
  23. protected $debug;
  24. /**
  25. * @param string $cacheFolder
  26. * @param bool $debug
  27. */
  28. public function __construct($cacheFolder, $debug)
  29. {
  30. $this->cacheFolder = $cacheFolder;
  31. $this->debug = $debug;
  32. }
  33. /**
  34. * @param AdminInterface $admin
  35. *
  36. * @return mixed
  37. * @throws \RuntimeException
  38. */
  39. public function load(AdminInterface $admin)
  40. {
  41. $filename = $this->cacheFolder.'/route_'.md5($admin->getCode());
  42. $cache = new ConfigCache($filename, $this->debug);
  43. if (!$cache->isFresh()) {
  44. $resources = array();
  45. $routes = array();
  46. $reflection = new \ReflectionObject($admin);
  47. $resources[] = new FileResource($reflection->getFileName());
  48. if (!$admin->getRoutes()) {
  49. throw new \RuntimeException('Invalid data type, Admin::getRoutes must return a RouteCollection');
  50. }
  51. foreach ($admin->getRoutes()->getElements() as $code => $route) {
  52. $routes[$code] = $route->getDefault('_sonata_name');
  53. }
  54. if (!is_array($admin->getExtensions())) {
  55. throw new \RuntimeException('extensions must be an array');
  56. }
  57. foreach ($admin->getExtensions() as $extension) {
  58. $reflection = new \ReflectionObject($extension);
  59. $resources[] = new FileResource($reflection->getFileName());
  60. }
  61. $cache->write(serialize($routes), $resources);
  62. }
  63. return unserialize(file_get_contents($filename));
  64. }
  65. }