Completed
Pull Request — master (#516)
by
unknown
01:30
created

Utils::getRouteActionUses()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.0444
c 0
b 0
f 0
cc 6
nc 6
nop 1
1
<?php
2
3
namespace Mpociot\ApiDoc\Tools;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Routing\Route;
7
8
class Utils
9
{
10
    public static function getFullUrl(Route $route, array $bindings = []): string
11
    {
12
        $uri = $route->uri();
13
14
        return self::replaceUrlParameterBindings($uri, $bindings);
15
    }
16
17
    /**
18
     * @param array $action
19
     * @return array|null
20
     */
21
    public static function getRouteActionUses(array $action)
22
    {
23
        if ($action['uses'] !== null) {
24
            if (is_array($action['uses'])) {
25
                return $action['uses'];
26
            } elseif (is_string($action['uses'])) {
27
                return explode('@', $action['uses']);
28
            }
29
        }
30
        if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
31
            return [
32
                0 => $action[0],
33
                1 => $action[1],
34
            ];
35
        }
36
37
        return null;
38
    }
39
40
    /**
41
     * Transform parameters in URLs into real values (/users/{user} -> /users/2).
42
     * Uses bindings specified by caller, otherwise just uses '1'.
43
     *
44
     * @param string $uri
45
     * @param array $bindings
46
     *
47
     * @return mixed
48
     */
49
    protected static function replaceUrlParameterBindings(string $uri, array $bindings)
50
    {
51
        foreach ($bindings as $path => $binding) {
52
            // So we can support partial bindings like
53
            // 'bindings' => [
54
            //  'foo/{type}' => 4,
55
            //  'bar/{type}' => 2
56
            //],
57
            if (Str::is("*$path*", $uri)) {
58
                preg_match('/({.+?})/', $path, $parameter);
59
                $uri = str_replace("{$parameter['1']}", $binding, $uri);
60
            }
61
        }
62
        // Replace any unbound parameters with '1'
63
        $uri = preg_replace('/{(.+?)}/', 1, $uri);
64
65
        return $uri;
66
    }
67
}
68