1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\Mapper\Definition\ConfigurationProcessor; |
5
|
|
|
|
6
|
|
|
use Mikemirten\Component\JsonApi\Mapper\Definition\Definition; |
7
|
|
|
use Mikemirten\Component\JsonApi\Mapper\Definition\Relationship; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Processor of relationships |
11
|
|
|
* |
12
|
|
|
* @package Mikemirten\Component\JsonApi\Mapper\Definition\AnnotationProcessor |
13
|
|
|
*/ |
14
|
|
|
class RelationshipProcessor extends AbstractProcessor |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* {@inheritdoc} |
18
|
|
|
*/ |
19
|
2 |
|
public function process(array $config, Definition $definition) |
20
|
|
|
{ |
21
|
2 |
|
if (! isset($config['relationships'])) { |
22
|
|
|
return; |
23
|
|
|
} |
24
|
|
|
|
25
|
2 |
|
$reflection = new \ReflectionClass($definition->getClass()); |
26
|
|
|
|
27
|
2 |
|
foreach ($config['relationships'] as $name => $data) |
28
|
|
|
{ |
29
|
2 |
|
$relationship = $this->createRelationship($reflection, $name, $data); |
30
|
|
|
|
31
|
2 |
|
$definition->addRelationship($relationship); |
32
|
|
|
} |
33
|
2 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Process relationship |
37
|
|
|
* |
38
|
|
|
* @param \ReflectionClass $reflection |
39
|
|
|
* @param string $name |
40
|
|
|
* @param array $data |
41
|
|
|
* @return Relationship |
42
|
|
|
*/ |
43
|
2 |
|
protected function createRelationship(\ReflectionClass $reflection, string $name, array $data): Relationship |
44
|
|
|
{ |
45
|
2 |
|
$getter = isset($data['getter']) |
46
|
2 |
|
? $data['getter'] |
47
|
2 |
|
: $this->resolveGetter($reflection, $name); |
48
|
|
|
|
49
|
2 |
|
$type = ($data['type'] === 'one') |
50
|
2 |
|
? Relationship::TYPE_X_TO_ONE |
51
|
2 |
|
: Relationship::TYPE_X_TO_MANY; |
52
|
|
|
|
53
|
2 |
|
$relationship = new Relationship($name, $type, $getter); |
54
|
|
|
|
55
|
2 |
|
$relationship->setIncludeData($data['dataAllowed']); |
56
|
2 |
|
$relationship->setDataLimit($data['dataLimit']); |
57
|
|
|
|
58
|
2 |
|
$this->handleLinks($data, $relationship); |
59
|
|
|
|
60
|
2 |
|
return $relationship; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Handle links |
65
|
|
|
* |
66
|
|
|
* @param array $data |
67
|
|
|
* @param Relationship $relationship |
68
|
|
|
*/ |
69
|
2 |
|
protected function handleLinks(array $data, Relationship $relationship) |
70
|
|
|
{ |
71
|
2 |
|
if (! isset($data['links'])) { |
72
|
1 |
|
return; |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
foreach ($data['links'] as $linkName => $linkData) |
76
|
|
|
{ |
77
|
1 |
|
$link = $this->createLink($linkName, $linkData); |
78
|
|
|
|
79
|
1 |
|
$relationship->addLink($link); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |