Completed
Push — dev ( 070006...d86ef5 )
by Андрей
02:18
created

DoctrineOrmModuleConfig::getModuleOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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
     * DoctrineOrmModuleConfig constructor.
51
     *
52
     * @param array                  $doctrineConfig
53
     * @param ModuleOptionsInterface $moduleOptions
54
     */
55
    public function __construct(array $doctrineConfig = [], ModuleOptionsInterface $moduleOptions)
56
    {
57
        $this->setDoctrineConfig($doctrineConfig);
58
        $this->setModuleOptions($moduleOptions);
59
    }
60
61
62
    /**
63
     * Возвращает конфигурацию доктрины.
64
     *
65
     * @return array
66
     */
67
    public function getDoctrineConfig()
68
    {
69
        return $this->doctrineConfig;
70
    }
71
72
    /**
73
     * Устанавливает конфигурацию доктрины.
74
     *
75
     * @param array $doctrineConfig
76
     *
77
     * @return $this
78
     */
79
    public function setDoctrineConfig(array $doctrineConfig = [])
80
    {
81
        $this->doctrineConfig = $doctrineConfig;
82
83
        return $this;
84
    }
85
86
    /**
87
     * @inheritdoc
88
     *
89
     * @param string $objectManagerServiceName
90
     *
91
     * @return boolean
92
     */
93
    public function hasNamespacesByObjectManager($objectManagerServiceName)
94
    {
95
        if (array_key_exists($objectManagerServiceName, $this->namespacesByObjectManagerCache)) {
96
            return false !== $this->namespacesByObjectManagerCache[$objectManagerServiceName];
97
        }
98
99
        if (!$this->isValidDoctrineOrmModuleConfig()) {
100
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
101
            return false;
102
        }
103
104
        if (0 !== strpos($objectManagerServiceName, static::DOCTRINE_PREFIX)) {
105
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
106
            return false;
107
        }
108
109
        $objectManagerName = substr($objectManagerServiceName, 23);
110
111
        $doctrineConfig = $this->getDoctrineConfig();
112
113
        if (!array_key_exists($objectManagerName, $doctrineConfig['entitymanager'])) {
114
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
115
            return false;
116
        }
117
118
        $omConfig = $doctrineConfig['entitymanager'][$objectManagerName];
119
120
        if (!is_array($omConfig) || !array_key_exists('configuration', $omConfig) || !is_string($omConfig['configuration'])) {
121
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
122
            return false;
123
        }
124
125
        $confName = $omConfig['configuration'];
126
127 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...
128
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
129
            return false;
130
        }
131
132
        $omConfiguration = $doctrineConfig['configuration'][$confName];
133
134
        if (!array_key_exists('driver', $omConfiguration) || !is_string($omConfiguration['driver'])) {
135
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
136
            return false;
137
        }
138
139
        $driverName = $omConfiguration['driver'];
140
141 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...
142
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
143
            return false;
144
        }
145
146
        $driverConfig = $doctrineConfig['driver'][$driverName];
147
148 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...
149
            $this->namespacesByObjectManagerCache[$objectManagerServiceName] = false;
150
            return false;
151
        }
152
153
        $this->namespacesByObjectManagerCache[$objectManagerServiceName] = $this->buildIndexNamespaces($driverConfig['drivers']);
154
155
        return false !== $this->namespacesByObjectManagerCache[$objectManagerServiceName];
156
    }
157
158
    /**
159
     * На основе секции drivers, для драйвера EntityManager'a doctrine строит индекс для работы с неймспейсами.
160
     *
161
     * Ключем явлеятся тот же ключ что и в $drivers, а значением часть неймспейса в котором распологаются все сущности модуля
162
     *
163
     * @param $drivers
164
     *
165
     * @return array
166
     */
167
    public function buildIndexNamespaces($drivers)
168
    {
169
        $listNamespaces = array_keys($drivers);
170
171
        $moduleOptions = $this->getModuleOptions();
172
        $entitySeparator = $moduleOptions->getEntitySeparator();
173
174
        $index = [];
175
        foreach ($listNamespaces as $currentNamespace) {
176
            $prepareNamespace = rtrim($currentNamespace, '\\');
177
            $normalizeNamespace = $prepareNamespace . '\\';
178
179
            $normalizeNamespaceStack = explode($entitySeparator, $normalizeNamespace);
180
181
            $namespacePrefix = array_shift($normalizeNamespaceStack);
182
            $index[$currentNamespace] = $namespacePrefix . $entitySeparator;
183
        }
184
185
        return $index;
186
    }
187
188
    /**
189
     * @inheritdoc
190
     *
191
     * @param $objectManagerServiceName
192
     *
193
     * @return array
194
     *
195
     * @throws Exception\EntityNamespacesNotFoundException
196
     */
197
    public function getNamespacesIndexByObjectManagerName($objectManagerServiceName)
198
    {
199
        if (false === $this->hasNamespacesByObjectManager($objectManagerServiceName)) {
200
            $errMsh = sprintf('Entity namespaces not found for: %s', $objectManagerServiceName);
201
            throw new Exception\EntityNamespacesNotFoundException($errMsh);
202
        }
203
204
        return $this->namespacesByObjectManagerCache[$objectManagerServiceName];
205
    }
206
207
    /**
208
     * Проверяет является ли структура конфига модуля DoctrineORMModule, подходящей для того что бы получить список
209
     * неймспейсов в которых распологаются сущности для работы заданного ObjectManager'a
210
     *
211
     * @return bool
212
     */
213
    public function isValidDoctrineOrmModuleConfig()
214
    {
215
        $doctrineConfig = $this->getDoctrineConfig();
216
217
        return array_key_exists('entitymanager', $doctrineConfig) && is_array($doctrineConfig['entitymanager'])
218
               && array_key_exists('configuration', $doctrineConfig) && is_array($doctrineConfig['configuration'])
219
               && array_key_exists('driver', $doctrineConfig) && is_array($doctrineConfig['driver']);
220
    }
221
222
    /**
223
     * Возвращает опции модуля
224
     *
225
     * @return ModuleOptionsInterface
226
     */
227
    public function getModuleOptions()
228
    {
229
        return $this->moduleOptions;
230
    }
231
232
    /**
233
     * Устанавливает опции модуля
234
     *
235
     * @param ModuleOptionsInterface $moduleOptions
236
     *
237
     * @return $this
238
     */
239
    public function setModuleOptions(ModuleOptionsInterface $moduleOptions)
240
    {
241
        $this->moduleOptions = $moduleOptions;
242
243
        return $this;
244
    }
245
}
246