|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\LaravelEndpointResources; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
6
|
|
|
use Illuminate\Routing\Exceptions\UrlGenerationException; |
|
7
|
|
|
use Illuminate\Routing\Route; |
|
8
|
|
|
use ReflectionParameter; |
|
9
|
|
|
|
|
10
|
|
|
class ParameterResolver |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var \Illuminate\Database\Eloquent\Model|null */ |
|
13
|
|
|
protected $model; |
|
14
|
|
|
|
|
15
|
|
|
/** @var array */ |
|
16
|
|
|
protected $defaultParameters; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(?Model $model, array $defaultParameters = []) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->model = $model; |
|
21
|
|
|
|
|
22
|
|
|
$this->defaultParameters = $defaultParameters; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function forRoute(Route $route): array |
|
26
|
|
|
{ |
|
27
|
|
|
$providedParameters = $this->getProvidedParameters(); |
|
28
|
|
|
|
|
29
|
|
|
return collect($route->signatureParameters()) |
|
30
|
|
|
->mapWithKeys(function (ReflectionParameter $signatureParameter) use ($providedParameters) { |
|
31
|
|
|
return [ |
|
32
|
|
|
$signatureParameter->getName() => $this->resolveParameter( |
|
33
|
|
|
$signatureParameter, |
|
34
|
|
|
$providedParameters |
|
35
|
|
|
), |
|
36
|
|
|
]; |
|
37
|
|
|
}) |
|
38
|
|
|
->reject(function ($parameter) { |
|
39
|
|
|
return $parameter === null; |
|
40
|
|
|
})->all(); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
protected function getProvidedParameters(): array |
|
44
|
|
|
{ |
|
45
|
|
|
return optional($this->model)->exists |
|
46
|
|
|
? array_merge($this->defaultParameters, [$this->model]) |
|
47
|
|
|
: $this->defaultParameters; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
protected function resolveParameter(ReflectionParameter $signatureParameter, array $providedParameters) |
|
51
|
|
|
{ |
|
52
|
|
|
if (array_key_exists($signatureParameter->getName(), $providedParameters)) { |
|
53
|
|
|
return $providedParameters[$signatureParameter->getName()]; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
foreach ($providedParameters as $providedParameter) { |
|
57
|
|
|
if (! is_object($providedParameter) || $signatureParameter->getType() === null) { |
|
58
|
|
|
continue; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
if ($signatureParameter->getType()->getName() === get_class($providedParameter)) { |
|
62
|
|
|
return $providedParameter; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return null; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|