Completed
Push — master ( 9c0fcf...cbcb64 )
by Tobias
05:38
created

HappyrSimpleBusExtension::load()   C

Complexity

Conditions 8
Paths 45

Size

Total Lines 52
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 36
cts 36
cp 1
rs 6.8493
c 0
b 0
f 0
cc 8
eloc 35
nc 45
nop 2
crap 8

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        $container->setParameter('happyr.simplebus.direct_publisher', $config['use_direct_publisher']);
41 1
        if ($config['auto_register_handlers']['enabled']) {
42 1
            $handlerPath = $config['auto_register_handlers']['command_handler_path'];
43 1
            if (empty($handlerPath)) {
44 1
                $rootDir = $container->getParameter('kernel.root_dir');
45 1
                $handlerPath = $rootDir.'/../src/App/Message/CommandHandler';
46
            }
47
48 1
            $commandNamespace = $config['auto_register_handlers']['command_namespace'];
49 1
            if (empty($commandNamespace)) {
50 1
                $commandNamespace = 'App\\Message\\Command';
51
            }
52
53 1
            $handlerNamespace = $config['auto_register_handlers']['command_handler_namespace'];
54 1
            if (empty($handlerNamespace)) {
55 1
                $handlerNamespace = 'App\\Message\\CommandHandler';
56
            }
57
58 1
            $this->autoRegisterCommands($container, $commandNamespace, $handlerNamespace, $handlerPath);
59
        }
60
61 1
        if ($config['auto_register_event_subscribers']['enabled']) {
62 1
            $path = $config['auto_register_event_subscribers']['event_subscriber_path'];
63 1
            if (empty($path)) {
64 1
                $rootDir = $container->getParameter('kernel.root_dir');
65 1
                $path = $rootDir.'/../src/App/Message/EventSubscriber';
66
            }
67
68 1
            $namespace = $config['auto_register_event_subscribers']['event_subscriber_namespace'];
69 1
            if (empty($namespace)) {
70 1
                $namespace = 'App\\Message\\EventSubscriber';
71
            }
72
73 1
            $this->autoRegisterEventSubscribers($container, $namespace, $path);
74
        }
75 1
    }
76
77
    /**
78
     * @param ContainerBuilder $container
79
     * @param string           $commandNamespace
80
     * @param string           $handlerNamespace
81
     * @param string           $handlerPath
82
     */
83 1
    protected function autoRegisterCommands(ContainerBuilder $container, $commandNamespace, $handlerNamespace, $handlerPath)
84
    {
85
        // Make sure it ends with slash
86 1
        $commandNamespace = rtrim($commandNamespace, '\\').'\\';
87 1
        $handlerNamespace = rtrim($handlerNamespace, '\\').'\\';
88
89 1
        $finder = new Finder();
90
        try {
91 1
            $finder->files()->in($handlerPath)->name('*Handler.php');
92 1
        } catch (\InvalidArgumentException $e) {
93 1
            return;
94
        }
95
96
        foreach ($finder as $file) {
97
            $handlerClassName = $file->getBasename('.php');
98
            $commandClassName = $file->getBasename('Handler.php');
99
100
            $dynamicContainerId = '';
101
            $dynamicFQN = '';
102
            $path = $file->getRelativePath();
103 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...
104
                $dynamicFQN = str_replace('/', '\\', $path).'\\';
105
                $dynamicContainerId = str_replace('/', '.', $path).'.';
106
            }
107
108
            $commandFQN = $commandNamespace.$dynamicFQN.$commandClassName;
109
            $handlerFQN = $handlerNamespace.$dynamicFQN.$handlerClassName;
110
111
            $containerId = strtolower(sprintf('command_handler.%s%s.auto', $dynamicContainerId, ltrim(preg_replace('/[A-Z]/', '_$0', $commandClassName), '_')));
112
113
            $def = new Definition($handlerFQN);
114
            $def->setAutowired(true);
115
116
            $tag = 'command_handler';
117
            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...
118
                $tag = 'asynchronous_command_handler';
119
            }
120
121
            $def->addTag($tag, ['handles' => $commandFQN]);
122
            $container->setDefinition($containerId, $def);
123
        }
124
    }
125
126
    /**
127
     * @param ContainerBuilder $container
128
     * @param string           $subscriberNamespace
129
     * @param string           $subscriberPath
130
     */
131 1
    protected function autoRegisterEventSubscribers(ContainerBuilder $container, $subscriberNamespace, $subscriberPath)
132
    {
133
        // Make sure it ends with slash
134 1
        $subscriberNamespace = rtrim($subscriberNamespace, '\\').'\\';
135
136 1
        $finder = new Finder();
137
        try {
138 1
            $finder->files()->in($subscriberPath)->name('*.php');
139 1
        } catch (\InvalidArgumentException $e) {
140 1
            return;
141
        }
142
143
        foreach ($finder as $file) {
144
            $subscriberClassName = $file->getBasename('.php');
145
146
            $dynamicContainerId = '';
147
            $dynamicFQN = '';
148
            $path = $file->getRelativePath();
149 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...
150
                $dynamicFQN = str_replace('/', '\\', $path).'\\';
151
                $dynamicContainerId = str_replace('/', '.', $path).'.';
152
            }
153
154
            $subscriberFQN = $subscriberNamespace.$dynamicFQN.$subscriberClassName;
155
            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...
156
                continue;
157
            }
158
159
            if (!method_exists($subscriberFQN, 'notify')) {
160
                throw new \LogicException(sprintf('An event subscriber that implements AutoRegisteredEventSubscriber must have a function called notify. Please add one in "%s"', $subscriberFQN));
161
            }
162
163
            $containerId = strtolower(sprintf('event_subscriber.%s%s.auto', $dynamicContainerId, ltrim(preg_replace('/[A-Z]/', '_$0', $subscriberClassName), '_')));
164
            $def = new Definition($subscriberFQN);
165
            $def->setAutowired(true);
166
167
            $tag = 'event_subscriber';
168
            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...
169
                $tag = 'asynchronous_event_subscriber';
170
            }
171
172
            $def->addTag($tag, ['subscribes_to' => call_user_func($subscriberFQN.'::subscribesTo')]);
173
            $container->setDefinition($containerId, $def);
174
        }
175
    }
176
177
    /**
178
     * Make sure we have activated the required bundles.
179
     *
180
     * @param $bundleName
181
     * @param ContainerBuilder $container
182
     */
183 1
    private function requireBundle($bundleName, ContainerBuilder $container)
184
    {
185 1
        $enabledBundles = $container->getParameter('kernel.bundles');
186 1
        if (!isset($enabledBundles[$bundleName])) {
187
            throw new \LogicException(sprintf('You need to enable "%s" as well', $bundleName));
188
        }
189 1
    }
190
191 1
    public function getAlias()
192
    {
193 1
        return 'happyr_simplebus';
194
    }
195
}
196