Completed
Push — master ( 2001b3...f7416c )
by Pavel
02:39
created

RelatedAction::getRelatedEntity()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 1
dl 0
loc 17
ccs 11
cts 11
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php namespace Pz\Doctrine\Rest\Traits;
2
3
use Pz\Doctrine\Rest\Exceptions\RestException;
4
use Pz\Doctrine\Rest\RestRepository;
5
6
trait RelatedAction
7
{
8
    /**
9
     * @var RestRepository
10
     */
11
    protected $related;
12
13
    /**
14
     * @var string
15
     */
16
    protected $field;
17
18
    /**
19
     * @var string
20
     */
21
    protected $mappedBy;
22
23
    /**
24
     * Related repository.
25
     *
26
     * @return RestRepository
27
     */
28 7
    public function related()
29
    {
30 7
        return $this->related;
31
    }
32
33
    /**
34
     * `field` on base entity that identify relation.
35
     *
36
     * @return string
37
     */
38 10
    public function field()
39
    {
40 10
        return $this->field;
41
    }
42
43
    /**
44
     * @return string
45
     */
46 5
    public function mappedBy()
47
    {
48 5
        return $this->mappedBy;
49
    }
50
51
    /**
52
     * @param $item
53
     *
54
     * @return null|object
55
     * @throws RestException
56
     */
57 7
    protected function getRelatedEntity($item)
58
    {
59 7
        if (!isset($item['id']) || !isset($item['type'])) {
60 1
            throw RestException::createUnprocessable('Relation item without identifiers.')
61 1
                ->error(
62 1
                    'invalid-data',
63 1
                    ['pointer' => $this->field()],
64 1
                    'Relation item without `id` or `type`.'
65
                );
66
        }
67
68 7
        if ($this->related()->getResourceKey() !== $item['type']) {
69 1
            throw RestException::createUnprocessable('Different resource type in delete request.')
70 1
                ->error('invalid-data', ['pointer' => $this->field()], 'Type is not in sync with relation.');
71
        }
72
73 6
        return $this->related()->findById($item['id']);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->related()->findById($item['id']) returns the type Pz\Doctrine\Rest\Contracts\JsonApiResource which is incompatible with the documented return type object|null.
Loading history...
74
    }
75
}
76