1
|
|
|
<?php namespace Pz\Doctrine\Rest\Action\Relationships; |
2
|
|
|
|
3
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
4
|
|
|
use Doctrine\Common\Collections\Collection; |
5
|
|
|
use League\Fractal\TransformerAbstract; |
6
|
|
|
use Pz\Doctrine\Rest\Action\Related\RelatedCollectionAction; |
7
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
8
|
|
|
use Pz\Doctrine\Rest\Exceptions\RestException; |
9
|
|
|
use Pz\Doctrine\Rest\RestAction; |
10
|
|
|
use Pz\Doctrine\Rest\RestRepository; |
11
|
|
|
use Pz\Doctrine\Rest\RestResponse; |
12
|
|
|
use Pz\Doctrine\Rest\Traits\CanHydrate; |
13
|
|
|
use Pz\Doctrine\Rest\Traits\RelatedAction; |
14
|
|
|
|
15
|
|
|
class RelationshipsCollectionUpdateAction extends RestAction |
16
|
|
|
{ |
17
|
|
|
use RelatedAction; |
18
|
|
|
use CanHydrate; |
|
|
|
|
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* RelatedRestAction constructor. |
22
|
|
|
* |
23
|
|
|
* @param RestRepository $repository |
24
|
|
|
* @param string $field |
25
|
|
|
* @param string $mappedBy |
26
|
|
|
* @param RestRepository $related |
27
|
|
|
* @param TransformerAbstract $transformer |
28
|
|
|
*/ |
29
|
1 |
|
public function __construct(RestRepository $repository, $field, $mappedBy, RestRepository $related, $transformer) |
30
|
|
|
{ |
31
|
1 |
|
parent::__construct($repository, $transformer); |
32
|
1 |
|
$this->mappedBy = $mappedBy; |
33
|
1 |
|
$this->related = $related; |
34
|
1 |
|
$this->field = $field; |
35
|
1 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param RestRequestContract $request |
39
|
|
|
* |
40
|
|
|
* @return RestResponse |
41
|
|
|
*/ |
42
|
1 |
|
public function handle($request) |
43
|
|
|
{ |
44
|
1 |
|
$entity = $this->repository()->findById($request->getId()); |
45
|
|
|
|
46
|
1 |
|
$this->authorize($request, $entity); |
47
|
|
|
|
48
|
1 |
|
$items = $this->getProperty($entity, $this->field()); |
49
|
|
|
|
50
|
1 |
|
$replace = new ArrayCollection(array_map( |
51
|
1 |
|
function($raw) use ($entity) { |
|
|
|
|
52
|
1 |
|
return $this->getRelatedEntity($raw); |
53
|
1 |
|
}, |
54
|
1 |
|
$request->getData() |
55
|
|
|
)); |
56
|
|
|
|
57
|
1 |
|
foreach ($items as $key => $item) { |
58
|
1 |
|
if (!$replace->contains($item)) { |
59
|
1 |
|
$items->remove($key); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
foreach ($replace as $item) { |
64
|
1 |
|
if (!$items->contains($item)) { |
65
|
1 |
|
$items->add($item); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
$this->setProperty($entity, $this->field(), $items); |
70
|
|
|
|
71
|
1 |
|
$this->repository()->getEntityManager()->flush($entity); |
72
|
|
|
|
73
|
|
|
return ( |
74
|
1 |
|
new RelatedCollectionAction( |
75
|
1 |
|
$this->repository(), |
76
|
1 |
|
$this->mappedBy(), |
77
|
1 |
|
$this->related(), |
78
|
1 |
|
$this->transformer() |
|
|
|
|
79
|
|
|
) |
80
|
1 |
|
)->dispatch($request); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|