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
/
Copy pathDoctrineResource.php
774 lines (654 loc) · 22.5 KB
/
DoctrineResource.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2016-2017 Zend Technologies USA Inc. (http://www.zend.com)
*/
namespace ZF\Apigility\Doctrine\Server\Resource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Instantiator\InstantiatorInterface;
use Doctrine\ODM\MongoDB\Query\Builder as MongoDBQueryBuilder;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NoResultException;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator;
use ReflectionClass;
use Traversable;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\SharedEventManager;
use Zend\Hydrator\HydratorAwareInterface;
use Zend\Hydrator\HydratorInterface;
use Zend\Mvc\ModuleRouteListener;
use ZF\Apigility\Doctrine\Server\Event\DoctrineResourceEvent;
use ZF\Apigility\Doctrine\Server\Exception\InvalidArgumentException;
use ZF\Apigility\Doctrine\Server\Query\CreateFilter\QueryCreateFilterInterface;
use ZF\Apigility\Doctrine\Server\Query\Provider\QueryProviderInterface;
use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;
use ZF\Rest\RestController;
class DoctrineResource extends AbstractResourceListener implements
ObjectManagerAwareInterface,
EventManagerAwareInterface,
HydratorAwareInterface
{
/**
* @var SharedEventManager Interface
*/
protected $sharedEventManager;
/**
* @var ObjectManager
*/
protected $objectManager;
/**
* @var EventManagerInterface
*/
protected $events;
/**
* @var array
*/
protected $eventIdentifier = ['ZF\Apigility\Doctrine\DoctrineResource'];
/**
* @var array|QueryProviderInterface
*/
protected $queryProviders;
/**
* @var string entityIdentifierName
*/
protected $entityIdentifierName;
/**
* @var string
*/
protected $routeIdentifierName;
/**
* @var QueryCreateFilterInterface
*/
protected $queryCreateFilter;
/**
* @var string
*/
protected $multiKeyDelimiter = '.';
/**
* @var HydratorInterface
*/
protected $hydrator;
/**
* @var InstantiatorInterface|null
*/
private $entityFactory;
/**
* @param InstantiatorInterface|null $entityFactory
*/
public function __construct(InstantiatorInterface $entityFactory = null)
{
$this->entityFactory = $entityFactory;
}
/**
* @return SharedEventManager
*/
public function getSharedEventManager()
{
return $this->sharedEventManager;
}
/**
* @param SharedEventManager $sharedEventManager
* @return $this
*/
public function setSharedEventManager(SharedEventManager $sharedEventManager)
{
$this->sharedEventManager = $sharedEventManager;
return $this;
}
/**
* Set the event manager instance used by this context.
*
* For convenience, this method will also set the class name / LSB name as
* identifiers, in addition to any string or array of strings set to the
* $this->eventIdentifier property.
*
* @param EventManagerInterface $events
* @return $this
*/
public function setEventManager(EventManagerInterface $events)
{
$identifiers = [__CLASS__, get_class($this)];
if (isset($this->eventIdentifier)) {
if (is_string($this->eventIdentifier)
|| is_array($this->eventIdentifier)
|| $this->eventIdentifier instanceof Traversable
) {
$identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
} elseif (is_object($this->eventIdentifier)) {
$identifiers[] = $this->eventIdentifier;
}
// silently ignore invalid eventIdentifier types
}
$events->setIdentifiers($identifiers);
$this->events = $events;
if (method_exists($this, 'attachDefaultListeners')) {
$this->attachDefaultListeners();
}
return $this;
}
/**
* Retrieve the event manager
*
* Lazy-loads an EventManager instance if none registered.
*
* @return EventManagerInterface
*/
public function getEventManager()
{
if (! $this->events instanceof EventManagerInterface) {
$this->setEventManager(new EventManager($this->getSharedEventManager()));
}
return $this->events;
}
/**
* Set the object manager
*
* @param ObjectManager|EntityManagerInterface $objectManager
*/
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
/**
* Get the object manager
*
* @return ObjectManager|EntityManagerInterface
*/
public function getObjectManager()
{
return $this->objectManager;
}
/**
* @param array|\ZF\Apigility\Doctrine\Server\Query\Provider\QueryProviderInterface[]
* @throws InvalidArgumentException if parameter is not an array or \Traversable object
*/
public function setQueryProviders($queryProviders)
{
if (! is_array($queryProviders) && ! $queryProviders instanceof Traversable) {
throw new InvalidArgumentException('queryProviders must be array or Traversable object');
}
foreach ($queryProviders as $qp) {
if (! $qp instanceof QueryProviderInterface) {
throw new InvalidArgumentException('queryProviders must implement QueryProviderInterface');
}
}
$this->queryProviders = (array) $queryProviders;
}
/**
* @return array|QueryProviderInterface[]
*/
public function getQueryProviders()
{
return $this->queryProviders;
}
/**
* @param $method
* @return QueryProviderInterface
*/
public function getQueryProvider($method)
{
$queryProviders = $this->getQueryProviders();
if (isset($queryProviders[$method])) {
return $queryProviders[$method];
}
return $queryProviders['default'];
}
/**
* @return string
*/
public function getEntityIdentifierName()
{
return $this->entityIdentifierName;
}
/**
* @param string
* @return $this
*/
public function setEntityIdentifierName($value)
{
$this->entityIdentifierName = $value;
return $this;
}
/**
* @return string
*/
public function getRouteIdentifierName()
{
return $this->routeIdentifierName;
}
/**
* @param string $routeIdentifierName
* @return $this
*/
public function setRouteIdentifierName($routeIdentifierName)
{
$this->routeIdentifierName = $routeIdentifierName;
return $this;
}
/**
* @param QueryCreateFilterInterface $value
* @return $this
*/
public function setQueryCreateFilter(QueryCreateFilterInterface $value)
{
$this->queryCreateFilter = $value;
return $this;
}
/**
* @return QueryCreateFilterInterface
*/
public function getQueryCreateFilter()
{
return $this->queryCreateFilter;
}
/**
* @param string $value
* @return $this
*/
public function setMultiKeyDelimiter($value)
{
$this->multiKeyDelimiter = $value;
return $this;
}
/**
* @return string
*/
public function getMultiKeyDelimiter()
{
return $this->multiKeyDelimiter;
}
/**
* @param HydratorInterface $hydrator
* @return $this
*/
public function setHydrator(HydratorInterface $hydrator)
{
$this->hydrator = $hydrator;
return $this;
}
/**
* @return HydratorInterface
*/
public function getHydrator()
{
if (! $this->hydrator) {
// FIXME: find a way to test this line from a created API. Shouldn't all created API's have a hydrator?
$this->hydrator = new Hydrator\DoctrineObject($this->getObjectManager(), $this->getEntityClass());
}
return $this->hydrator;
}
/**
* Create a resource
*
* @param mixed $data
* @return ApiProblem|mixed
*/
public function create($data)
{
$entityClass = $this->getEntityClass();
$data = $this->getQueryCreateFilter()->filter($this->getEvent(), $entityClass, $data);
if ($data instanceof ApiProblem) {
return $data;
}
$entity = $this->entityFactory
? $this->entityFactory->instantiate($entityClass)
: new $entityClass();
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_CREATE_PRE, $entity, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
} elseif (! $results->isEmpty() && $results->last() !== null) {
// TODO Change to a more logical/secure way to see if data was acted and and we have the expected response
$preEventData = $results->last();
} else {
$preEventData = $data;
}
$hydrator = $this->getHydrator();
$hydrator->hydrate((array) $preEventData, $entity);
$this->getObjectManager()->persist($entity);
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_CREATE_POST, $entity, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
$this->getObjectManager()->flush();
return $entity;
}
/**
* Delete a resource
*
* @param mixed $id
* @return ApiProblem|mixed
*/
public function delete($id)
{
$entity = $this->findEntity($id, 'delete');
if ($entity instanceof ApiProblem) {
return $entity;
}
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_DELETE_PRE, $entity);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
$this->getObjectManager()->remove($entity);
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_DELETE_POST, $entity);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
$this->getObjectManager()->flush();
return true;
}
/**
* Respond to the PATCH method (partial update of existing entity) on
* a collection, i.e. update multiple entities in a collection.
*
* @param array $data
* @return array
*/
public function patchList($data)
{
$return = new ArrayCollection();
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_PATCH_LIST_PRE, $data, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
if (! $this->getObjectManager() instanceof EntityManagerInterface) {
throw new InvalidArgumentException('Invalid Object Manager, must implement EntityManagerInterface');
}
$this->getObjectManager()->getConnection()->beginTransaction();
foreach ($data as $row) {
$result = $this->patch($row[$this->getEntityIdentifierName()], $row);
if ($result instanceof ApiProblem) {
$this->getObjectManager()->getConnection()->rollback();
return $result;
}
$return->add($result);
}
$this->getObjectManager()->getConnection()->commit();
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_PATCH_LIST_POST, $return, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
return $return;
}
/**
* Delete a list of entities
*
* @param mixed $data
* @return ApiProblem|mixed
*/
public function deleteList($data)
{
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_DELETE_LIST_PRE, $data, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
$this->getObjectManager()->getConnection()->beginTransaction();
foreach ($data as $row) {
$result = $this->delete($row[$this->getEntityIdentifierName()]);
if ($result instanceof ApiProblem) {
$this->getObjectManager()->getConnection()->rollback();
return $result;
}
}
$this->getObjectManager()->getConnection()->commit();
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_DELETE_LIST_POST, true, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
return true;
}
/**
* Fetch a resource
*
* If the extractCollections array contains a collection for this resource
* expand that collection instead of returning a link to the collection
*
* @param mixed $id
* @return ApiProblem|mixed
*/
public function fetch($id)
{
$event = new DoctrineResourceEvent(DoctrineResourceEvent::EVENT_FETCH_PRE, $this);
$event->setEntityClassName($this->getEntityClass());
$event->setResourceEvent($this->getEvent());
$event->setEntityId($id);
$eventManager = $this->getEventManager();
$response = $eventManager->triggerEvent($event);
if ($response->last() instanceof ApiProblem) {
return $response->last();
}
$entity = $this->findEntity($id, 'fetch');
if ($entity instanceof ApiProblem) {
return $entity;
}
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_FETCH_POST, $entity);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
return $entity;
}
/**
* Fetch all or a subset of resources
*
* @param array $data
* @return ApiProblem|mixed
*/
public function fetchAll($data = [])
{
// Build query
$queryProvider = $this->getQueryProvider('fetch_all');
$queryBuilder = $queryProvider->createQuery($this->getEvent(), $this->getEntityClass(), $data);
if ($queryBuilder instanceof ApiProblem) {
return $queryBuilder;
}
$response = $this->triggerDoctrineEvent(
DoctrineResourceEvent::EVENT_FETCH_ALL_PRE,
$this->getEntityClass(),
$data
);
if ($response->last() instanceof ApiProblem) {
return $response->last();
}
$adapter = $queryProvider->getPaginatedQuery($queryBuilder);
$reflection = new ReflectionClass($this->getCollectionClass());
$collection = $reflection->newInstance($adapter);
$results = $this->triggerDoctrineEvent(
DoctrineResourceEvent::EVENT_FETCH_ALL_POST,
$this->getEntityClass(),
$data
);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
// Add event to set extra HAL data
$entityClass = $this->getEntityClass();
$this->getSharedEventManager()->attach(
RestController::class,
'getList.post',
function (EventInterface $e) use ($queryProvider, $entityClass, $data) {
/** @var \ZF\Hal\Collection $halCollection */
$halCollection = $e->getParam('collection');
$collection = $halCollection->getCollection();
$collection->setItemCountPerPage($halCollection->getPageSize());
$collection->setCurrentPageNumber($halCollection->getPage());
$halCollection->setCollectionRouteOptions([
'query' => $e->getTarget()->getRequest()->getQuery()->toArray(),
]);
}
);
return $collection;
}
/**
* Patch (partial in-place update) a resource
*
* @param mixed $id
* @param mixed $data
* @return ApiProblem|mixed
*/
public function patch($id, $data)
{
$entity = $this->findEntity($id, 'patch', $data);
if ($entity instanceof ApiProblem) {
return $entity;
}
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_PATCH_PRE, $entity, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
} elseif (! $results->isEmpty() && $results->last() !== null) {
// TODO Change to a more logical/secure way to see if data was acted and and we have the expected response
$preEventData = $results->last();
} else {
$preEventData = $data;
}
// Hydrate entity with patched data
$this->getHydrator()->hydrate((array) $preEventData, $entity);
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_PATCH_POST, $entity, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
$this->getObjectManager()->flush();
return $entity;
}
/**
* Replace a collection or members of a collection
*
* @param mixed $data
* @return ApiProblem|mixed
*/
public function replaceList($data)
{
return new ApiProblem(405, 'The PUT method has not been defined for collections');
}
/**
* Update a resource
*
* @param mixed $id
* @param mixed $data
* @return ApiProblem|mixed
*/
public function update($id, $data)
{
$entity = $this->findEntity($id, 'update', $data);
if ($entity instanceof ApiProblem) {
return $entity;
}
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_UPDATE_PRE, $entity, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
} elseif (! $results->isEmpty() && $results->last() !== null) {
// TODO Change to a more logical/secure way to see if data was acted on and we have the expected response
$preEventData = $results->last();
} else {
$preEventData = $data;
}
$this->getHydrator()->hydrate((array) $preEventData, $entity);
$results = $this->triggerDoctrineEvent(DoctrineResourceEvent::EVENT_UPDATE_POST, $entity, $data);
if ($results->last() instanceof ApiProblem) {
return $results->last();
}
$this->getObjectManager()->flush();
return $entity;
}
/**
* This method will give custom listeners te chance to alter entities / collections.
* Listeners can also return an ApiProblem, which will be returned immediately.
* It is also possible to throw Exceptions, which will result in an ApiProblem eventually.
*
* @param $name
* @param $entity
* @param $data mixed The original data supplied to the resource method, if any
* @return \Zend\EventManager\ResponseCollection
*/
protected function triggerDoctrineEvent($name, $entity, $data = null)
{
$event = new DoctrineResourceEvent($name, $this);
$event->setEntity($entity);
$event->setData($data);
$event->setObjectManager($this->getObjectManager());
$event->setResourceEvent($this->getEvent());
$eventManager = $this->getEventManager();
$response = $eventManager->triggerEvent($event);
return $response;
}
/**
* Gets an entity by route params and/or the specified id
*
* @param $id
* @param $method
* @param null|array $data parameters
* @return object
*/
protected function findEntity($id, $method, $data = null)
{
// Match identity identifier name(s) with id(s)
$ids = explode($this->getMultiKeyDelimiter(), $id);
$keys = explode($this->getMultiKeyDelimiter(), $this->getEntityIdentifierName());
$criteria = [];
if (count($ids) !== count($keys)) {
return new ApiProblem(
500,
'Invalid multi identifier count. '
. count($ids)
. ' must equal '
. count($keys)
);
}
foreach ($keys as $index => $identifier) {
$criteria[$identifier] = $ids[$index];
}
$classMetaData = $this->getObjectManager()->getClassMetadata($this->getEntityClass());
$routeMatch = $this->getEvent()->getRouteMatch();
$associationMappings = $classMetaData->getAssociationNames();
$fieldNames = $classMetaData->getFieldNames();
$routeParams = $routeMatch->getParams();
if (array_key_exists($this->getRouteIdentifierName(), $routeParams)) {
unset($routeParams[$this->getRouteIdentifierName()]);
}
$reservedRouteParams = [
'controller',
'action',
'version',
ModuleRouteListener::MODULE_NAMESPACE,
ModuleRouteListener::ORIGINAL_CONTROLLER,
];
$allowedRouteParams = array_diff_key($routeParams, array_flip($reservedRouteParams));
/**
* Append query selection parameters by route match.
*/
foreach ($allowedRouteParams as $routeMatchParam => $value) {
if (in_array($routeMatchParam, $associationMappings) || in_array($routeMatchParam, $fieldNames)) {
$criteria[$routeMatchParam] = $value;
}
}
// Build query
$queryProvider = $this->getQueryProvider($method);
$queryBuilder = $queryProvider->createQuery($this->getEvent(), $this->getEntityClass(), $data);
if ($queryBuilder instanceof ApiProblem) {
return $queryBuilder;
}
// Add criteria
foreach ($criteria as $key => $value) {
if ($queryBuilder instanceof MongoDBQueryBuilder) {
$queryBuilder->field($key)->equals($value);
} else {
$parameterName = 'a' . md5(rand());
$queryBuilder->andwhere($queryBuilder->expr()->eq('row.' . $key, ":$parameterName"));
$queryBuilder->setParameter($parameterName, $value, $classMetaData->getTypeOfField($key));
}
}
try {
$entity = $queryBuilder->getQuery()->getSingleResult();
} catch (NoResultException $e) {
$entity = null;
}
if (! $entity) {
$entity = new ApiProblem(404, 'Entity was not found');
}
return $entity;
}
}