canCreateServiceWithName()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
rs 8.9197
cc 4
eloc 12
nc 6
nop 3
1
<?php
2
/**
3
 * @link    https://github.com/nnx-framework/doctrine
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace Nnx\Doctrine\EntityManager;
7
8
use Zend\ServiceManager\AbstractFactoryInterface;
9
use Zend\ServiceManager\AbstractPluginManager;
10
use Zend\ServiceManager\ServiceLocatorInterface;
11
use Nnx\Doctrine\Options\ModuleOptionsInterface;
12
use Nnx\ModuleOptions\ModuleOptionsPluginManagerInterface;
13
use Nnx\Doctrine\Utils\DoctrineOrmModuleConfigInterface;
14
use Nnx\Doctrine\Utils\EntityMapCacheInterface;
15
use ReflectionClass;
16
17
/**
18
 * Class OrmAbstractFactory
19
 *
20
 * @package Nnx\Doctrine\EntityManager
21
 */
22
class EntityMapAbstractFactory implements AbstractFactoryInterface
23
{
24
25
    /**
26
     * Ключем является имя интерфейса сущности, а значением объект прототип, либо false
27
     *
28
     * @var array
29
     */
30
    protected $prototype = [];
31
32
    /**
33
     * Флаг определяет была ли инициированна фабрика
34
     *
35
     * @var bool
36
     */
37
    protected $isInit = false;
38
39
    /**
40
     * Настройки модуля
41
     *
42
     * @var ModuleOptionsInterface
43
     */
44
    protected $moduleOptions;
45
46
    /**
47
     * Ключем является имя objectManager'a, а значением карта сущностей для него
48
     *
49
     * @var array
50
     */
51
    protected $objectManagerToEntityMap = [];
52
53
    /**
54
     * Колличество ObjectManagers для которых есть EntityMap
55
     *
56
     * @var int
57
     */
58
    protected $countObjectManagers = 0;
59
60
    /**
61
     * В случае если EntityMap есть только для одного ObjectManager, то данное свойство будет содержать эту EntityMap
62
     *
63
     * @var array
64
     */
65
    protected $baseEntityMap = [];
66
67
    /**
68
     * Ключем является имя интерфейса,  а значением имя класса сущности
69
     *
70
     * @var array
71
     */
72
    protected $interfaceNameToClassName = [];
73
74
    /**
75
     * @inheritdoc
76
     *
77
     * @param ServiceLocatorInterface $serviceLocator
78
     * @param                         $name
79
     * @param                         $requestedName
80
     *
81
     * @return boolean
82
     *
83
     * @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
84
     * @throws  Exception\ErrorBuildEntityMapCacheException
85
     */
86
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
87
    {
88
        $appServiceLocator = $serviceLocator;
89
        if ($serviceLocator instanceof AbstractPluginManager) {
90
            $appServiceLocator = $serviceLocator->getServiceLocator();
91
        }
92
        /** @var ModuleOptionsPluginManagerInterface $moduleOptionsManager */
93
        $moduleOptionsManager = $appServiceLocator->get(ModuleOptionsPluginManagerInterface::class);
94
        /** @var ModuleOptionsInterface $moduleOptions */
95
        $moduleOptions = $moduleOptionsManager->get(ModuleOptionsInterface::class);
96
97
        if ($moduleOptions->getFlagDisableUseEntityMapDoctrineCache()) {
98
            return false;
99
        }
100
101
        $this->init($serviceLocator);
102
        if (array_key_exists($requestedName, $this->prototype)) {
103
            return false !== $this->prototype[$requestedName];
104
        }
105
106
        return false !== $this->getClassNameByInterface($requestedName);
107
    }
108
109
    /**
110
     * Попытка получить имя класса, на оснве интерфейса
111
     *
112
     * @param $interfaceName
113
     *
114
     * @return string|false
115
     */
116
    protected function getClassNameByInterface($interfaceName)
117
    {
118
        if (array_key_exists($interfaceName, $this->interfaceNameToClassName)) {
119
            return $this->interfaceNameToClassName[$interfaceName];
120
        }
121
122
        if (0 === $this->countObjectManagers) {
123
            $this->interfaceNameToClassName[$interfaceName] = false;
124
            return false;
125
        } elseif (1 === $this->countObjectManagers) {
126
            $this->interfaceNameToClassName[$interfaceName] = array_key_exists($interfaceName, $this->baseEntityMap) ? $this->baseEntityMap[$interfaceName] : false;
127
            return $this->interfaceNameToClassName[$interfaceName];
128
        }
129
130
        foreach ($this->objectManagerToEntityMap as $entityMap) {
131
            if (array_key_exists($interfaceName, $entityMap)) {
132
                $this->interfaceNameToClassName[$interfaceName] = $entityMap[$interfaceName];
133
                return $this->interfaceNameToClassName[$interfaceName];
134
            }
135
        }
136
        $this->interfaceNameToClassName[$interfaceName] = false;
137
        return $this->interfaceNameToClassName[$interfaceName];
138
    }
139
140
    /**
141
     * @inheritdoc
142
     *
143
     * @param ServiceLocatorInterface $serviceLocator
144
     * @param                         $name
145
     * @param                         $requestedName
146
     *
147
     * @return mixed
148
     *
149
     * @throws Exception\RuntimeException
150
     * @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
151
     * @throws Exception\ErrorBuildEntityMapCacheException
152
     */
153
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
154
    {
155
        $this->init($serviceLocator);
156
157 View Code Duplication
        if (array_key_exists($requestedName, $this->prototype)) {
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...
158
            if (!is_object($this->prototype[$requestedName])) {
159
                $errMsg = sprintf('Invalid prototype for %s', $requestedName);
160
                throw new Exception\RuntimeException($errMsg);
161
            }
162
            return clone $this->prototype[$requestedName];
163
        }
164
165
        $className = $this->getClassNameByInterface($requestedName);
166
        if (false === $className) {
167
            $errMsg = sprintf('Invalid cache date for  %s', $requestedName);
168
            throw new Exception\RuntimeException($errMsg);
169
        }
170
171 View Code Duplication
        if ($serviceLocator->has($className)) {
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...
172
            $entity = $serviceLocator->get($className);
173
        } else {
174
            $r = new ReflectionClass($className);
175
            $entity = $r->newInstance();
176
        }
177
        $this->prototype[$requestedName] = $entity;
178
179
        return $entity;
180
    }
181
182
    /**
183
     * @param ServiceLocatorInterface $serviceLocator
184
     *
185
     * @return void
186
     *
187
     * @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
188
     * @throws Exception\ErrorBuildEntityMapCacheException
189
     */
190
    public function init(ServiceLocatorInterface $serviceLocator)
191
    {
192
        if (true === $this->isInit) {
193
            return;
194
        }
195
196
        $appServiceLocator = $serviceLocator;
197
        if ($serviceLocator instanceof AbstractPluginManager) {
198
            $appServiceLocator = $serviceLocator->getServiceLocator();
199
        }
200
201
        /** @var ModuleOptionsPluginManagerInterface $moduleOptionsManager */
202
        $moduleOptionsManager = $appServiceLocator->get(ModuleOptionsPluginManagerInterface::class);
203
        /** @var ModuleOptionsInterface $moduleOptions */
204
        $moduleOptions = $moduleOptionsManager->get(ModuleOptionsInterface::class);
205
        $this->setModuleOptions($moduleOptions);
206
207
        /** @var DoctrineOrmModuleConfigInterface $doctrineOrmModuleConfig */
208
        $doctrineOrmModuleConfig = $appServiceLocator->get(DoctrineOrmModuleConfigInterface::class);
209
210
        $listObjectManagerName = $doctrineOrmModuleConfig->getListObjectManagerName();
211
212
        /** @var EntityMapCacheInterface $entityMapCache */
213
        $entityMapCache = $appServiceLocator->get(EntityMapCacheInterface::class);
214
215
        $excludeEntityManagerForAutoBuildEntityMap = $moduleOptions->getExcludeEntityManagerForAutoBuildEntityMap();
216
        foreach ($listObjectManagerName as $objectManagerName) {
217
            $flagBuildCache = !in_array($objectManagerName, $excludeEntityManagerForAutoBuildEntityMap, true)
218
                && $moduleOptions->getFlagAutoBuildEntityMapDoctrineCache()
219
                && !$entityMapCache->hasEntityMap($objectManagerName);
220
221
            if ($flagBuildCache) {
222
                $entityMapCache->saveEntityMap($objectManagerName);
223
                if (!$entityMapCache->hasEntityMap($objectManagerName)) {
224
                    $errMsg = sprintf('Invalid build entity map for: %s', $objectManagerName);
225
                    throw new Exception\ErrorBuildEntityMapCacheException($errMsg);
226
                }
227
            }
228
229
            if ($entityMapCache->hasEntityMap($objectManagerName)) {
230
                $this->objectManagerToEntityMap[$objectManagerName] = $entityMapCache->loadEntityMap($objectManagerName);
231
            }
232
        }
233
234
        $this->countObjectManagers = count($this->objectManagerToEntityMap);
235
236
        if (1 === $this->countObjectManagers) {
237
            reset($this->objectManagerToEntityMap);
238
            $this->baseEntityMap = current($this->objectManagerToEntityMap);
239
        }
240
241
        $this->isInit = true;
242
    }
243
244
    /**
245
     * Возвращает настройки модуля
246
     *
247
     * @return ModuleOptionsInterface
248
     */
249
    public function getModuleOptions()
250
    {
251
        return $this->moduleOptions;
252
    }
253
254
    /**
255
     * Устанавливает настройки модуля
256
     *
257
     * @param ModuleOptionsInterface $moduleOptions
258
     *
259
     * @return $this
260
     */
261
    public function setModuleOptions($moduleOptions)
262
    {
263
        $this->moduleOptions = $moduleOptions;
264
265
        return $this;
266
    }
267
}
268