1 | <?php |
||
8 | class Restifier implements Restifiable |
||
9 | { |
||
10 | /** @var callable[] */ |
||
11 | protected $transformers = []; |
||
12 | |||
13 | 10 | public function __construct(array $transformers = []) |
|
19 | |||
20 | /** |
||
21 | * @param string $name |
||
22 | * @param callable $transformer |
||
23 | */ |
||
24 | 7 | public function addTransformer(string $name, callable $transformer) |
|
32 | |||
33 | /** |
||
34 | * {@inheritdoc} |
||
35 | */ |
||
36 | 10 | public function restify($resource, array $includes = [], callable $transformer = null) |
|
37 | { |
||
38 | 10 | if ($resource === null) return null; |
|
39 | 9 | if (!$transformer) { |
|
40 | 8 | $transformer = $this->findTransformer($resource); |
|
41 | } |
||
42 | 8 | $parsedIncludes = $this->parseIncludes($includes, $resource); |
|
43 | 8 | $entity = call_user_func($transformer, $resource, $this, $parsedIncludes); |
|
44 | 8 | foreach ($parsedIncludes as $key => $nextIncludes) { |
|
45 | 2 | if (is_object($transformer) && method_exists($transformer, $key)) { |
|
46 | 2 | $entity = array_merge( |
|
47 | 2 | $entity, |
|
48 | 2 | $transformer->{$key}($resource, $this, $nextIncludes) |
|
49 | ); |
||
50 | } |
||
51 | } |
||
52 | 8 | return $entity; |
|
53 | } |
||
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | 1 | public function restifyMany($resource, array $includes = [], callable $transformer = null): array |
|
59 | { |
||
60 | 1 | $result = []; |
|
61 | 1 | foreach ($resource as $key => $value) { |
|
62 | 1 | $result[$key] = $this->restify($value, $includes, $transformer); |
|
63 | } |
||
64 | 1 | return $result; |
|
65 | } |
||
66 | |||
67 | 8 | protected function findTransformer($resource) |
|
68 | { |
||
69 | 8 | $className = null; |
|
70 | 8 | if (is_object($resource) && $className = get_class($resource)) { |
|
71 | 8 | if (array_key_exists($className, $this->transformers)) { |
|
72 | 7 | return $this->transformers[$className]; |
|
73 | } |
||
74 | 2 | foreach ($this->transformers as $name => $transformer) { |
|
75 | 1 | if ($resource instanceof $name) { |
|
76 | 1 | return $transformer; |
|
77 | } |
||
78 | } |
||
79 | } |
||
80 | 1 | if ($className) { |
|
|
|||
81 | 1 | throw new NotFoundTransformerException( |
|
82 | 1 | sprintf("cannot find the transformer named %s.", $className) |
|
83 | ); |
||
84 | } |
||
85 | 1 | throw new NotFoundTransformerException("resource is not an object."); |
|
86 | } |
||
87 | |||
88 | /** |
||
89 | * @param array $includes |
||
90 | * @param mixed $resource |
||
91 | * @return array |
||
92 | */ |
||
93 | 8 | private function parseIncludes(array $includes = [], $resource) |
|
120 | } |
||
121 |
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: