RoutesCache.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. $resources[] = new FileResource($reflection->getFileName());
  54. if (!$admin->getRoutes()) {
  55. throw new \RuntimeException('Invalid data type, Admin::getRoutes must return a RouteCollection');
  56. }
  57. foreach ($admin->getRoutes()->getElements() as $code => $route) {
  58. $routes[$code] = $route->getDefault('_sonata_name');
  59. }
  60. if (!is_array($admin->getExtensions())) {
  61. throw new \RuntimeException('extensions must be an array');
  62. }
  63. foreach ($admin->getExtensions() as $extension) {
  64. $reflection = new \ReflectionObject($extension);
  65. $resources[] = new FileResource($reflection->getFileName());
  66. }
  67. $cache->write(serialize($routes), $resources);
  68. }
  69. return unserialize(file_get_contents($filename));
  70. }
  71. }