1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ResourceLinks\EndpointTypes; |
4
|
|
|
|
5
|
|
|
use Illuminate\Routing\RouteUrlGenerator; |
6
|
|
|
use Spatie\ResourceLinks\Exceptions\EndpointGenerationException; |
7
|
|
|
use Spatie\ResourceLinks\Formatters\LayeredFormatter; |
8
|
|
|
use Spatie\ResourceLinks\Formatters\Endpoint; |
9
|
|
|
use Spatie\ResourceLinks\Formatters\DefaultFormatter; |
10
|
|
|
use Spatie\ResourceLinks\Formatters\Formatter; |
11
|
|
|
use Spatie\ResourceLinks\ParameterResolver; |
12
|
|
|
use Illuminate\Database\Eloquent\Model; |
13
|
|
|
use Illuminate\Routing\Exceptions\UrlGenerationException; |
14
|
|
|
use Illuminate\Routing\Route; |
15
|
|
|
use Spatie\ResourceLinks\UrlResolver; |
16
|
|
|
|
17
|
|
|
class RouteEndpointType extends EndpointType |
18
|
|
|
{ |
19
|
|
|
/** @var \Illuminate\Routing\Route */ |
20
|
|
|
protected $route; |
21
|
|
|
|
22
|
|
|
/** @var string|null */ |
23
|
|
|
protected $httpVerb; |
24
|
|
|
|
25
|
|
|
/** @var string|null */ |
26
|
|
|
protected $name; |
27
|
|
|
|
28
|
|
|
public static function make(Route $route): RouteEndpointType |
29
|
|
|
{ |
30
|
|
|
return new self($route); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function __construct(Route $route) |
34
|
|
|
{ |
35
|
|
|
$this->route = $route; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function httpVerb(?string $httpVerb): RouteEndpointType |
39
|
|
|
{ |
40
|
|
|
$this->httpVerb = $httpVerb; |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function name(?string $name): RouteEndpointType |
46
|
|
|
{ |
47
|
|
|
$this->name = $name; |
48
|
|
|
|
49
|
|
|
return $this; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function getEndpoints(Model $model = null): array |
53
|
|
|
{ |
54
|
|
|
$parameterResolver = new ParameterResolver($model, $this->parameters); |
55
|
|
|
|
56
|
|
|
$urlResolver = new UrlResolver(app('url')); |
57
|
|
|
|
58
|
|
|
$endpoint = Endpoint::make( |
59
|
|
|
$this->name ?? $this->route->getActionMethod(), |
60
|
|
|
$this->httpVerb ?? $this->getHttpVerbForRoute($this->route), |
61
|
|
|
$urlResolver->resolve($this->route, $parameterResolver->forRoute($this->route)), |
62
|
|
|
$this->prefix |
63
|
|
|
); |
64
|
|
|
|
65
|
|
|
return $this->resolveFormatter()->format($endpoint); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function getHttpVerbForRoute(Route $route): string |
69
|
|
|
{ |
70
|
|
|
$httpVerbs = $route->methods; |
71
|
|
|
|
72
|
|
|
if ($httpVerbs === ['GET', 'HEAD']) { |
73
|
|
|
return 'GET'; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $httpVerbs[0]; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
private function resolveFormatter(): Formatter |
80
|
|
|
{ |
81
|
|
|
$formatter = is_null($this->formatter) |
82
|
|
|
? config('resource-links.formatter') |
83
|
|
|
: $this->formatter; |
84
|
|
|
|
85
|
|
|
return new $formatter; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|