1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TomHart\Restful; |
4
|
|
|
|
5
|
|
|
use Illuminate\Routing\Router; |
6
|
|
|
use TomHart\Restful\Concerns\HasLinks; |
7
|
|
|
|
8
|
|
|
class LinkBuilder |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Builds a link if possible |
12
|
|
|
* |
13
|
|
|
* @param HasLinks $model |
14
|
|
|
* @param string $routePart |
15
|
|
|
* @param Router $router |
16
|
|
|
* @return mixed[]|bool |
17
|
|
|
*/ |
18
|
|
|
public static function buildLink(HasLinks $model, string $routePart, Router $router) |
19
|
|
|
{ |
20
|
|
|
$routeStub = $model->getRouteName(); |
21
|
|
|
|
22
|
|
|
if ($routeStub === null) { |
23
|
|
|
return false; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
if (!$model->getKeyName()) { |
|
|
|
|
27
|
|
|
return false; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
// Make the route name, and check if it exists. |
31
|
|
|
$routeName = "$routeStub.$routePart"; |
32
|
|
|
|
33
|
|
|
if (!($route = $router->getRoutes()->getByName($routeName))) { |
34
|
|
|
return false; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
// Get any params needed to build the URL. |
38
|
|
|
$params = []; |
39
|
|
|
switch ($routePart) { |
40
|
|
|
case 'destroy': |
41
|
|
|
case 'update': |
42
|
|
|
case 'show': |
43
|
|
|
$params = [$model->getRouteKey() => $model->getAttribute((string)$model->getKeyName())]; |
44
|
|
|
break; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// Get the methods applicable to the route, ignoring HEAD and PATCH. |
48
|
|
|
$methods = collect($route->methods()); |
49
|
|
|
$methods = $methods->filter(static function ($item) { |
50
|
|
|
return !in_array($item, ['HEAD', 'PATCH']); |
51
|
|
|
})->map(static function ($str) { |
52
|
|
|
return strtolower($str); |
53
|
|
|
}); |
54
|
|
|
|
55
|
|
|
// If there's only 1, return just that, otherwise, return an array. |
56
|
|
|
if ($methods->count() === 1) { |
57
|
|
|
$methods = $methods->first(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
// Add! |
61
|
|
|
return [ |
62
|
|
|
'method' => $methods, |
63
|
|
|
'href' => route($routeName, $params, false) |
64
|
|
|
]; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: