1
|
|
|
<?php namespace Pz\Doctrine\Rest\Action\Related; |
2
|
|
|
|
3
|
|
|
use League\Fractal\TransformerAbstract; |
4
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
5
|
|
|
use Pz\Doctrine\Rest\Exceptions\RestException; |
6
|
|
|
use Pz\Doctrine\Rest\RestAction; |
7
|
|
|
use Pz\Doctrine\Rest\RestRepository; |
8
|
|
|
use Pz\Doctrine\Rest\RestResponse; |
9
|
|
|
use Pz\Doctrine\Rest\Traits\CanHydrate; |
10
|
|
|
use Pz\Doctrine\Rest\Traits\CanValidate; |
11
|
|
|
use Pz\Doctrine\Rest\Traits\RelatedAction; |
12
|
|
|
|
13
|
|
|
class RelatedCollectionCreateAction extends RestAction |
14
|
|
|
{ |
15
|
|
|
use RelatedAction; |
16
|
|
|
use CanHydrate; |
|
|
|
|
17
|
|
|
use CanValidate; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* RelatedCollectionCreateAction constructor. |
21
|
|
|
* |
22
|
|
|
* @param RestRepository $repository |
23
|
|
|
* @param string $field |
24
|
|
|
* @param $mappedBy |
25
|
|
|
* @param RestRepository $related |
26
|
|
|
* @param \Closure|TransformerAbstract $transformer |
27
|
|
|
*/ |
28
|
1 |
|
public function __construct(RestRepository $repository, $field, $mappedBy, RestRepository $related, $transformer) |
29
|
|
|
{ |
30
|
1 |
|
parent::__construct($repository, $transformer); |
31
|
1 |
|
$this->mappedBy = $mappedBy; |
32
|
1 |
|
$this->related = $related; |
33
|
1 |
|
$this->field = $field; |
34
|
1 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param RestRequestContract $request |
38
|
|
|
* |
39
|
|
|
* @return RestResponse |
40
|
|
|
* @throws RestException |
41
|
|
|
*/ |
42
|
1 |
|
public function handle($request) |
43
|
|
|
{ |
44
|
1 |
|
$entity = $this->repository()->findById($request->getId()); |
45
|
1 |
|
$this->authorize($request, $entity); |
46
|
|
|
|
47
|
1 |
|
foreach ($request->getData() as $raw) { |
48
|
1 |
|
$item = $this->hydrateEntity($this->related()->getClassName(), $raw); |
49
|
1 |
|
$this->addRelationItem($entity, $this->field(), $item); |
50
|
1 |
|
$this->validateEntity($item); |
51
|
1 |
|
$this->related()->getEntityManager()->persist($item); |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
$this->repository()->getEntityManager()->flush($entity); |
55
|
|
|
|
56
|
1 |
|
return (new RelatedCollectionAction( |
57
|
1 |
|
$this->repository(), |
58
|
1 |
|
$this->mappedBy(), |
59
|
1 |
|
$this->related(), |
60
|
1 |
|
$this->transformer() |
|
|
|
|
61
|
1 |
|
))->dispatch($request)->setStatusCode(RestResponse::HTTP_CREATED); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|