-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerializer.php
83 lines (70 loc) · 1.65 KB
/
Serializer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace Orchestra\Support;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Support\Collection as BaseCollection;
abstract class Serializer
{
/**
* Data serializer key name.
*
* @var string
*/
protected $key = 'data';
/**
* Invoke the serializer.
*
* @param mixed $parameters
*
* @return mixed
*/
public function __invoke(...$parameters)
{
if (\method_exists($this, 'serialize')) {
return $this->serialize(...$parameters);
}
return $this->serializeBasicDataset($parameters[0]);
}
/**
* Resolve paginated dataset.
*
* @param mixed $dataset
*
* @return array
*/
final protected function serializeBasicDataset($dataset): array
{
$key = $this->resolveSerializerKey($dataset);
if ($dataset instanceof Paginator) {
$collection = $dataset->toArray();
$collection[$key] = $collection['data'];
unset($collection['data']);
return $collection;
}
return [
$key => $dataset->toArray(),
];
}
/**
* Get serializer key.
*
* @return string
*/
final public function getKey(): string
{
return $this->key;
}
/**
* Resolve serializer key.
*
* @param mixed $dataset
*
* @return string
*/
protected function resolveSerializerKey($dataset): string
{
if ($dataset instanceof BaseCollection || $dataset instanceof Paginator) {
return Str::plural($this->getKey());
}
return $this->getKey();
}
}