CacheContextsPass.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Symfony\Component\DependencyInjection\ContainerBuilder;
  4. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  5. /**
  6. * Adds cache_contexts parameter to the container.
  7. */
  8. class CacheContextsPass implements CompilerPassInterface {
  9. /**
  10. * Implements CompilerPassInterface::process().
  11. *
  12. * Collects the cache contexts into the cache_contexts parameter.
  13. */
  14. public function process(ContainerBuilder $container) {
  15. $cache_contexts = [];
  16. foreach (array_keys($container->findTaggedServiceIds('cache.context')) as $id) {
  17. if (strpos($id, 'cache_context.') !== 0) {
  18. throw new \InvalidArgumentException(sprintf('The service "%s" has an invalid service ID: cache context service IDs must use the "cache_context." prefix. (The suffix is the cache context ID developers may use.)', $id));
  19. }
  20. $cache_contexts[] = substr($id, 14);
  21. }
  22. // Validate.
  23. sort($cache_contexts);
  24. foreach ($cache_contexts as $id) {
  25. // Validate the hierarchy of non-root-level cache contexts.
  26. if (strpos($id, '.') !== FALSE) {
  27. $parent = substr($id, 0, strrpos($id, '.'));
  28. if (!in_array($parent, $cache_contexts)) {
  29. throw new \InvalidArgumentException(sprintf('The service "%s" has an invalid service ID: the period indicates the hierarchy of cache contexts, therefore "%s" is considered the parent cache context, but no cache context service with that name was found.', $id, $parent));
  30. }
  31. }
  32. }
  33. $container->setParameter('cache_contexts', $cache_contexts);
  34. }
  35. }