1
|
|
|
<?php |
2
|
|
|
namespace keeko\core\model\serializer; |
3
|
|
|
|
4
|
|
|
use keeko\core\model\types\ModelSerializerInterface; |
5
|
|
|
use Tobscure\JsonApi\Relationship; |
6
|
|
|
|
7
|
|
|
abstract class AbstractSerializer implements ModelSerializerInterface { |
8
|
|
|
|
9
|
|
|
public function getAttributes($model, $fields = null) { |
10
|
|
|
return []; |
11
|
|
|
} |
12
|
|
|
|
13
|
|
|
public function getSelf($model) { |
14
|
|
|
return '%apiurl%' . $this->getType($model) . '/' . $this->getId($model); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function getLinks($model) { |
18
|
|
|
return [ |
19
|
|
|
'self' => $this->getSelf($model) |
20
|
|
|
]; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getRelationship($model, $name) { |
24
|
|
|
// strip namespace |
25
|
|
|
if (strstr($name, '/') !== false) { |
26
|
|
|
$name = substr($name, strpos($name, '/') + 1); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$method = $name; |
30
|
|
|
|
31
|
|
|
// to camel case |
32
|
|
|
if (strstr($method, '-') !== false) { |
33
|
|
|
$method = lcfirst(implode('', array_map('ucfirst', explode('-', $method)))); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if (method_exists($this, $method)) { |
37
|
|
|
$relationship = $this->$method($model, $name); |
38
|
|
|
if ($relationship !== null && !($relationship instanceof Relationship)) { |
39
|
|
|
throw new \LogicException('Relationship method must return null or an instance of ' |
40
|
|
|
. Relationship::class); |
41
|
|
|
} |
42
|
|
|
return $relationship; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
protected function addRelationshipSelfLink(Relationship $relationship, $model, $related) { |
47
|
|
|
$links = $relationship->getLinks(); |
48
|
|
|
$links = $links + [ |
49
|
|
|
'self' => $this->getSelf($model) . '/relationships/' . $related |
50
|
|
|
]; |
51
|
|
|
$relationship->setLinks($links); |
52
|
|
|
return $relationship; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function toArray($model) { |
56
|
|
|
$id = ['id' => $this->getId($model)]; |
|
|
|
|
57
|
|
|
$attributes = $this->getAttributes($model); |
58
|
|
|
return $id + $attributes; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function hydrateRelationships($model, $data) { |
62
|
|
|
$relationships = isset($data['relationships']) ? $data['relationships'] : []; |
63
|
|
|
|
64
|
|
|
foreach (array_keys($this->getRelationships()) as $rel) { |
65
|
|
|
if (isset($relationships[$rel]) && isset($relationships[$rel]['data'])) { |
66
|
|
|
$method = 'set' . ucFirst($rel); |
67
|
|
|
if (method_exists($this, $method)) { |
68
|
|
|
$this->$method($model, $relationships[$rel]['data']); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.