BackendCompilerPass.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\Core\DependencyInjection\Compiler;
  3. use Symfony\Component\DependencyInjection\Alias;
  4. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  5. use Symfony\Component\DependencyInjection\ContainerBuilder;
  6. /**
  7. * Defines a compiler pass to allow automatic override per backend.
  8. *
  9. * A module developer has to tag his backend service with "backend_overridable":
  10. * @code
  11. * custom_service:
  12. * class: ...
  13. * tags:
  14. * - { name: backend_overridable }
  15. * @endcode
  16. *
  17. * As a site admin you set the 'default_backend' in your services.yml file:
  18. * @code
  19. * parameters:
  20. * default_backend: sqlite
  21. * @endcode
  22. *
  23. * As a developer for alternative storage engines you register a service with
  24. * $yourbackend.$original_service:
  25. *
  26. * @code
  27. * sqlite.custom_service:
  28. * class: ...
  29. * @endcode
  30. */
  31. class BackendCompilerPass implements CompilerPassInterface {
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function process(ContainerBuilder $container) {
  36. if ($container->hasParameter('default_backend')) {
  37. $default_backend = $container->getParameter('default_backend');
  38. // Opt out from the default backend.
  39. if (!$default_backend) {
  40. return;
  41. }
  42. }
  43. else {
  44. try {
  45. $default_backend = $container->get('database')->driver();
  46. $container->set('database', NULL);
  47. }
  48. catch (\Exception $e) {
  49. // If Drupal is not installed or a test doesn't define database there
  50. // is nothing to override.
  51. return;
  52. }
  53. }
  54. foreach ($container->findTaggedServiceIds('backend_overridable') as $id => $attributes) {
  55. // If the service is already an alias it is not the original backend, so
  56. // we don't want to fallback to other storages any longer.
  57. if ($container->hasAlias($id)) {
  58. continue;
  59. }
  60. if ($container->hasDefinition("$default_backend.$id") || $container->hasAlias("$default_backend.$id")) {
  61. $container->setAlias($id, new Alias("$default_backend.$id"));
  62. }
  63. }
  64. }
  65. }