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

Utils::replaceUrlParameterBindings()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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