CachePoolPass.php 9.9 KB

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