1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of JSON-API. |
5
|
|
|
* |
6
|
|
|
* (c) Toby Zerner <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Tobscure\JsonApi; |
13
|
|
|
|
14
|
|
|
use LogicException; |
15
|
|
|
|
16
|
|
|
abstract class AbstractSerializer implements SerializerInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* The type. |
20
|
|
|
* |
21
|
|
|
* @var string |
22
|
|
|
*/ |
23
|
|
|
protected $type; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* {@inheritdoc} |
27
|
|
|
*/ |
28
|
|
|
public function getType($model) |
29
|
|
|
{ |
30
|
|
|
return $this->type; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritdoc} |
35
|
|
|
*/ |
36
|
|
|
public function getId($model) |
37
|
|
|
{ |
38
|
|
|
return $model->id; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* {@inheritdoc} |
43
|
|
|
*/ |
44
|
|
|
public function getAttributes($model, array $fields = null) |
45
|
|
|
{ |
46
|
|
|
return []; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
|
|
public function getLinks($model) |
53
|
|
|
{ |
54
|
|
|
return []; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritdoc} |
59
|
|
|
* |
60
|
|
|
* @throws LogicException |
61
|
|
|
*/ |
62
|
|
|
public function getRelationship($model, $name) |
63
|
|
|
{ |
64
|
|
|
if (stripos($name, '-')) { |
65
|
|
|
$name = $this->replaceDashWithUppercase($name); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if (method_exists($this, $name)) { |
69
|
|
|
$relationship = $this->$name($model); |
70
|
|
|
|
71
|
|
|
if ($relationship !== null && ! ($relationship instanceof Relationship)) { |
72
|
|
|
throw new LogicException('Relationship method must return null or an instance of ' |
73
|
|
|
.Relationship::class); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $relationship; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Removes all dashes from relationsship and uppercases the following letter. |
82
|
|
|
* @example If relationship parent-page is needed the the function name will be changed to parentPage |
83
|
|
|
* |
84
|
|
|
* @param string Name of the function |
85
|
|
|
* |
86
|
|
|
* @return string New function name |
87
|
|
|
*/ |
88
|
|
|
private function replaceDashWithUppercase($name) |
89
|
|
|
{ |
90
|
|
|
return lcfirst(implode('', array_map('ucfirst', explode('-', $name)))); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|