Completed
Push — master ( 3efb43...6ac6c3 )
by Андрей
05:02
created

ManagerRegistry::getConnectionByName()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 15

Duplication

Lines 27
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 27
loc 27
rs 8.8571
cc 3
eloc 15
nc 3
nop 1
1
<?php
2
/**
3
 * @link    https://github.com/nnx-framework/doctrine
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace Nnx\Doctrine\ManagerRegistry;
7
8
use Doctrine\Common\Persistence\AbstractManagerRegistry;
9
use Doctrine\Common\Persistence\ObjectManager;
10
use Zend\EventManager\EventManagerAwareTrait;
11
12
/**
13
 * Class ManagerRegistry
14
 *
15
 * @package Nnx\Doctrine\ManagerRegistry
16
 */
17
class ManagerRegistry extends AbstractManagerRegistry
18
{
19
    use EventManagerAwareTrait;
20
21
    /**
22
     * Имя менеджера
23
     *
24
     * @var string
25
     */
26
    const NAME = 'defaultManagerRegistry';
27
28
    /**
29
     * Контекст вызова метода getService
30
     *
31
     * @var string
32
     */
33
    const OBJECT_MANAGER_CONTEXT = 'objectManagerContext';
34
35
    /**
36
     * Контекст вызова метода getService
37
     *
38
     * @var string
39
     */
40
    const CONNECTION_CONTEXT = 'connectionContext';
41
42
    /**
43
     * Контекст вызова метода getService
44
     *
45
     * @var string
46
     */
47
    protected $serviceContext;
48
49
    /**
50
     * Ключем является имя ObjectManager'a, а значением объект ObjectManager'a
51
     *
52
     * @var array
53
     */
54
    protected $objectManagerByName = [];
55
56
    /**
57
     * Ключем является имя соеденения, а значением объект соеденения к базе данных
58
     *
59
     * @var array
60
     */
61
    protected $connectionByName = [];
62
63
    /**
64
     * Прототип для создания объекта события, бросаемого когда нужно получить ресурс
65
     *
66
     * @var ManagerRegistryResourceEventInterface
67
     */
68
    protected $managerRegistryResourceEventPrototype;
69
70
    /**
71
     * Возвращает прототип для создания объекта события, бросаемого когда нужно получить ресурс
72
     * 
73
     * @return ManagerRegistryResourceEventInterface
74
     */
75
    public function getManagerRegistryResourceEventPrototype()
76
    {
77
        if (null === $this->managerRegistryResourceEventPrototype) {
78
            $managerRegistryResourceEventPrototype = new ManagerRegistryResourceEvent();
79
            $this->setManagerRegistryResourceEventPrototype($managerRegistryResourceEventPrototype);
80
        }
81
        return $this->managerRegistryResourceEventPrototype;
82
    }
83
84
    /**
85
     * Устанавливает прототип для создания объекта события, бросаемого когда нужно получить ресурс
86
     *
87
     * @param ManagerRegistryResourceEventInterface $managerRegistryResourceEventPrototype
88
     *
89
     * @return $this
90
     */
91
    public function setManagerRegistryResourceEventPrototype(ManagerRegistryResourceEventInterface $managerRegistryResourceEventPrototype)
92
    {
93
        $this->managerRegistryResourceEventPrototype = $managerRegistryResourceEventPrototype;
94
95
        return $this;
96
    }
97
98
    /**
99
     * @inheritdoc
100
     *
101
     * @param null $name
102
     *
103
     * @return mixed
104
     */
105 View Code Duplication
    public function getConnection($name = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
106
    {
107
        $this->serviceContext = static::CONNECTION_CONTEXT;
108
        $result = parent::getConnection($name);
109
        $this->serviceContext = null;
110
        return $result;
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 View Code Duplication
    public function getConnections()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
117
    {
118
        $this->serviceContext = static::CONNECTION_CONTEXT;
119
        $result = parent::getConnections();
120
        $this->serviceContext = null;
121
        return $result;
122
    }
123
124
125
    /**
126
     * {@inheritdoc}
127
     */
128 View Code Duplication
    public function getManager($name = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
129
    {
130
        $this->serviceContext = static::OBJECT_MANAGER_CONTEXT;
131
        $result = parent::getManager($name);
132
        $this->serviceContext = null;
133
        return $result;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139 View Code Duplication
    public function getManagerForClass($class)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
140
    {
141
        $this->serviceContext = static::OBJECT_MANAGER_CONTEXT;
142
        $result = parent::getManagerForClass($class);
143
        $this->serviceContext = null;
144
        return $result;
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150 View Code Duplication
    public function getManagers()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
151
    {
152
        $this->serviceContext = static::OBJECT_MANAGER_CONTEXT;
153
        $result = parent::getManagers();
154
        $this->serviceContext = null;
155
        return $result;
156
    }
157
158
159
    /**
160
     * @inheritdoc
161
     *
162
     * @param string $name
163
     *
164
     * @return mixed
165
     * @throws \Nnx\Doctrine\ManagerRegistry\Exception\ConnectionNotFoundException
166
     * @throws \Nnx\Doctrine\ManagerRegistry\Exception\ObjectManagerNotFoundException
167
     * @throws \Nnx\Doctrine\ManagerRegistry\Exception\RuntimeException
168
     */
169
    protected function getService($name)
170
    {
171
        if (static::OBJECT_MANAGER_CONTEXT === $this->serviceContext) {
172
            return $this->getObjectManagerByName($name);
173
        }
174
175
        if (static::CONNECTION_CONTEXT === $this->serviceContext) {
176
            return $this->getConnectionByName($name);
177
        }
178
179
        $errMsg = 'Invalid execution context';
180
        throw new Exception\RuntimeException($errMsg);
181
    }
182
183
    /**
184
     * Получает ObjectManager по имени
185
     *
186
     * @param $name
187
     *
188
     * @return ObjectManager
189
     * @throws \Nnx\Doctrine\ManagerRegistry\Exception\ObjectManagerNotFoundException
190
     */
191 View Code Duplication
    protected function getObjectManagerByName($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
192
    {
193
        if (array_key_exists($name, $this->objectManagerByName)) {
194
            return $this->objectManagerByName[$name];
195
        }
196
197
        $event = clone $this->getManagerRegistryResourceEventPrototype();
198
        $event->setName(ManagerRegistryResourceEvent::RESOLVE_OBJECT_MANAGER_EVENT);
199
        $event->setResourceName($name);
200
        $event->setTarget($this);
201
202
203
        $resultsEvent = $this->getEventManager()->trigger($event, function ($objectManager) {
204
            return $objectManager instanceof ObjectManager;
205
        });
206
207
        $objectManager = $resultsEvent->last();
208
209
        if (!$objectManager instanceof ObjectManager) {
210
            $errMsg = sprintf('Object manager %s not found', $name);
211
            throw new Exception\ObjectManagerNotFoundException($errMsg);
212
        }
213
214
        $this->objectManagerByName[$name] = $objectManager;
215
216
        return $this->objectManagerByName[$name];
217
    }
218
219
220
    /**
221
     * Получает соеденение по имени
222
     *
223
     * @param $name
224
     *
225
     * @return mixed
226
     * @throws \Nnx\Doctrine\ManagerRegistry\Exception\ConnectionNotFoundException
227
     */
228 View Code Duplication
    protected function getConnectionByName($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
229
    {
230
        if (array_key_exists($name, $this->connectionByName)) {
231
            return $this->connectionByName[$name];
232
        }
233
234
        $event = clone $this->getManagerRegistryResourceEventPrototype();
235
        $event->setName(ManagerRegistryResourceEvent::RESOLVE_CONNECTION_EVENT);
236
        $event->setResourceName($name);
237
        $event->setTarget($this);
238
239
240
        $resultsEvent = $this->getEventManager()->trigger($event, function ($connection) {
241
            return is_object($connection);
242
        });
243
244
        $connection = $resultsEvent->last();
245
246
        if (!is_object($connection)) {
247
            $errMsg = sprintf('Connection %s not found', $name);
248
            throw new Exception\ConnectionNotFoundException($errMsg);
249
        }
250
251
        $this->connectionByName[$name] = $connection;
252
253
        return $this->connectionByName[$name];
254
    }
255
256
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function resetManager($name = null)
261
    {
262
        $this->serviceContext = static::OBJECT_MANAGER_CONTEXT;
263
        parent::resetManager($name);
264
        $this->serviceContext = null;
265
    }
266
267
    /**
268
     * @param string $name
269
     *
270
     * @return mixed
271
     * @throws \Nnx\Doctrine\ManagerRegistry\Exception\ObjectManagerNotFoundException
272
     */
273
    protected function resetService($name)
274
    {
275
        if (static::OBJECT_MANAGER_CONTEXT === $this->serviceContext) {
276
            $this->getObjectManagerByName($name)->clear();
277
        }
278
    }
279
280
    /**
281
     * @inheritdoc
282
     *
283
     * @param string $alias
284
     *
285
     * @return mixed
286
     */
287
    public function getAliasNamespace($alias)
288
    {
289
        return $alias;
290
    }
291
}
292