AbstractPhpFileCacheWarmer.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Bundle\FrameworkBundle\CacheWarmer;
  11. use Symfony\Component\Cache\Adapter\ArrayAdapter;
  12. use Symfony\Component\Cache\Adapter\NullAdapter;
  13. use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
  14. use Symfony\Component\Config\Resource\ClassExistenceResource;
  15. use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
  16. abstract class AbstractPhpFileCacheWarmer implements CacheWarmerInterface
  17. {
  18. private $phpArrayFile;
  19. /**
  20. * @param string $phpArrayFile The PHP file where metadata are cached
  21. */
  22. public function __construct(string $phpArrayFile)
  23. {
  24. $this->phpArrayFile = $phpArrayFile;
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function isOptional()
  30. {
  31. return true;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @return string[] A list of classes to preload on PHP 7.4+
  37. */
  38. public function warmUp(string $cacheDir)
  39. {
  40. $arrayAdapter = new ArrayAdapter();
  41. spl_autoload_register([ClassExistenceResource::class, 'throwOnRequiredClass']);
  42. try {
  43. if (!$this->doWarmUp($cacheDir, $arrayAdapter)) {
  44. return;
  45. }
  46. } finally {
  47. spl_autoload_unregister([ClassExistenceResource::class, 'throwOnRequiredClass']);
  48. }
  49. // the ArrayAdapter stores the values serialized
  50. // to avoid mutation of the data after it was written to the cache
  51. // so here we un-serialize the values first
  52. $values = array_map(function ($val) { return null !== $val ? unserialize($val) : null; }, $arrayAdapter->getValues());
  53. return $this->warmUpPhpArrayAdapter(new PhpArrayAdapter($this->phpArrayFile, new NullAdapter()), $values);
  54. }
  55. /**
  56. * @return string[] A list of classes to preload on PHP 7.4+
  57. */
  58. protected function warmUpPhpArrayAdapter(PhpArrayAdapter $phpArrayAdapter, array $values)
  59. {
  60. return (array) $phpArrayAdapter->warmUp($values);
  61. }
  62. /**
  63. * @internal
  64. */
  65. final protected function ignoreAutoloadException(string $class, \Exception $exception): void
  66. {
  67. try {
  68. ClassExistenceResource::throwOnRequiredClass($class, $exception);
  69. } catch (\ReflectionException $e) {
  70. }
  71. }
  72. /**
  73. * @return bool false if there is nothing to warm-up
  74. */
  75. abstract protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter);
  76. }