Completed
Pull Request — master (#700)
by
unknown
01:21
created

Utils::getFullUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Mpociot\ApiDoc\Tools;
4
5
use Illuminate\Routing\Route;
6
use Illuminate\Support\Arr;
7
use League\Flysystem\Adapter\Local;
8
use League\Flysystem\Filesystem;
9
use Symfony\Component\Console\Output\ConsoleOutput;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\VarExporter\VarExporter;
12
13
class Utils
14
{
15
    public static function getFullUrl(Route $route, array $urlParameters = []): string
16
    {
17
        $uri = $route->uri();
18
19
        return self::replaceUrlParameterPlaceholdersWithValues($uri, $urlParameters);
20
    }
21
22
    /**
23
     * @param array|Route $routeOrAction
24
     *
25
     * @return array|null
26
     */
27
    public static function getRouteClassAndMethodNames($routeOrAction)
28
    {
29
        $action = $routeOrAction instanceof Route ? $routeOrAction->getAction() : $routeOrAction;
0 ignored issues
show
Bug introduced by
The class Illuminate\Routing\Route does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
30
31
        if ($action['uses'] !== null) {
32
            if (is_array($action['uses'])) {
33
                return $action['uses'];
34
            } elseif (is_string($action['uses'])) {
35
                return explode('@', $action['uses']);
36
            }
37
        }
38
        if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
39
            return [
40
                0 => $action[0],
41
                1 => $action[1],
42
            ];
43
        }
44
    }
45
46
    /**
47
     * Transform parameters in URLs into real values (/users/{user} -> /users/2).
48
     * Uses @urlParam values specified by caller, otherwise just uses '1'.
49
     *
50
     * @param string $uri
51
     * @param array $urlParameters Dictionary of url params and example values
52
     *
53
     * @return mixed
54
     */
55
    public static function replaceUrlParameterPlaceholdersWithValues(string $uri, array $urlParameters)
56
    {
57
        $matches = preg_match_all('/{.+?}/i', $uri, $parameterPaths);
58
        if (!$matches) {
59
            return $uri;
60
        }
61
62
        foreach ($parameterPaths[0] as $parameterPath) {
63
            $key = trim($parameterPath, '{?}');
64
            if (isset($urlParameters[$key])) {
65
                $example = $urlParameters[$key];
66
                $uri = str_replace($parameterPath, $example, $uri);
67
            }
68
        }
69
        // Remove unbound optional parameters with nothing
70
        $uri = preg_replace('#{([^/]+\?)}#', '', $uri);
71
        // Replace any unbound non-optional parameters with '1'
72
        $uri = preg_replace('#{([^/]+)}#', '1', $uri);
73
74
        return $uri;
75
    }
76
77
    public static function dumpException(\Exception $e)
78
    {
79
        if (class_exists(\NunoMaduro\Collision\Handler::class)) {
80
            $output = new ConsoleOutput(OutputInterface::VERBOSITY_VERBOSE);
81
            $handler = new \NunoMaduro\Collision\Handler(new \NunoMaduro\Collision\Writer($output));
82
            $handler->setInspector(new \Whoops\Exception\Inspector($e));
83
            $handler->setException($e);
84
            $handler->handle();
85
        } else {
86
            dump($e);
87
            echo "You can get better exception output by installing the library \nunomaduro/collision (PHP 7.1+ only).\n";
88
        }
89
    }
90
91
    public static function deleteDirectoryAndContents($dir)
92
    {
93
        $dir = ltrim($dir, "/");
94
        $adapter = new Local(realpath(__DIR__ . '/../../'));
95
        $fs = new Filesystem($adapter);
96
        $fs->deleteDir($dir);
97
    }
98
99
    /**
100
     * @param mixed $value
101
     * @param int $indentationLevel
102
     *
103
     * @return string
104
     * @throws \Symfony\Component\VarExporter\Exception\ExceptionInterface
105
     *
106
     */
107
    public static function printPhpValue($value, $indentationLevel = 0)
108
    {
109
        $output = VarExporter::export($value);
110
        // Padding with x spaces so they align
111
        $split = explode("\n", $output);
112
        $result = '';
113
        $padWith = str_repeat(' ', $indentationLevel);
114
        foreach ($split as $index => $line) {
115
            $result .= ($index == 0 ? '' : "\n$padWith") . $line;
116
        }
117
118
        return $result;
119
    }
120
121
    public static function printQueryParamsAsString(array $cleanQueryParams): string
122
    {
123
        $qs = "";
124
        foreach ($cleanQueryParams as $parameter => $value) {
125
            $paramName = urlencode($parameter);
126
127
            if (!is_array($value)) {
128
                $qs .= "$paramName=" . urlencode($value) . "&";
129
            } else {
130
                if (array_keys($value)[0] === 0) {
131
                    // List query param (eg filter[]=haha should become "filter[]": "haha")
132
                    $qs .= "$paramName" . "[]=" . urlencode($value[0]) . "&";
133
                } else {
134
                    // Hash query param (eg filter[name]=john should become "filter[name]": "john")
135
                    foreach ($value as $item => $itemValue) {
136
                        $qs .= "$paramName" . "[" . urlencode($item) . "]=" . urlencode($itemValue) . "&";
137
                    }
138
                }
139
140
            }
141
        }
142
143
        return rtrim($qs, '&');
144
    }
145
146
    public static function printQueryParamsAsKeyValue(
147
        array $cleanQueryParams,
148
        string $quote = "\"",
149
        string $delimiter = ":",
150
        int $spacesIndentation = 4,
151
        string $braces = "{}",
152
        int $closingBraceIndentation = 0
153
    ): string
154
    {
155
        $output = "{$braces[0]}\n";
156
        foreach ($cleanQueryParams as $parameter => $value) {
157
            if (!is_array($value)) {
158
                $output .= str_repeat(" ", $spacesIndentation);
159
                    $output .= "$quote$parameter$quote$delimiter $quote$value$quote,\n";
160
            } else {
161
                if (array_keys($value)[0] === 0) {
162
                    // List query param (eg filter[]=haha should become "filter[]": "haha")
163
                    $output .= str_repeat(" ", $spacesIndentation);
164
                    $output .= "$quote$parameter"."[]$quote$delimiter $quote$value[0]$quote,\n";
165
                } else {
166
                    // Hash query param (eg filter[name]=john should become "filter[name]": "john")
167
                    foreach ($value as $item => $itemValue) {
168
                        $output .= str_repeat(" ", $spacesIndentation);
169
                        $output .= "$quote$parameter"."[$item]$quote$delimiter $quote$itemValue$quote,\n";
170
                    }
171
                }
172
173
            }
174
        }
175
176
        return $output.str_repeat(" ", $closingBraceIndentation)."{$braces[1]}";
177
    }
178
}
179