RoutesCache.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. class RoutesCache
  15. {
  16. /**
  17. * @var string
  18. */
  19. protected $cacheFolder;
  20. /**
  21. * @var bool
  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. *
  38. * @throws \RuntimeException
  39. */
  40. public function load(AdminInterface $admin)
  41. {
  42. $filename = $this->cacheFolder.'/route_'.md5($admin->getCode());
  43. $cache = new ConfigCache($filename, $this->debug);
  44. if (!$cache->isFresh()) {
  45. $resources = array();
  46. $routes = array();
  47. $reflection = new \ReflectionObject($admin);
  48. $resources[] = new FileResource($reflection->getFileName());
  49. if (!$admin->getRoutes()) {
  50. throw new \RuntimeException('Invalid data type, Admin::getRoutes must return a RouteCollection');
  51. }
  52. foreach ($admin->getRoutes()->getElements() as $code => $route) {
  53. $routes[$code] = $route->getDefault('_sonata_name');
  54. }
  55. if (!is_array($admin->getExtensions())) {
  56. throw new \RuntimeException('extensions must be an array');
  57. }
  58. foreach ($admin->getExtensions() as $extension) {
  59. $reflection = new \ReflectionObject($extension);
  60. $resources[] = new FileResource($reflection->getFileName());
  61. }
  62. $cache->write(serialize($routes), $resources);
  63. }
  64. return unserialize(file_get_contents($filename));
  65. }
  66. }