TestServiceProvider.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Drupal\KernelTests;
  3. use Drupal\Core\DependencyInjection\ContainerBuilder;
  4. use Drupal\Core\DependencyInjection\ServiceModifierInterface;
  5. use Drupal\Core\DependencyInjection\ServiceProviderInterface;
  6. use Symfony\Component\DependencyInjection\Definition;
  7. /**
  8. * Provides special routing services for tests.
  9. */
  10. class TestServiceProvider implements ServiceProviderInterface, ServiceModifierInterface {
  11. /**
  12. * @var \Drupal\simpletest\TestBase
  13. */
  14. public static $currentTest;
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public function register(ContainerBuilder $container) {
  19. if (static::$currentTest && method_exists(static::$currentTest, 'containerBuild')) {
  20. static::$currentTest->containerBuild($container);
  21. }
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function alter(ContainerBuilder $container) {
  27. if (static::$currentTest instanceof KernelTestBase) {
  28. static::addRouteProvider($container);
  29. }
  30. }
  31. /**
  32. * Add the on demand rebuild route provider service.
  33. *
  34. * @param \Drupal\Core\DependencyInjection\ContainerBuilder $container
  35. */
  36. public static function addRouteProvider(ContainerBuilder $container) {
  37. $route_provider_service_name = 'router.route_provider';
  38. // While $container->get() does a recursive resolve, getDefinition() does
  39. // not, so do it ourselves.
  40. $id = $route_provider_service_name;
  41. while ($container->hasAlias($id)) {
  42. $id = (string) $container->getAlias($id);
  43. }
  44. $definition = $container->getDefinition($id);
  45. $definition->clearTag('needs_destruction');
  46. $container->setDefinition("simpletest.$route_provider_service_name", $definition);
  47. $container->setDefinition($id, new Definition(RouteProvider::class));
  48. }
  49. }