Completed
Push — master ( a5189e...da7714 )
by Pavel
02:31
created

RelatedItemCreateAction::handle()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 2
nop 1
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
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;
0 ignored issues
show
introduced by
The trait Pz\Doctrine\Rest\Traits\CanHydrate requires some properties which are not provided by Pz\Doctrine\Rest\Action\...RelatedItemCreateAction: $reflFields, $associationMappings
Loading history...
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