ControllerInjectorsWarmer.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace JMS\DiExtraBundle\HttpKernel;
  3. use Symfony\Component\Finder\Finder;
  4. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  5. use Symfony\Component\HttpKernel\KernelInterface;
  6. use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
  7. class ControllerInjectorsWarmer implements CacheWarmerInterface
  8. {
  9. private $kernel;
  10. private $controllerResolver;
  11. public function __construct(KernelInterface $kernel, ControllerResolver $resolver)
  12. {
  13. $this->kernel = $kernel;
  14. $this->controllerResolver = $resolver;
  15. }
  16. public function warmUp($cacheDir)
  17. {
  18. // This avoids class-being-declared twice errors when the cache:clear
  19. // command is called. The controllers are not pre-generated in that case.
  20. if (basename($cacheDir) === $this->kernel->getEnvironment().'_new') {
  21. return;
  22. }
  23. $classes = $this->findControllerClasses();
  24. foreach ($classes as $class) {
  25. $this->controllerResolver->createInjector($class);
  26. }
  27. }
  28. public function isOptional()
  29. {
  30. return false;
  31. }
  32. private function findControllerClasses()
  33. {
  34. $dirs = array();
  35. foreach ($this->kernel->getBundles() as $bundle) {
  36. if (!is_dir($controllerDir = $bundle->getPath().'/Controller')) {
  37. continue;
  38. }
  39. $dirs[] = $controllerDir;
  40. }
  41. foreach (Finder::create()->name('*Controller.php')->in($dirs)->files() as $file) {
  42. require_once $file->getRealPath();
  43. }
  44. // It is not so important if these controllers never can be reached with
  45. // the current configuration nor whether they are actually controllers.
  46. // Important is only that we do not miss any classes.
  47. return array_filter(get_declared_classes(), function($name) {
  48. return preg_match('/Controller\\\(.+)Controller$/', $name) > 0;
  49. });
  50. }
  51. }