1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flugg\Responder\Transformers\Concerns; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use League\Fractal\ParamBag; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* A trait to be used by a transformer to make resources for relations |
11
|
|
|
* |
12
|
|
|
* @package flugger/laravel-responder |
13
|
|
|
* @author Alexander Tømmerås <[email protected]> |
14
|
|
|
* @license The MIT License |
15
|
|
|
*/ |
16
|
|
|
trait MakesResources |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* A list of cached related resources. |
20
|
|
|
* |
21
|
|
|
* @var \League\Fractal\ResourceInterface[] |
22
|
|
|
*/ |
23
|
|
|
protected $resources = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* The resource builder resolver callback. |
27
|
|
|
* |
28
|
|
|
* @var \Closure|null |
29
|
|
|
*/ |
30
|
|
|
protected static $resourceBuilderResolver; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Set a resource builder using a resolver callback. |
34
|
|
|
* |
35
|
|
|
* @param null $data |
36
|
|
|
* @param \Flugg\Responder\Transformers\Transformer|string|callable|null $transformer |
37
|
|
|
* @param string|null $resourceKey |
38
|
|
|
* @return void |
39
|
|
|
*/ |
40
|
|
|
public function resource($data = null, $transformer = null, string $resourceKey = null) |
41
|
|
|
{ |
42
|
|
|
return static::resolveResourceBuilder()->make($data, $transformer)->withResourceKey($resourceKey)->get(); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Set a resource builder using a resolver callback. |
47
|
|
|
* |
48
|
|
|
* @param \Closure $resolver |
49
|
|
|
* @return void |
50
|
|
|
*/ |
51
|
|
|
public static function resourceBuilderResolver(Closure $resolver) |
52
|
|
|
{ |
53
|
|
|
static::$resourceBuilderResolver = $resolver; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Resolve a resource builder using the resolver. |
58
|
|
|
* |
59
|
|
|
* @return \Flugg\Responder\Resources\ResourceBuilder |
60
|
|
|
*/ |
61
|
|
|
protected static function resolveResourceBuilder() |
62
|
|
|
{ |
63
|
|
|
return call_user_func(static::$currentCursorResolver, $name); |
|
|
|
|
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Make a related resource. |
68
|
|
|
* |
69
|
|
|
* @param string $relation |
70
|
|
|
* @return \League\Fractal\Resource\ResourceInterface|false |
71
|
|
|
*/ |
72
|
|
|
protected function makeResource(string $relation, $data) |
73
|
|
|
{ |
74
|
|
|
if (key_exists($relation, $this->resources)) { |
75
|
|
|
return $this->resources[$relation]->setData($data); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $this->resource($data); |
79
|
|
|
} |
80
|
|
|
} |
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.