-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVersionedHelpers.php
106 lines (89 loc) · 2.87 KB
/
VersionedHelpers.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace Orchestra\Routing;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Collection;
use Illuminate\Support\Fluent;
use Orchestra\Http\Transformer;
use Orchestra\Support\Transformer as BaseTransformer;
trait VersionedHelpers
{
/**
* Transform and serialize the instance.
*
* @param \Orchestra\Model\Eloquent|\Illuminate\Support\Collection $instance
*
* @return array
*/
protected function transform($instance, string $transformer, ?string $serializer = null, array $options = [])
{
if (\is_null($serializer)) {
$serializer = $transformer;
}
return $this->serializeWith(
$this->transformWith($instance, $transformer, $options),
$serializer,
$options
);
}
/**
* Process the instance.
*
* @param \Orchestra\Model\Eloquent|\Illuminate\Support\Collection $instance
* @param mixed $parameters
*
* @return mixed
*/
protected function processWith($instance, string $name, string $method, ...$parameters)
{
$processor = $this->getVersionedResourceClassName('Processors', $name);
return \app($processor)->{$method}($this, $instance, ...$parameters);
}
/**
* Transform the instance.
*
* @param \Orchestra\Model\Eloquent|\Illuminate\Support\Collection $instance
*
* @return mixed
*/
protected function transformWith($instance, string $name, array $options = [])
{
$transformer = $this->getVersionedResourceClassName('Transformers', $name);
if (\class_exists($transformer)) {
$transformer = \resolve($transformer);
if ($transformer instanceof Transformer) {
return $transformer->options($options)->handle($instance);
}
if ($transformer instanceof BaseTransformer) {
return $transformer->handle($instance);
}
return $instance->transform($transformer);
}
return $instance;
}
/**
* Serialize the instance.
*
* @param mixed $instance
*
* @return array
*/
protected function serializeWith($instance, string $name)
{
$serializer = $this->getVersionedResourceClassName('Serializers', $name);
if (\class_exists($serializer)) {
return \call_user_func(\app($serializer), $instance);
}
if ($instance instanceof Fluent) {
return $instance->getAttributes();
} elseif ($instance instanceof Collection) {
return $instance->all();
} elseif ($instance instanceof Arrayable) {
return $instance->toArray();
}
return $instance;
}
/**
* Get versioned resource class name.
*/
abstract public function getVersionedResourceClassName(string $group, string $name): string;
}