CachePoolPass.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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\Component\Cache\DependencyInjection;
  11. use Symfony\Component\Cache\Adapter\AbstractAdapter;
  12. use Symfony\Component\Cache\Adapter\ArrayAdapter;
  13. use Symfony\Component\Cache\Adapter\ChainAdapter;
  14. use Symfony\Component\Cache\Adapter\NullAdapter;
  15. use Symfony\Component\Cache\Adapter\ParameterNormalizer;
  16. use Symfony\Component\Cache\Adapter\TagAwareAdapter;
  17. use Symfony\Component\Cache\Messenger\EarlyExpirationDispatcher;
  18. use Symfony\Component\Cache\PruneableInterface;
  19. use Symfony\Component\DependencyInjection\ChildDefinition;
  20. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  21. use Symfony\Component\DependencyInjection\ContainerBuilder;
  22. use Symfony\Component\DependencyInjection\Definition;
  23. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  24. use Symfony\Component\DependencyInjection\Reference;
  25. /**
  26. * @author Nicolas Grekas <p@tchwork.com>
  27. */
  28. class CachePoolPass implements CompilerPassInterface
  29. {
  30. public function process(ContainerBuilder $container): void
  31. {
  32. if ($container->hasParameter('cache.prefix.seed')) {
  33. $seed = $container->getParameterBag()->resolveValue($container->getParameter('cache.prefix.seed'));
  34. } else {
  35. $seed = '_'.$container->getParameter('kernel.project_dir');
  36. $seed .= '.'.$container->getParameter('kernel.container_class');
  37. }
  38. $needsMessageHandler = false;
  39. $allPools = [];
  40. $clearers = [];
  41. $attributes = [
  42. 'provider',
  43. 'name',
  44. 'namespace',
  45. 'default_lifetime',
  46. 'early_expiration_message_bus',
  47. 'reset',
  48. 'pruneable',
  49. ];
  50. foreach ($container->findTaggedServiceIds('cache.pool') as $id => $tags) {
  51. $adapter = $pool = $container->getDefinition($id);
  52. if ($pool->isAbstract()) {
  53. continue;
  54. }
  55. $class = $adapter->getClass();
  56. $providers = $adapter->getArguments();
  57. while ($adapter instanceof ChildDefinition) {
  58. $adapter = $container->findDefinition($adapter->getParent());
  59. $class = $class ?: $adapter->getClass();
  60. $providers += $adapter->getArguments();
  61. if ($t = $adapter->getTag('cache.pool')) {
  62. $tags[0] += $t[0];
  63. }
  64. }
  65. $name = $tags[0]['name'] ?? $id;
  66. if (!isset($tags[0]['namespace'])) {
  67. $namespaceSeed = $seed;
  68. if (null !== $class) {
  69. $namespaceSeed .= '.'.$class;
  70. }
  71. $tags[0]['namespace'] = $this->getNamespace($namespaceSeed, $name);
  72. }
  73. if (isset($tags[0]['clearer'])) {
  74. $clearer = $tags[0]['clearer'];
  75. while ($container->hasAlias($clearer)) {
  76. $clearer = (string) $container->getAlias($clearer);
  77. }
  78. } else {
  79. $clearer = null;
  80. }
  81. unset($tags[0]['clearer'], $tags[0]['name']);
  82. if (isset($tags[0]['provider'])) {
  83. $tags[0]['provider'] = new Reference(static::getServiceProvider($container, $tags[0]['provider']));
  84. }
  85. $pruneable = $tags[0]['pruneable'] ?? $container->getReflectionClass($class, false)?->implementsInterface(PruneableInterface::class) ?? false;
  86. if (ChainAdapter::class === $class) {
  87. $adapters = [];
  88. foreach ($providers['index_0'] ?? $providers[0] as $provider => $adapter) {
  89. if ($adapter instanceof ChildDefinition) {
  90. $chainedPool = clone $adapter;
  91. } else {
  92. $chainedPool = $adapter = new ChildDefinition($adapter);
  93. }
  94. $chainedTags = [\is_int($provider) ? [] : ['provider' => $provider]];
  95. $chainedClass = '';
  96. while ($adapter instanceof ChildDefinition) {
  97. $adapter = $container->findDefinition($adapter->getParent());
  98. $chainedClass = $chainedClass ?: $adapter->getClass();
  99. if ($t = $adapter->getTag('cache.pool')) {
  100. $chainedTags[0] += $t[0];
  101. }
  102. }
  103. if (ChainAdapter::class === $chainedClass) {
  104. throw new InvalidArgumentException(\sprintf('Invalid service "%s": chain of adapters cannot reference another chain, found "%s".', $id, $chainedPool->getParent()));
  105. }
  106. $i = 0;
  107. if (isset($chainedTags[0]['provider'])) {
  108. $chainedPool->replaceArgument($i++, new Reference(static::getServiceProvider($container, $chainedTags[0]['provider'])));
  109. }
  110. if (isset($tags[0]['namespace']) && !\in_array($adapter->getClass(), [ArrayAdapter::class, NullAdapter::class], true)) {
  111. $chainedPool->replaceArgument($i++, $tags[0]['namespace']);
  112. }
  113. if (isset($tags[0]['default_lifetime'])) {
  114. $chainedPool->replaceArgument($i++, $tags[0]['default_lifetime']);
  115. }
  116. $adapters[] = $chainedPool;
  117. }
  118. $pool->replaceArgument(0, $adapters);
  119. unset($tags[0]['provider'], $tags[0]['namespace']);
  120. $i = 1;
  121. } else {
  122. $i = 0;
  123. }
  124. foreach ($attributes as $attr) {
  125. if (!isset($tags[0][$attr])) {
  126. // no-op
  127. } elseif ('reset' === $attr) {
  128. if ($tags[0][$attr]) {
  129. $pool->addTag('kernel.reset', ['method' => $tags[0][$attr]]);
  130. }
  131. } elseif ('early_expiration_message_bus' === $attr) {
  132. $needsMessageHandler = true;
  133. $pool->addMethodCall('setCallbackWrapper', [(new Definition(EarlyExpirationDispatcher::class))
  134. ->addArgument(new Reference($tags[0]['early_expiration_message_bus']))
  135. ->addArgument(new Reference('reverse_container'))
  136. ->addArgument((new Definition('callable'))
  137. ->setFactory([new Reference($id), 'setCallbackWrapper'])
  138. ->addArgument(null)
  139. ),
  140. ]);
  141. $pool->addTag('container.reversible');
  142. } elseif ('pruneable' === $attr) {
  143. // no-op
  144. } elseif ('namespace' !== $attr || !\in_array($class, [ArrayAdapter::class, NullAdapter::class, TagAwareAdapter::class], true)) {
  145. $argument = $tags[0][$attr];
  146. if ('default_lifetime' === $attr && !is_numeric($argument)) {
  147. $argument = (new Definition('int', [$argument]))
  148. ->setFactory([ParameterNormalizer::class, 'normalizeDuration']);
  149. }
  150. $pool->replaceArgument($i++, $argument);
  151. }
  152. unset($tags[0][$attr]);
  153. }
  154. if (!empty($tags[0])) {
  155. throw new InvalidArgumentException(\sprintf('Invalid "cache.pool" tag for service "%s": accepted attributes are "clearer", "provider", "name", "namespace", "default_lifetime", "early_expiration_message_bus", "reset" and "pruneable", found "%s".', $id, implode('", "', array_keys($tags[0]))));
  156. }
  157. if (null !== $clearer) {
  158. $clearers[$clearer][$name] = new Reference($id, $container::IGNORE_ON_UNINITIALIZED_REFERENCE);
  159. }
  160. $poolTags = $pool->getTags();
  161. $poolTags['cache.pool'][0]['pruneable'] ??= $pruneable;
  162. $pool->setTags($poolTags);
  163. $allPools[$name] = new Reference($id, $container::IGNORE_ON_UNINITIALIZED_REFERENCE);
  164. }
  165. if (!$needsMessageHandler) {
  166. $container->removeDefinition('cache.early_expiration_handler');
  167. }
  168. $notAliasedCacheClearerId = 'cache.global_clearer';
  169. while ($container->hasAlias($notAliasedCacheClearerId)) {
  170. $notAliasedCacheClearerId = (string) $container->getAlias($notAliasedCacheClearerId);
  171. }
  172. if ($container->hasDefinition($notAliasedCacheClearerId)) {
  173. $clearers[$notAliasedCacheClearerId] = $allPools;
  174. }
  175. foreach ($clearers as $id => $pools) {
  176. $clearer = $container->getDefinition($id);
  177. if ($clearer instanceof ChildDefinition) {
  178. $clearer->replaceArgument(0, $pools);
  179. } else {
  180. $clearer->setArgument(0, $pools);
  181. }
  182. $clearer->addTag('cache.pool.clearer');
  183. }
  184. $allPoolsKeys = array_keys($allPools);
  185. if ($container->hasDefinition('console.command.cache_pool_list')) {
  186. $container->getDefinition('console.command.cache_pool_list')->replaceArgument(0, $allPoolsKeys);
  187. }
  188. if ($container->hasDefinition('console.command.cache_pool_clear')) {
  189. $container->getDefinition('console.command.cache_pool_clear')->addArgument($allPoolsKeys);
  190. }
  191. if ($container->hasDefinition('console.command.cache_pool_delete')) {
  192. $container->getDefinition('console.command.cache_pool_delete')->addArgument($allPoolsKeys);
  193. }
  194. }
  195. private function getNamespace(string $seed, string $id): string
  196. {
  197. return substr(str_replace('/', '-', base64_encode(hash('xxh128', $id.$seed, true))), 0, 10);
  198. }
  199. /**
  200. * @internal
  201. */
  202. public static function getServiceProvider(ContainerBuilder $container, string $name): string
  203. {
  204. $container->resolveEnvPlaceholders($name, null, $usedEnvs);
  205. if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) {
  206. $dsn = $name;
  207. if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) {
  208. $definition = new Definition(AbstractAdapter::class);
  209. $definition->setFactory([AbstractAdapter::class, 'createConnection']);
  210. $definition->setArguments([$dsn, ['lazy' => true]]);
  211. $container->setDefinition($name, $definition);
  212. }
  213. }
  214. return $name;
  215. }
  216. }