DoctrineMetadataCacheWarmer.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Doctrine\Bundle\DoctrineBundle\CacheWarmer;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\Persistence\Mapping\AbstractClassMetadataFactory;
  5. use LogicException;
  6. use Symfony\Bundle\FrameworkBundle\CacheWarmer\AbstractPhpFileCacheWarmer;
  7. use Symfony\Component\Cache\Adapter\ArrayAdapter;
  8. use Symfony\Component\Cache\DoctrineProvider;
  9. use function is_file;
  10. use function method_exists;
  11. class DoctrineMetadataCacheWarmer extends AbstractPhpFileCacheWarmer
  12. {
  13. /** @var EntityManagerInterface */
  14. private $entityManager;
  15. /** @var string */
  16. private $phpArrayFile;
  17. public function __construct(EntityManagerInterface $entityManager, string $phpArrayFile)
  18. {
  19. $this->entityManager = $entityManager;
  20. $this->phpArrayFile = $phpArrayFile;
  21. parent::__construct($phpArrayFile);
  22. }
  23. /**
  24. * It must not be optional because it should be called before ProxyCacheWarmer which is not optional.
  25. */
  26. public function isOptional(): bool
  27. {
  28. return false;
  29. }
  30. /**
  31. * @param string $cacheDir
  32. */
  33. protected function doWarmUp($cacheDir, ArrayAdapter $arrayAdapter): bool
  34. {
  35. // cache already warmed up, no needs to do it again
  36. if (is_file($this->phpArrayFile)) {
  37. return false;
  38. }
  39. $metadataFactory = $this->entityManager->getMetadataFactory();
  40. if ($metadataFactory instanceof AbstractClassMetadataFactory && $metadataFactory->getLoadedMetadata()) {
  41. throw new LogicException('DoctrineMetadataCacheWarmer must load metadata first, check priority of your warmers.');
  42. }
  43. if (method_exists($metadataFactory, 'setCache')) {
  44. $metadataFactory->setCache($arrayAdapter);
  45. } elseif ($metadataFactory instanceof AbstractClassMetadataFactory) {
  46. // BC with doctrine/persistence < 2.2
  47. $metadataFactory->setCacheDriver(new DoctrineProvider($arrayAdapter));
  48. }
  49. $metadataFactory->getAllMetadata();
  50. return true;
  51. }
  52. }