1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flugg\Responder; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\Pivot; |
6
|
|
|
use League\Fractal\Scope; |
7
|
|
|
use League\Fractal\TransformerAbstract; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* An abstract base transformer. Your transformers should extend this class, and this |
11
|
|
|
* class itself extends Fractal's transformer. |
12
|
|
|
* |
13
|
|
|
* @package flugger/laravel-responder |
14
|
|
|
* @author Alexander Tømmerås <[email protected]> |
15
|
|
|
* @license The MIT License |
16
|
|
|
*/ |
17
|
|
|
abstract class Transformer extends TransformerAbstract |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Get relations set on the transformer. |
21
|
|
|
* |
22
|
|
|
* @return array |
23
|
|
|
*/ |
24
|
|
|
public function getRelations():array |
25
|
|
|
{ |
26
|
|
|
return array_merge($this->getAvailableIncludes(), $this->getDefaultIncludes()); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Set relations on the transformer. |
31
|
|
|
* |
32
|
|
|
* @param array|string $relations |
33
|
|
|
* @return self |
34
|
|
|
*/ |
35
|
|
|
public function setRelations($relations) |
36
|
|
|
{ |
37
|
|
|
$this->setAvailableIncludes(array_merge($this->availableIncludes, (array) $relations)); |
38
|
|
|
|
39
|
|
|
return $this; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Call method for retrieving a relation. This method overrides Fractal's own |
44
|
|
|
* [callIncludeMethod] method to load relations directly from your models. |
45
|
|
|
* |
46
|
|
|
* @param Scope $scope |
47
|
|
|
* @param string $includeName |
48
|
|
|
* @param mixed $data |
49
|
|
|
* @return \League\Fractal\Resource\ResourceInterface|bool |
50
|
|
|
* @throws \Exception |
51
|
|
|
*/ |
52
|
|
|
protected function callIncludeMethod(Scope $scope, $includeName, $data) |
53
|
|
|
{ |
54
|
|
|
if ($includeName === 'pivot') { |
55
|
|
|
return $this->includePivot($data->$includeName); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return app(Responder::class)->transform($data->$includeName)->getResource(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Include pivot table data to the response. |
63
|
|
|
* |
64
|
|
|
* @param Pivot $pivot |
65
|
|
|
* @return \League\Fractal\Resource\ResourceInterface|bool |
66
|
|
|
*/ |
67
|
|
|
protected function includePivot(Pivot $pivot) |
68
|
|
|
{ |
69
|
|
|
if (! method_exists($this, 'transformPivot')) { |
70
|
|
|
return false; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return app(Responder::class)->transform($pivot, function () use ($pivot) { |
74
|
|
|
return $this->transformPivot($pivot); |
|
|
|
|
75
|
|
|
})->getResource(); |
76
|
|
|
} |
77
|
|
|
} |