Passed
Pull Request — master (#1)
by Tom
03:27
created

LinkBuilder::buildLink()   B

Complexity

Conditions 8
Paths 11

Size

Total Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 7.8901
c 0
b 0
f 0
cc 8
nc 11
nop 3
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()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $model->getKeyName() of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch 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:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
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