1
|
|
|
<?php namespace Pz\Doctrine\Rest\Action\Related; |
2
|
|
|
|
3
|
|
|
use League\Fractal\TransformerAbstract; |
4
|
|
|
use Pz\Doctrine\Rest\Contracts\JsonApiResource; |
5
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
6
|
|
|
use Pz\Doctrine\Rest\Exceptions\RestException; |
7
|
|
|
use Pz\Doctrine\Rest\Resource\Item; |
8
|
|
|
use Pz\Doctrine\Rest\RestAction; |
9
|
|
|
use Pz\Doctrine\Rest\RestRepository; |
10
|
|
|
use Pz\Doctrine\Rest\RestResponse; |
11
|
|
|
use Pz\Doctrine\Rest\Traits\CanHydrate; |
12
|
|
|
use Pz\Doctrine\Rest\Traits\RelatedAction; |
13
|
|
|
|
14
|
|
|
class RelatedItemCreateAction extends RestAction |
15
|
|
|
{ |
16
|
|
|
use RelatedAction; |
17
|
|
|
use CanHydrate; |
|
|
|
|
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* RelatedRestAction constructor. |
21
|
|
|
* |
22
|
|
|
* @param RestRepository $repository |
23
|
|
|
* @param string $field |
24
|
|
|
* @param RestRepository $related |
25
|
|
|
* @param TransformerAbstract $transformer |
26
|
|
|
*/ |
27
|
1 |
|
public function __construct(RestRepository $repository, $field, RestRepository $related, $transformer) |
28
|
|
|
{ |
29
|
1 |
|
parent::__construct($repository, $transformer); |
30
|
1 |
|
$this->related = $related; |
31
|
1 |
|
$this->field = $field; |
32
|
1 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param RestRequestContract $request |
36
|
|
|
* |
37
|
|
|
* @return RestResponse |
38
|
|
|
* @throws RestException |
39
|
|
|
*/ |
40
|
1 |
|
public function handle($request) |
41
|
|
|
{ |
42
|
1 |
|
$entity = $this->repository()->findById($request->getId()); |
43
|
1 |
|
$data = $request->getData(); |
44
|
1 |
|
$this->authorize($request, $entity); |
45
|
|
|
|
46
|
1 |
|
if (isset($data['id']) && isset($data['type'])) { |
47
|
1 |
|
$item = $this->getRelatedEntity($data); |
48
|
|
|
} else { |
49
|
1 |
|
$scope = $entity->getResourceKey().'.'.$this->field(); |
50
|
|
|
/** @var JsonApiResource $item */ |
51
|
1 |
|
$item = $this->hydrateEntity($this->related()->getClassName(), $data, $scope); |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
$this->setProperty($entity, $this->field(), $item); |
55
|
1 |
|
$this->repository()->getEntityManager()->flush($entity); |
56
|
|
|
|
57
|
1 |
|
return $this->response()->resource($request, new Item($item, $this->transformer())); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|