Completed
Push — master ( af7081...8b532e )
by Андрей
05:28 queued 03:12
created

hasNamespacesByObjectManager()   C

Complexity

Conditions 16
Paths 10

Size

Total Lines 64
Code Lines 36

Duplication

Lines 12
Ratio 18.75 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 12
loc 64
rs 5.9894
cc 16
eloc 36
nc 10
nop 1

How to fix   Long Method    Complexity   

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
 * @link    https://github.com/nnx-framework/doctrine
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace Nnx\Doctrine\Utils;
7
8
use Nnx\Doctrine\Options\ModuleOptionsInterface;
9
10
/**
11
 * Class DoctrineOrmModuleConfig
12
 *
13
 * @package Nnx\Doctrine\Utils
14
 */
15
class DoctrineOrmModuleConfig implements DoctrineOrmModuleConfigInterface
16
{
17
    /**
18
     * Префикс, с которого начинается имя сервиса, для получения ObjectManager'a доктрины
19
     *
20
     * @var string
21
     */
22
    const DOCTRINE_PREFIX = 'doctrine.entitymanager.';
23
24
    /**
25
     * Конфигурация доктрины.
26
     *
27
     * @see https://github.com/doctrine/DoctrineORMModule/blob/0.10.0/config/module.config.php
28
     *
29
     * @var array
30
     */
31
    protected $doctrineConfig = [];
32
33
    /**
34
     * Ключем является имя ObjectManager'a значением либо массив содержащий имена неймспейсов в которых расположены
35
     * сущности данного ObjectManager, либо false, в случае если для данного ObjectManager невозможно получить список
36
     * неймспейсов
37
     *
38
     * @var array
39
     */
40
    protected $namespacesByObjectManagerCache = [];
41
42
    /**
43
     * Опции модуля
44
     *
45
     * @var ModuleOptionsInterface
46
     */
47
    protected $moduleOptions;
48
49
    /**
50
     * Список имен ObjectManager'ов
51
     *
52
     * @var array|null
53
     */
54
    protected $listObjectManagerName;
55
56
    /**
57
     * DoctrineOrmModuleConfig constructor.
58
     *
59
     * @param array                  $doctrineConfig
60
     * @param ModuleOptionsInterface $moduleOptions
61
     */
62
    public function __construct(array $doctrineConfig = [], ModuleOptionsInterface $moduleOptions)
63
    {
64
        $this->setDoctrineConfig($doctrineConfig);
65
        $this->setModuleOptions($moduleOptions);
66
    }
67
68
69
    /**
70
     * Возвращает конфигурацию доктрины.
71
     *
72
     * @return array
73
     */
74
    public function getDoctrineConfig()
75
    {
76
        return $this->doctrineConfig;
77
    }
78
79
    /**
80
     * Устанавливает конфигурацию доктрины.
81
     *
82
     * @param array $doctrineConfig
83
     *
84
     * @return $this
85
     */
86
    public function setDoctrineConfig(array $doctrineConfig = [])
87
    {
88
        $this->doctrineConfig = $doctrineConfig;
89
90
        return $this;
91
    }
92
93
    /**
94
     * Список ObjectManager'ов декларированных в настройках модуля DoctrineOrmModule
95
     *
96
     * @return array
97
     */
98
    public function getListObjectManagerName()
99
    {
100
        if ($this->listObjectManagerName) {
101
            return $this->listObjectManagerName;
102
        }
103
104
        if (!$this->isValidDoctrineOrmModuleEntityManagerConfig()) {
105
            $this->listObjectManagerName = [];
106
            return $this->listObjectManagerName;
107
        }
108
109
        $doctrineConfig = $this->getDoctrineConfig();
110
111
        $listObjectManagerName = array_keys($doctrineConfig['entitymanager']);
112
        $prepareListObjectManagerName = array_map(function ($objectManagerName) {
113
            return 'doctrine.entitymanager.' . $objectManagerName;
114
        }, $listObjectManagerName);
115
116
        $this->listObjectManagerName = array_combine($listObjectManagerName, $prepareListObjectManagerName);
117
118
        return $this->listObjectManagerName;
119
    }
120
121
    /**
122
     * @inheritdoc
123
     *
124
     * @param string $objectManagerServiceName
125
     *
126
     * @return boolean
127
     */
128
    public function hasNamespacesByObjectManager($objectManagerServiceName)
129
    {
130
        if (array_key_exists($objectManagerServiceName, $this->namespacesByObjectManagerCache)) {
131
            return false !== $this->namespacesByObjectManagerCache[$objectManagerServiceName];
132
        }
133
134
        if (!$this->isValidDoctrineOrmModuleConfig()) {
135
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
136
            return false;
137
        }
138
139
        if (0 !== strpos($objectManagerServiceName, static::DOCTRINE_PREFIX)) {
140
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
141
            return false;
142
        }
143
144
        $objectManagerName = substr($objectManagerServiceName, 23);
145
146
        $doctrineConfig = $this->getDoctrineConfig();
147
148
        if (!array_key_exists($objectManagerName, $doctrineConfig['entitymanager'])) {
149
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
150
            return false;
151
        }
152
153
        $omConfig = $doctrineConfig['entitymanager'][$objectManagerName];
154
155
        if (!is_array($omConfig) || !array_key_exists('configuration', $omConfig) || !is_string($omConfig['configuration'])) {
156
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
157
            return false;
158
        }
159
160
        $confName = $omConfig['configuration'];
161
162 View Code Duplication
        if (!array_key_exists($confName, $doctrineConfig['configuration']) || !is_array($doctrineConfig['configuration'][$confName])) {
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...
163
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
164
            return false;
165
        }
166
167
        $omConfiguration = $doctrineConfig['configuration'][$confName];
168
169
        if (!array_key_exists('driver', $omConfiguration) || !is_string($omConfiguration['driver'])) {
170
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
171
            return false;
172
        }
173
174
        $driverName = $omConfiguration['driver'];
175
176 View Code Duplication
        if (!array_key_exists($driverName, $doctrineConfig['driver']) || !is_array($doctrineConfig['driver'][$driverName])) {
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...
177
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
178
            return false;
179
        }
180
181
        $driverConfig = $doctrineConfig['driver'][$driverName];
182
183 View Code Duplication
        if (!array_key_exists('drivers', $driverConfig) || !is_array($driverConfig['drivers'])) {
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...
184
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
185
            return false;
186
        }
187
188
        $this->namespacesByObjectManagerCache[$objectManagerServiceName] = $this->buildIndexNamespaces($driverConfig['drivers']);
189
190
        return false !== $this->namespacesByObjectManagerCache[$objectManagerServiceName];
191
    }
192
193
    /**
194
     * На основе секции drivers, для драйвера EntityManager'a doctrine строит индекс для работы с неймспейсами.
195
     *
196
     * Ключем явлеятся тот же ключ что и в $drivers, а значением часть неймспейса в котором распологаются все сущности модуля
197
     *
198
     * @param $drivers
199
     *
200
     * @return array
201
     */
202
    public function buildIndexNamespaces($drivers)
203
    {
204
        $listNamespaces = array_keys($drivers);
205
206
        $moduleOptions = $this->getModuleOptions();
207
        $entitySeparator = $moduleOptions->getEntitySeparator();
208
209
        $index = [];
210
        foreach ($listNamespaces as $currentNamespace) {
211
            $prepareNamespace = rtrim($currentNamespace, '\\');
212
            $normalizeNamespace = $prepareNamespace . '\\';
213
214
            $normalizeNamespaceStack = explode($entitySeparator, $normalizeNamespace);
215
216
            $namespacePrefix = array_shift($normalizeNamespaceStack);
217
            $index[$currentNamespace] = $namespacePrefix . $entitySeparator;
218
        }
219
220
        return $index;
221
    }
222
223
    /**
224
     * @inheritdoc
225
     *
226
     * @param $objectManagerServiceName
227
     *
228
     * @return array
229
     *
230
     * @throws Exception\EntityNamespacesNotFoundException
231
     */
232
    public function getNamespacesIndexByObjectManagerName($objectManagerServiceName)
233
    {
234
        if (false === $this->hasNamespacesByObjectManager($objectManagerServiceName)) {
235
            $errMsh = sprintf('Entity namespaces not found for: %s', $objectManagerServiceName);
236
            throw new Exception\EntityNamespacesNotFoundException($errMsh);
237
        }
238
239
        return $this->namespacesByObjectManagerCache[$objectManagerServiceName];
240
    }
241
242
    /**
243
     * Проверяет является ли структура конфига модуля DoctrineORMModule, подходящей для того что бы получить список
244
     * неймспейсов в которых распологаются сущности для работы заданного ObjectManager'a
245
     *
246
     * @return bool
247
     */
248
    public function isValidDoctrineOrmModuleConfig()
249
    {
250
        $doctrineConfig = $this->getDoctrineConfig();
251
252
        return $this->isValidDoctrineOrmModuleEntityManagerConfig()
253
               && array_key_exists('configuration', $doctrineConfig) && is_array($doctrineConfig['configuration'])
254
               && array_key_exists('driver', $doctrineConfig) && is_array($doctrineConfig['driver']);
255
    }
256
257
    /**
258
     * Проверяет есть ли в конфиги корректная секция описывающая настройки entitymanager
259
     *
260
     * @return bool
261
     */
262
    public function isValidDoctrineOrmModuleEntityManagerConfig()
263
    {
264
        $doctrineConfig = $this->getDoctrineConfig();
265
266
        return array_key_exists('entitymanager', $doctrineConfig) && is_array($doctrineConfig['entitymanager']);
267
    }
268
269
    /**
270
     * Возвращает опции модуля
271
     *
272
     * @return ModuleOptionsInterface
273
     */
274
    public function getModuleOptions()
275
    {
276
        return $this->moduleOptions;
277
    }
278
279
    /**
280
     * Устанавливает опции модуля
281
     *
282
     * @param ModuleOptionsInterface $moduleOptions
283
     *
284
     * @return $this
285
     */
286
    public function setModuleOptions(ModuleOptionsInterface $moduleOptions)
287
    {
288
        $this->moduleOptions = $moduleOptions;
289
290
        return $this;
291
    }
292
}
293