Completed
Push — master ( 4b7d76...9c0fcf )
by Tobias
12:59 queued 09:16
created

HappyrSimpleBusExtension::getAlias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Happyr\SimpleBusBundle\DependencyInjection;
4
5
use Happyr\SimpleBusBundle\Message\AutoRegisteredEventSubscriber;
6
use Happyr\SimpleBusBundle\Message\HandlesMessagesAsync;
7
use Symfony\Component\DependencyInjection\ContainerBuilder;
8
use Symfony\Component\Config\FileLocator;
9
use Symfony\Component\DependencyInjection\Definition;
10
use Symfony\Component\Finder\Finder;
11
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
12
use Symfony\Component\DependencyInjection\Loader;
13
14
/**
15
 * This is the class that loads and manages your bundle configuration.
16
 *
17
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
18
 */
19
class HappyrSimpleBusExtension extends Extension
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24 1
    public function load(array $configs, ContainerBuilder $container)
25
    {
26 1
        $configuration = new Configuration();
27 1
        $config = $this->processConfiguration($configuration, $configs);
28
29 1
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
30 1
        $loader->load('ping.yml');
31 1
        $this->requireBundle('SimpleBusCommandBusBundle', $container);
32 1
        $this->requireBundle('SimpleBusEventBusBundle', $container);
33 1
        $this->requireBundle('SimpleBusAsynchronousBundle', $container);
34 1
        $this->requireBundle('SimpleBusRabbitMQBundleBridgeBundle', $container);
35 1
        $this->requireBundle('SimpleBusJMSSerializerBundleBridgeBundle', $container);
36 1
        $this->requireBundle('HappyrMq2phpBundle', $container);
37 1
        $this->requireBundle('OldSoundRabbitMqBundle', $container);
38 1
        $this->requireBundle('JMSSerializerBundle', $container);
39
40 1
        if ($config['auto_register_handlers']['enabled']) {
41 1
            $handlerPath = $config['auto_register_handlers']['command_handler_path'];
42 1
            if (empty($handlerPath)) {
43 1
                $rootDir = $container->getParameter('kernel.root_dir');
44 1
                $handlerPath = $rootDir.'/../src/App/Message/CommandHandler';
45
            }
46
47 1
            $commandNamespace = $config['auto_register_handlers']['command_namespace'];
48 1
            if (empty($commandNamespace)) {
49 1
                $commandNamespace = 'App\\Message\\Command';
50
            }
51
52 1
            $handlerNamespace = $config['auto_register_handlers']['command_handler_namespace'];
53 1
            if (empty($handlerNamespace)) {
54 1
                $handlerNamespace = 'App\\Message\\CommandHandler';
55
            }
56
57 1
            $this->autoRegisterCommands($container, $commandNamespace, $handlerNamespace, $handlerPath);
58
        }
59
60 1
        if ($config['auto_register_event_subscribers']['enabled']) {
61 1
            $path = $config['auto_register_event_subscribers']['event_subscriber_path'];
62 1
            if (empty($path)) {
63 1
                $rootDir = $container->getParameter('kernel.root_dir');
64 1
                $path = $rootDir.'/../src/App/Message/EventSubscriber';
65
            }
66
67 1
            $namespace = $config['auto_register_event_subscribers']['event_subscriber_namespace'];
68 1
            if (empty($namespace)) {
69 1
                $namespace = 'App\\Message\\EventSubscriber';
70
            }
71
72 1
            $this->autoRegisterEventSubscribers($container, $namespace, $path);
73
        }
74 1
    }
75
76
    /**
77
     * @param ContainerBuilder $container
78
     * @param string           $commandNamespace
79
     * @param string           $handlerNamespace
80
     * @param string           $handlerPath
81
     */
82 1
    protected function autoRegisterCommands(ContainerBuilder $container, $commandNamespace, $handlerNamespace, $handlerPath)
