RoutesCache.php 2.3 KB

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