RoutesCache.php 2.3 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. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  16. */
  17. class RoutesCache
  18. {
  19. /**
  20. * @var string
  21. */
  22. protected $cacheFolder;
  23. /**
  24. * @var bool
  25. */
  26. protected $debug;
  27. /**
  28. * @param string $cacheFolder
  29. * @param bool $debug
  30. */
  31. public function __construct($cacheFolder, $debug)
  32. {
  33. $this->cacheFolder = $cacheFolder;
  34. $this->debug = $debug;
  35. }
  36. /**
  37. * @param AdminInterface $admin
  38. *
  39. * @return mixed
  40. *
  41. * @throws \RuntimeException
  42. */
  43. public function load(AdminInterface $admin)
  44. {
  45. $filename = $this->cacheFolder.'/route_'.md5($admin->getCode());
  46. $cache = new ConfigCache($filename, $this->debug);
  47. if (!$cache->isFresh()) {
  48. $resources = array();
  49. $routes = array();
  50. $reflection = new \ReflectionObject($admin);
  51. if (file_exists($reflection->getFileName())) {
  52. $resources[] = new FileResource($reflection->getFileName());
  53. }
  54. if (!$admin->getRoutes()) {
  55. throw new \RuntimeException('Invalid data type, AdminInterface::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. }