83
    {
84
        // Make sure it ends with slash
85 1
        $commandNamespace = rtrim($commandNamespace, '\\').'\\';
86 1
        $handlerNamespace = rtrim($handlerNamespace, '\\').'\\';
87
88 1
        $finder = new Finder();
89
        try {
90 1
            $finder->files()->in($handlerPath)->name('*Handler.php');
91 1
        } catch (\InvalidArgumentException $e) {
92 1
            return;
93
        }
94
95
        foreach ($finder as $file) {
96
            $handlerClassName = $file->getBasename('.php');
97
            $commandClassName = $file->getBasename('Handler.php');
98
99
            $dynamicContainerId = '';
100
            $dynamicFQN = '';
101
            $path = $file->getRelativePath();
102 View Code Duplication
            if (!empty($path)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
                $dynamicFQN = str_replace('/', '\\', $path).'\\';
104
                $dynamicContainerId = str_replace('/', '.', $path).'.';
105
            }
106
107
            $commandFQN = $commandNamespace.$dynamicFQN.$commandClassName;
108
            $handlerFQN = $handlerNamespace.$dynamicFQN.$handlerClassName;
109
110
            $containerId = strtolower(sprintf('command_handler.%s%s.auto', $dynamicContainerId, ltrim(preg_replace('/[A-Z]/', '_$0', $commandClassName), '_')));
111
112
            $def = new Definition($handlerFQN);
113
            $def->setAutowired(true);
114
115
            $tag = 'command_handler';
116
            if (is_subclass_of($handlerFQN, HandlesMessagesAsync::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Happyr\SimpleBusBundle\...lesMessagesAsync::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
117
                $tag = 'asynchronous_command_handler';
118
            }
119
120
            $def->addTag($tag, ['handles' => $commandFQN]);
121
            $container->setDefinition($containerId, $def);
122
        }
123
    }
124
125
    /**
126
     * @param ContainerBuilder $container
127
     * @param string           $subscriberNamespace
128
     * @param string           $subscriberPath
129
     */
130 1
    protected function autoRegisterEventSubscribers(ContainerBuilder $container, $subscriberNamespace, $subscriberPath)
131
    {
132
        // Make sure it ends with slash
133 1
        $subscriberNamespace = rtrim($subscriberNamespace, '\\').'\\';
134
135 1
        $finder = new Finder();
136
        try {
137 1
            $finder->files()->in($subscriberPath)->name('*.php');
138 1
        } catch (\InvalidArgumentException $e) {
139 1
            return;
140
        }
141
142
        foreach ($finder as $file) {
143
            $subscriberClassName = $file->getBasename('.php');
144
145
            $dynamicContainerId = '';
146
            $dynamicFQN = '';
147
            $path = $file->getRelativePath();
148 View Code Duplication
            if (!empty($path)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149
                $dynamicFQN = str_replace('/', '\\', $path).'\\';
150
                $dynamicContainerId = str_replace('/', '.', $path).'.';
151
            }
152
153
            $subscriberFQN = $subscriberNamespace.$dynamicFQN.$subscriberClassName;
154
            if (!is_subclass_of($subscriberFQN, AutoRegisteredEventSubscriber::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Happyr\SimpleBusBundle\...dEventSubscriber::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
155
                continue;
156
            }
157
158
            if (!method_exists($subscriberFQN, 'notify')) {
159
                throw new \LogicException(sprintf('An event subscriber that implements AutoRegisteredEventSubscriber must have a function called notify. Please add one in "%s"', $subscriberFQN));
160
            }
161
162
            $containerId = strtolower(sprintf('event_subscriber.%s%s.auto', $dynamicContainerId, ltrim(preg_replace('/[A-Z]/', '_$0', $subscriberClassName), '_')));
163
            $def = new Definition($subscriberFQN);
164
            $def->setAutowired(true);
165
166
            $tag = 'event_subscriber';
167
            if (is_subclass_of($subscriberFQN, HandlesMessagesAsync::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Happyr\SimpleBusBundle\...lesMessagesAsync::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
168
                $tag = 'asynchronous_event_subscriber';
169
            }
170
171
            $def->addTag($tag, ['subscribes_to' => call_user_func($subscriberFQN.'::subscribesTo')]);
172
            $container->setDefinition($containerId, $def);
173
        }
174
    }
175
176
    /**
177
     * Make sure we have activated the required bundles.
178
     *
179
     * @param $bundleName
180
     * @param ContainerBuilder $container
181
     */
182 1
    private function requireBundle($bundleName, ContainerBuilder $container)
183
    {
184 1
        $enabledBundles = $container->getParameter('kernel.bundles');
185 1
        if (!isset($enabledBundles[$bundleName])) {
186
            throw new \LogicException(sprintf('You need to enable "%s" as well', $bundleName));
187
        }
188 1
    }
189
190 1
    public function getAlias()
191
    {
192 1
        return 'happyr_simplebus';
193
    }
194
}
195