This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
DoctrineResourceFactory.php
324 lines (281 loc) · 11.2 KB
/
DoctrineResourceFactory.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
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2016 Zend Technologies USA Inc. (http://www.zend.com)
*/
namespace ZF\Apigility\Doctrine\Server\Resource;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ORM\EntityManager;
use Interop\Container\ContainerInterface;
use RuntimeException;
use Zend\Hydrator\HydratorInterface;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZF\Apigility\Doctrine\Server\Query\CreateFilter\QueryCreateFilterInterface;
use ZF\Hal\Plugin\Hal;
class DoctrineResourceFactory implements AbstractFactoryInterface
{
/**
* Can this factory create the requested service?
*
* @param ContainerInterface $container
* @param string $requestedName
* @return bool
* @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
*/
public function canCreate(ContainerInterface $container, $requestedName)
{
if (! $container->has('config')) {
return false;
}
$config = $container->get('config');
if (! isset($config['zf-apigility']['doctrine-connected'])
|| ! is_array($config['zf-apigility']['doctrine-connected'])
) {
return false;
}
$config = $config['zf-apigility']['doctrine-connected'];//[$requestedName];
if (! isset($config[$requestedName])
|| ! is_array($config[$requestedName])
|| ! $this->isValidConfig($config[$requestedName], $requestedName, $container)
) {
return false;
}
return true;
}
/**
* Can this factory create the requested service? (v2)
*
* Provided for backwards compatiblity; proxies to canCreate().
*
* @param ServiceLocatorInterface $container
* @param string $name
* @param string $requestedName
* @return bool
*/
public function canCreateServiceWithName(ServiceLocatorInterface $container, $name, $requestedName)
{
return $this->canCreate($container, $requestedName);
}
/**
* Create and return the doctrine-connected resource.
*
* @param ContainerInterface $container
* @param string $requestedName
* @param null|array $options
* @return DoctrineResource
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('config');
$doctrineConnectedConfig = $config['zf-apigility']['doctrine-connected'][$requestedName];
$doctrineHydratorConfig = $config['doctrine-hydrator'];
$restConfig = null;
foreach ($config['zf-rest'] as $restControllerConfig) {
if ($restControllerConfig['listener'] == $requestedName) {
$restConfig = $restControllerConfig;
break;
}
}
if (is_null($restConfig)) {
throw new RuntimeException(
sprintf('No zf-rest configuration found for resource %s', $requestedName)
);
}
$resourceClass = $this->getResourceClassFromConfig($doctrineConnectedConfig, $requestedName);
$objectManager = $container->get($doctrineConnectedConfig['object_manager']);
$entityFactory = ! empty($doctrineConnectedConfig['entity_factory'])
? $container->get($doctrineConnectedConfig['entity_factory'])
: null;
$hydrator = $this->loadHydrator($container, $doctrineConnectedConfig, $doctrineHydratorConfig);
$queryProviders = $this->loadQueryProviders($container, $doctrineConnectedConfig, $objectManager);
$queryCreateFilter = $this->loadQueryCreateFilter($container, $doctrineConnectedConfig, $objectManager);
$configuredListeners = $this->loadConfiguredListeners($container, $doctrineConnectedConfig);
/** @var DoctrineResource $listener */
$listener = new $resourceClass($entityFactory);
$listener->setSharedEventManager($container->get('Application')->getEventManager()->getSharedManager());
$listener->setObjectManager($objectManager);
$listener->setHydrator($hydrator);
$listener->setQueryProviders($queryProviders);
$listener->setQueryCreateFilter($queryCreateFilter);
$listener->setEntityIdentifierName($restConfig['entity_identifier_name']);
$listener->setRouteIdentifierName($restConfig['route_identifier_name']);
if ($configuredListeners) {
$events = $listener->getEventManager();
foreach ($configuredListeners as $configuredListener) {
$configuredListener->attach($events);
}
}
return $listener;
}
/**
* Retrieve the resource class based on the provided configuration.
*
* Defaults to ZF\Apigility\Doctrine\Server\Resource\DoctrineResource.
*
* @param array $config
* @param string $requestedName
* @return string
* @throws ServiceNotCreatedException if the discovered resource class
* does not exist or is not a subclass of DoctrineResource.
*/
protected function getResourceClassFromConfig($config, $requestedName)
{
$defaultClass = DoctrineResource::class;
$resourceClass = isset($config['class']) ? $config['class'] : $requestedName;
$resourceClass = $this->normalizeClassname($resourceClass);
if (! class_exists($resourceClass) || ! is_subclass_of($resourceClass, $defaultClass)) {
throw new ServiceNotCreatedException(sprintf(
'Unable to create instance for service "%s"; resource class "%s" cannot be found or does not extend %s',
$requestedName,
$resourceClass,
$defaultClass
));
}
return $resourceClass;
}
/**
* Tests if the configuration is valid
*
* If the configuration has a "object_manager" key, and that service exists,
* then the configuration is valid.
*
* @param array $config
* @param string $requestedName
* @param ContainerInterface $container
* @return bool
*/
protected function isValidConfig(array $config, $requestedName, ContainerInterface $container)
{
if (! isset($config['object_manager'])
|| ! $container->has($config['object_manager'])
) {
return false;
}
return true;
}
/**
* Create and return the doctrine-connected resource (v2).
*
* Provided for backwards compatibility; proxies to __invoke().
*
* @param ServiceLocatorInterface $container
* @param string $name
* @param string $requestedName
* @return DoctrineResource
*/
public function createServiceWithName(ServiceLocatorInterface $container, $name, $requestedName)
{
return $this($container, $requestedName);
}
/**
* @param string $className
* @return string
*/
protected function normalizeClassname($className)
{
return '\\' . ltrim($className, '\\');
}
/**
* @param ContainerInterface $container
* @param array $doctrineConnectedConfig
* @param array $doctrineHydratorConfig
* @return HydratorInterface
*/
protected function loadHydrator(
ContainerInterface $container,
array $doctrineConnectedConfig,
array $doctrineHydratorConfig
) {
if (! isset($doctrineConnectedConfig['hydrator'])) {
return null;
}
if (! $container->has('HydratorManager')) {
return null;
}
$hydratorManager = $container->get('HydratorManager');
if (! $hydratorManager->has($doctrineConnectedConfig['hydrator'])) {
return null;
}
// Set the hydrator for the entity for this resource to the hydrator
// configured for the resource. This removes per-entity hydrator configuration
// allowing multiple hydrators per resource.
if (isset($doctrineConnectedConfig['hydrator'])) {
$entityClass = $doctrineHydratorConfig[$doctrineConnectedConfig['hydrator']]['entity_class'];
$viewHelpers = $container->get('ViewHelperManager');
/** @var Hal $hal */
$hal = $viewHelpers->get('Hal');
$hal->getEntityHydratorManager()->addHydrator($entityClass, $doctrineConnectedConfig['hydrator']);
}
return $hydratorManager->get($doctrineConnectedConfig['hydrator']);
}
/**
* @param ContainerInterface $container
* @param array $config
* @param ObjectManager $objectManager
* @return QueryCreateFilterInterface
*/
protected function loadQueryCreateFilter(ContainerInterface $container, array $config, $objectManager)
{
$createFilterManager = $container->get('ZfApigilityDoctrineQueryCreateFilterManager');
$filterManagerAlias = isset($config['query_create_filter']) ? $config['query_create_filter'] : 'default';
/** @var QueryCreateFilterInterface $queryCreateFilter */
$queryCreateFilter = $createFilterManager->get($filterManagerAlias);
// Set object manager for all query providers
$queryCreateFilter->setObjectManager($objectManager);
return $queryCreateFilter;
}
/**
* @param ContainerInterface $serviceLocator
* @param array $config
* @param ObjectManager $objectManager
* @return array
* @throws ServiceNotCreatedException
*/
protected function loadQueryProviders(ContainerInterface $serviceLocator, array $config, $objectManager)
{
$queryProviders = [];
$queryManager = $serviceLocator->get('ZfApigilityDoctrineQueryProviderManager');
// Load default query provider
if (class_exists(EntityManager::class)
&& $objectManager instanceof EntityManager
) {
$queryProviders['default'] = $queryManager->get('default_orm');
} elseif (class_exists(DocumentManager::class)
&& $objectManager instanceof DocumentManager
) {
$queryProviders['default'] = $queryManager->get('default_odm');
} else {
throw new ServiceNotCreatedException('No valid doctrine module is found for objectManager.');
}
// Load custom query providers
if (isset($config['query_providers'])) {
foreach ($config['query_providers'] as $method => $plugin) {
$queryProviders[$method] = $queryManager->get($plugin);
}
}
// Set object manager for all query providers
foreach ($queryProviders as $provider) {
$provider->setObjectManager($objectManager);
}
return $queryProviders;
}
/**
* @param ContainerInterface $container
* @param array $config
* @return array
*/
protected function loadConfiguredListeners(ContainerInterface $container, array $config)
{
if (! isset($config['listeners'])) {
return [];
}
$listeners = [];
foreach ($config['listeners'] as $listener) {
$listeners[] = $container->get($listener);
}
return $listeners;
}
}