HappyrSimpleBusExtension   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 179
Duplicated Lines 4.47 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 56.12%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 7
dl 8
loc 179
ccs 55
cts 98
cp 0.5612
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
C load() 0 52 8
B autoRegisterCommands() 4 43 5
C autoRegisterEventSubscribers() 4 46 7
A requireBundle() 0 7 2
A getAlias() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
91
        try {
92 1
            $finder->files()->in($handlerPath)->name('*Handler.php');
93 1
        } catch (\InvalidArgumentException $e) {
94 1
            return;
95
        }
96
97
        foreach ($finder as $file) {
98
            $handlerClassName = $file->getBasename('.php');
99
            $commandClassName = $file->getBasename('Handler.php');
100
101
            $dynamicContainerId = '';
102
            $dynamicFQN = '';
103
            $path = $file->getRelativePath();
104 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...
105
                $dynamicFQN = str_replace('/', '\\', $path).'\\';
106
                $dynamicContainerId = str_replace('/', '.', $path).'.';
107
            }
108
109
            $commandFQN = $commandNamespace.$dynamicFQN.$commandClassName;
110
            $handlerFQN = $handlerNamespace.$dynamicFQN.$handlerClassName;
111
112
            $containerId = strtolower(sprintf('command_handler.%s%s.auto', $dynamicContainerId, ltrim(preg_replace('/[A-Z]/', '_$0', $commandClassName), '_')));
113
114
            $def = new Definition($handlerFQN);
115
            $def->setAutowired(true);
116
117
            $tag = 'command_handler';
118
            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...
119
                $tag = 'asynchronous_command_handler';
120
            }
121
122
            $def->addTag($tag, ['handles' => $commandFQN]);
123
            $container->setDefinition($containerId, $def);
124
        }
125
    }
126
127
    /**
128
     * @param ContainerBuilder $container
129
     * @param string           $subscriberNamespace
130
     * @param string           $subscriberPath
131
     */
132 1
    protected function autoRegisterEventSubscribers(ContainerBuilder $container, $subscriberNamespace, $subscriberPath)
133
    {
134
        // Make sure it ends with slash
135 1
        $subscriberNamespace = rtrim($subscriberNamespace, '\\').'\\';
136
137 1
        $finder = new Finder();
138
139
        try {
140 1
            $finder->files()->in($subscriberPath)->name('*.php');
141 1
        } catch (\InvalidArgumentException $e) {
142 1
            return;
143
        }
144
145
        foreach ($finder as $file) {
146
            $subscriberClassName = $file->getBasename('.php');
147
148
            $dynamicContainerId = '';
149
            $dynamicFQN = '';
150
            $path = $file->getRelativePath();
151 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...
152
                $dynamicFQN = str_replace('/', '\\', $path).'\\';
153
                $dynamicContainerId = str_replace('/', '.', $path).'.';
154
            }
155
156
            $subscriberFQN = $subscriberNamespace.$dynamicFQN.$subscriberClassName;
157
            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...
158
                continue;
159
            }
160
161
            if (!method_exists($subscriberFQN, 'notify')) {
162
                throw new \LogicException(sprintf('An event subscriber that implements AutoRegisteredEventSubscriber must have a function called notify. Please add one in "%s"', $subscriberFQN));
163
            }
164
165
            $containerId = strtolower(sprintf('event_subscriber.%s%s.auto', $dynamicContainerId, ltrim(preg_replace('/[A-Z]/', '_$0', $subscriberClassName), '_')));
166
            $def = new Definition($subscriberFQN);
167
            $def->setAutowired(true);
168
169
            $tag = 'event_subscriber';
170
            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...
171
                $tag = 'asynchronous_event_subscriber';
172
            }
173
174
            $def->addTag($tag, ['subscribes_to' => call_user_func($subscriberFQN.'::subscribesTo')]);
175
            $container->setDefinition($containerId, $def);
176
        }
177
    }
178
179
    /**
180
     * Make sure we have activated the required bundles.
181
     *
182
     * @param $bundleName
183
     * @param ContainerBuilder $container
184
     */
185 1
    private function requireBundle($bundleName, ContainerBuilder $container)
186
    {
187 1
        $enabledBundles = $container->getParameter('kernel.bundles');
188 1
        if (!isset($enabledBundles[$bundleName])) {
189
            throw new \LogicException(sprintf('You need to enable "%s" as well', $bundleName));
190
        }
191 1
    }
192
193 1
    public function getAlias()
194
    {
195 1
        return 'happyr_simplebus';
196
    }
197
}
198