This repository has been archived by the owner on May 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
DoctrineHydratorFactory.php
393 lines (342 loc) · 13.6 KB
/
DoctrineHydratorFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
namespace Phpro\DoctrineHydrationModule\Service;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ORM\EntityManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator;
use Interop\Container\ContainerInterface;
use Phpro\DoctrineHydrationModule\Hydrator\DoctrineHydrator;
use Phpro\DoctrineHydrationModule\Hydrator\ODM\MongoDB;
use Zend\Hydrator\AbstractHydrator;
use Zend\Hydrator\Filter\FilterComposite;
use Zend\Hydrator\Filter\FilterInterface;
use Zend\Hydrator\FilterEnabledInterface;
use Zend\Hydrator\HydratorInterface;
use Zend\Hydrator\NamingStrategy\NamingStrategyInterface;
use Zend\Hydrator\NamingStrategyEnabledInterface;
use Zend\Hydrator\Strategy\StrategyInterface;
use Zend\Hydrator\StrategyEnabledInterface;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Class DoctrineHydratorFactory.
*/
class DoctrineHydratorFactory implements AbstractFactoryInterface
{
const FACTORY_NAMESPACE = 'doctrine-hydrator';
const OBJECT_MANAGER_TYPE_ODM_MONGODB = 'ODM/MongoDB';
const OBJECT_MANAGER_TYPE_ORM = 'ORM';
/**
* Cache of canCreateServiceWithName lookups.
*
* @var array
*/
protected $lookupCache = array();
/**
* Determine if we can create a service with name.
*
* @param ContainerInterface $container
* @param string $requestedName
*
* @return bool
*
* @throws ServiceNotFoundException
*/
public function canCreate(ContainerInterface $container, $requestedName)
{
if (array_key_exists($requestedName, $this->lookupCache)) {
return $this->lookupCache[$requestedName];
}
if (!$container->has('config')) {
return false;
}
// Validate object is set
$config = $container->get('config');
$namespace = self::FACTORY_NAMESPACE;
if (!isset($config[$namespace])
|| !is_array($config[$namespace])
|| !isset($config[$namespace][$requestedName])
) {
$this->lookupCache[$requestedName] = false;
return false;
}
// Validate object manager
$config = $config[$namespace];
if (!isset($config[$requestedName]) || !isset($config[$requestedName]['object_manager'])) {
throw new ServiceNotFoundException(sprintf(
'%s requires that a valid "object_manager" is specified for hydrator %s; no service found',
__METHOD__,
$requestedName
));
}
// Validate object class
if (!isset($config[$requestedName]['entity_class'])) {
throw new ServiceNotFoundException(sprintf(
'%s requires that a valid "entity_class" is specified for hydrator %s; no service found',
__METHOD__,
$requestedName
));
}
$this->lookupCache[$requestedName] = true;
return true;
}
/**
* Determine if we can create a service with name. (v2)
*
* Provided for backwards compatiblity; proxies to canCreate().
*
* @param ServiceLocatorInterface $hydratorManager
* @param string $name
* @param string $requestedName
*
* @return bool
*
* @throws ServiceNotFoundException
*/
public function canCreateServiceWithName(ServiceLocatorInterface $hydratorManager, $name, $requestedName)
{
return $this->canCreate($hydratorManager->getServiceLocator(), $requestedName);
}
/**
* Create and return the database-connected resource.
*
* @param ContainerInterface $container
* @param string $requestedName
* @param null|array $options
*
* @return DoctrineHydrator
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('config');
$config = $config[self::FACTORY_NAMESPACE][$requestedName];
$objectManager = $this->loadObjectManager($container, $config);
$extractService = null;
$hydrateService = null;
$useEntityHydrator = (array_key_exists('use_generated_hydrator', $config) && $config['use_generated_hydrator']);
$useCustomHydrator = (array_key_exists('hydrator', $config));
if ($useEntityHydrator) {
$hydrateService = $this->loadEntityHydrator($container, $config, $objectManager);
}
if ($useCustomHydrator) {
try {
$extractService = $container->build($config['hydrator'], $config);
} catch (ServiceNotFoundException $e) {
$extractService = $container->get($config['hydrator']);
}
$hydrateService = $extractService;
}
# Use DoctrineModuleHydrator by default
if (!isset($extractService, $hydrateService)) {
$doctrineModuleHydrator = $this->loadDoctrineModuleHydrator($container, $config, $objectManager);
$extractService = ($extractService ?: $doctrineModuleHydrator);
$hydrateService = ($hydrateService ?: $doctrineModuleHydrator);
}
$this->configureHydrator($extractService, $container, $config, $objectManager);
$this->configureHydrator($hydrateService, $container, $config, $objectManager);
return new DoctrineHydrator($extractService, $hydrateService);
}
/**
* Create and return the database-connected resource (v2).
*
* Provided for backwards compatibility; proxies to __invoke().
*
* @param ServiceLocatorInterface $hydratorManager
* @param string $name
* @param string $requestedName
*
* @return DoctrineHydrator
*/
public function createServiceWithName(ServiceLocatorInterface $hydratorManager, $name, $requestedName)
{
return $this($hydratorManager->getServiceLocator(), $requestedName);
}
/**
* @param $objectManager
*
* @return string
*
* @throws ServiceNotCreatedException
*/
protected function getObjectManagerType($objectManager)
{
if (class_exists(DocumentManager::class) && $objectManager instanceof DocumentManager) {
return self::OBJECT_MANAGER_TYPE_ODM_MONGODB;
} elseif (class_exists(EntityManager::class) && $objectManager instanceof EntityManager) {
return self::OBJECT_MANAGER_TYPE_ORM;
}
throw new ServiceNotCreatedException('Unknown object manager type: ' . get_class($objectManager));
}
/**
* @param ContainerInterface $container
* @param array $config
*
* @return ObjectManager
*
* @throws ServiceNotCreatedException
*/
protected function loadObjectManager(ContainerInterface $container, $config)
{
if (!$container->has($config['object_manager'])) {
throw new ServiceNotCreatedException('The object_manager could not be found.');
}
return $container->get($config['object_manager']);
}
/**
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
*
* @return null|HydratorInterface
*/
protected function loadEntityHydrator(ContainerInterface $container, $config, $objectManager)
{
$objectManagerType = $this->getObjectManagerType($objectManager);
if ($objectManagerType != self::OBJECT_MANAGER_TYPE_ODM_MONGODB) {
return;
}
$hydratorFactory = $objectManager->getHydratorFactory();
$hydrator = $hydratorFactory->getHydratorFor($config['entity_class']);
return $hydrator;
}
/**
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
*
* @return HydratorInterface
*/
protected function loadDoctrineModuleHydrator(ContainerInterface $container, $config, $objectManager)
{
$objectManagerType = $this->getObjectManagerType($objectManager);
if ($objectManagerType == self::OBJECT_MANAGER_TYPE_ODM_MONGODB) {
$hydrator = new MongoDB\DoctrineObject($objectManager, $config['by_value']);
} else {
$hydrator = new Hydrator\DoctrineObject($objectManager, $config['by_value']);
}
return $hydrator;
}
/**
* @param AbstractHydrator $hydrator
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
*
* @throws ServiceNotCreatedException
*/
public function configureHydrator($hydrator, ContainerInterface $container, $config, $objectManager)
{
$this->configureHydratorFilters($hydrator, $container, $config, $objectManager);
$this->configureHydratorStrategies($hydrator, $container, $config, $objectManager);
$this->configureHydratorNamingStrategy($hydrator, $container, $config, $objectManager);
}
/**
* @param AbstractHydrator $hydrator
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
*
* @throws ServiceNotCreatedException
*/
public function configureHydratorNamingStrategy($hydrator, ContainerInterface $container, $config, $objectManager)
{
if (!($hydrator instanceof NamingStrategyEnabledInterface) || !isset($config['naming_strategy'])) {
return;
}
$namingStrategyKey = $config['naming_strategy'];
if (!$container->has($namingStrategyKey)) {
throw new ServiceNotCreatedException(sprintf('Invalid naming strategy %s.', $namingStrategyKey));
}
$namingStrategy = $container->get($namingStrategyKey);
if (!$namingStrategy instanceof NamingStrategyInterface) {
throw new ServiceNotCreatedException(
sprintf('Invalid naming strategy class %s', get_class($namingStrategy))
);
}
// Attach object manager:
if ($namingStrategy instanceof ObjectManagerAwareInterface) {
$namingStrategy->setObjectManager($objectManager);
}
$hydrator->setNamingStrategy($namingStrategy);
}
/**
* @param AbstractHydrator $hydrator
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
*
* @throws ServiceNotCreatedException
*/
protected function configureHydratorStrategies($hydrator, ContainerInterface $container, $config, $objectManager)
{
if (!$hydrator instanceof StrategyEnabledInterface
|| !isset($config['strategies'])
|| !is_array($config['strategies'])
) {
return;
}
foreach ($config['strategies'] as $field => $strategyKey) {
if (!$container->has($strategyKey)) {
throw new ServiceNotCreatedException(sprintf('Invalid strategy %s for field %s', $strategyKey, $field));
}
$strategy = $container->get($strategyKey);
if (!$strategy instanceof StrategyInterface) {
throw new ServiceNotCreatedException(
sprintf('Invalid strategy class %s for field %s', get_class($strategy), $field)
);
}
// Attach object manager:
if ($strategy instanceof ObjectManagerAwareInterface) {
$strategy->setObjectManager($objectManager);
}
$hydrator->addStrategy($field, $strategy);
}
}
/**
* Add filters to the Hydrator based on a predefined configuration format, if specified.
*
* @param AbstractHydrator $hydrator
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
*
* @throws ServiceNotCreatedException
*/
protected function configureHydratorFilters($hydrator, ContainerInterface $container, $config, $objectManager)
{
if (!$hydrator instanceof FilterEnabledInterface
|| !isset($config['filters'])
|| !is_array($config['filters'])
) {
return;
}
foreach ($config['filters'] as $name => $filterConfig) {
$conditionMap = array(
'and' => FilterComposite::CONDITION_AND,
'or' => FilterComposite::CONDITION_OR,
);
$condition = isset($filterConfig['condition']) ?
$conditionMap[$filterConfig['condition']] :
FilterComposite::CONDITION_OR;
$filterService = $filterConfig['filter'];
if (!$container->has($filterService)) {
throw new ServiceNotCreatedException(
sprintf('Invalid filter %s for field %s: service does not exist', $filterService, $name)
);
}
$filterService = $container->get($filterService);
if (!$filterService instanceof FilterInterface) {
throw new ServiceNotCreatedException(
sprintf('Filter service %s must implement FilterInterface', get_class($filterService))
);
}
if ($filterService instanceof ObjectManagerAwareInterface) {
$filterService->setObjectManager($objectManager);
}
$hydrator->addFilter($name, $filterService, $condition);
}
}
}