1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Fractal; |
4
|
|
|
|
5
|
|
|
use League\Fractal\Serializer\SerializerAbstract; |
6
|
|
|
use Spatie\Fractal\Exceptions\InvalidFractalHelperArgument; |
7
|
|
|
use Traversable; |
8
|
|
|
|
9
|
|
|
class FractalFunctionHelper |
10
|
|
|
{ |
11
|
|
|
/** @var \Spatie\Fractal\Fractal */ |
12
|
|
|
protected $fractal; |
13
|
|
|
|
14
|
|
|
/** @var array */ |
15
|
|
|
protected $arguments; |
16
|
|
|
|
17
|
|
|
public function __construct(array $arguments) |
18
|
|
|
{ |
19
|
|
|
$this->fractal = app(Fractal::class); |
20
|
|
|
|
21
|
|
|
$this->arguments = $arguments; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @return \Spatie\Fractal\Fractal |
26
|
|
|
* |
27
|
|
|
* @throws \Spatie\Fractal\Exceptions\InvalidFractalHelperArgument |
28
|
|
|
*/ |
29
|
|
|
public function getFractalInstance() |
30
|
|
|
{ |
31
|
|
|
if (count($this->arguments) === 1) { |
32
|
|
|
throw InvalidFractalHelperArgument::secondArgumentMissing(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (count($this->arguments) >= 2) { |
36
|
|
|
$this->setData($this->arguments[0]); |
37
|
|
|
|
38
|
|
|
$this->setTransformer($this->arguments[1]); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (count($this->arguments) >= 3) { |
42
|
|
|
$this->setSerializer($this->arguments[2]); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (count($this->arguments) > 3) { |
46
|
|
|
throw InvalidFractalHelperArgument::tooManyArguments($this->arguments); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $this->fractal; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param mixed $data |
54
|
|
|
*/ |
55
|
|
|
public function setData($data) |
56
|
|
|
{ |
57
|
|
|
$dataType = $this->determineDataType($data); |
58
|
|
|
|
59
|
|
|
$this->fractal->data($dataType, $data); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param mixed $data |
64
|
|
|
* |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
|
|
protected function determineDataType($data) |
68
|
|
|
{ |
69
|
|
|
if (is_array($data)) { |
70
|
|
|
return 'collection'; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if ($data instanceof Traversable) { |
74
|
|
|
return 'collection'; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return 'item'; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @param callable|\League\Fractal\TransformerAbstract $transformer |
82
|
|
|
*/ |
83
|
|
|
protected function setTransformer($transformer) |
84
|
|
|
{ |
85
|
|
|
$this->fractal->transformWith($transformer); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* @param \League\Fractal\Serializer\SerializerAbstract $serializer |
90
|
|
|
*/ |
91
|
|
|
protected function setSerializer(SerializerAbstract $serializer) |
92
|
|
|
{ |
93
|
|
|
$this->fractal->serializeWith($serializer); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|