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