Completed
Pull Request — master (#782)
by
unknown
01:20
created

Utils::printQueryParamsAsKeyValue()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 43

Duplication

Lines 10
Ratio 23.26 %

Importance

Changes 0
Metric Value
dl 10
loc 43
rs 7.9875
c 0
b 0
f 0
cc 8
nc 12
nop 6
1
<?php
2
3
namespace Mpociot\ApiDoc\Tools;
4
5
use Illuminate\Routing\Route;
6
use League\Flysystem\Adapter\Local;
7
use League\Flysystem\Filesystem;
8
use Symfony\Component\Console\Output\ConsoleOutput;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\VarExporter\VarExporter;
11
12
class Utils
13
{
14
    public static function getFullUrl(Route $route, array $urlParameters = []): string
15
    {
16
        $uri = $route->uri();
17
18
        return self::replaceUrlParameterPlaceholdersWithValues($uri, $urlParameters);
19
    }
20
21
    /**
22
     * @param array|Route $routeOrAction
23
     *
24
     * @return array|null
25
     */
26
    public static function getRouteClassAndMethodNames($routeOrAction)
27
    {
28
        $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...
29
30
        if ($action['uses'] !== null) {
31
            if (is_array($action['uses'])) {
32
                return $action['uses'];
33
            } elseif (is_string($action['uses'])) {
34
                return explode('@', $action['uses']);
35
            }
36
        }
37
        if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
38
            return [
39
                0 => $action[0],
40
                1 => $action[1],
41
            ];
42
        }
43
    }
44
45
    /**
46
     * Transform parameters in URLs into real values (/users/{user} -> /users/2).
47
     * Uses @urlParam values specified by caller, otherwise just uses '1'.
48
     *
49
     * @param string $uri
50
     * @param array $urlParameters Dictionary of url params and example values
51
     *
52
     * @return mixed
53
     */
54
    public static function replaceUrlParameterPlaceholdersWithValues(string $uri, array $urlParameters)
55
    {
56
        $matches = preg_match_all('/{.+?}/i', $uri, $parameterPaths);
57
        if (!$matches) {
58
            return $uri;
59
        }
60
61
        foreach ($parameterPaths[0] as $parameterPath) {
62
            $key = trim($parameterPath, '{?}');
63
            if (isset($urlParameters[$key])) {
64
                $example = $urlParameters[$key];
65
                $uri = str_replace($parameterPath, $example, $uri);
66
            }
67
        }
68
        // Remove unbound optional parameters with nothing
69
        $uri = preg_replace('#{([^/]+\?)}#', '', $uri);
70
        // Replace any unbound non-optional parameters with '1'
71
        $uri = preg_replace('#{([^/]+)}#', '1', $uri);
72
73
        return $uri;
74
    }
75
76
    public static function dumpException(\Exception $e)
77
    {
78
        if (class_exists(\NunoMaduro\Collision\Handler::class)) {
79
            $output = new ConsoleOutput(OutputInterface::VERBOSITY_VERBOSE);
80
            $handler = new \NunoMaduro\Collision\Handler(new \NunoMaduro\Collision\Writer($output));
81
            $handler->setInspector(new \Whoops\Exception\Inspector($e));
82
            $handler->setException($e);
83
            $handler->handle();
84
        } else {
85
            dump($e);
86
            echo "You can get better exception output by installing the library \nunomaduro/collision (PHP 7.1+ only).\n";
87
        }
88
    }
89
90
    public static function deleteDirectoryAndContents($dir)
91
    {
92
        $dir = ltrim($dir, '/');
93
        $adapter = new Local(realpath(__DIR__ . '/../../'));
94
        $fs = new Filesystem($adapter);
95
        $fs->deleteDir($dir);
96
    }
97
98
    /**
99
     * @param mixed $value
100
     * @param int $indentationLevel
101
     *
102
     * @return string
103
     * @throws \Symfony\Component\VarExporter\Exception\ExceptionInterface
104
     *
105
     */
106
    public static function printPhpValue($value, int $indentationLevel = 0): string
107
    {
108
        $output = VarExporter::export($value);
109
        // Padding with x spaces so they align
110
        $split = explode("\n", $output);
111
        $result = '';
112
        $padWith = str_repeat(' ', $indentationLevel);
113
        foreach ($split as $index => $line) {
114
            $result .= ($index == 0 ? '' : "\n$padWith") . $line;
115
        }
116
117
        return $result;
118
    }
119
120
    public static function printQueryParamsAsString(array $cleanQueryParams): string
121
    {
122
        $qs = '';
123
        foreach ($cleanQueryParams as $parameter => $value) {
124
            $paramName = urlencode($parameter);
125
126
            if (!is_array($value)) {
127
                $qs .= "$paramName=" . urlencode($value) . "&";
128
            } else {
129
                if (array_keys($value)[0] === 0) {
130
                    // List query param (eg filter[]=haha should become "filter[]": "haha")
131
                    $qs .= "$paramName" . '[]=' . urlencode($value[0]) . '&';
132
                } else {
133 View Code Duplication
                    foreach ($value as $item => $itemValue) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
                        if(!is_array($itemValue))
135
                            continue;
136
137
                        $return = self::recursiveItemValue("[$item]", $itemValue);
138
139
                        unset($value[$item]);
140
141
                        $value = array_merge($value, $return);
142
                    }
143
144
                    // Hash query param (eg filter[name]=john should become "filter[name]": "john")
145
                    foreach ($value as $item => $itemValue) {
146
                        $item = strpos($item, '[')!==false ? str_replace(['%5B', '%5D'], ['[', ']'], urlencode($item)) : '[' . urlencode($item) . ']';
147
                        $qs .= "$paramName" . $item . '=' . urlencode($itemValue) . '&';
148
                    }
149
                }
150
            }
151
        }
152
153
        return rtrim($qs, '&');
154
    }
155
156
    private static function recursiveItemValue($item, $item_value)
157
    {
158
        $item_values = [];
159
160
        if(is_array($item_value)) {
161
            foreach ($item_value as $key => $value) {
162
                $item_values = array_merge(
163
                    $item_values, 
164
                    self::recursiveItemValue(
165
                        sprintf("%s[%s]", $item, $key), 
166
                        $value
167
                    )
168
                );
169
            }
170
        }else{
171
            return [$item => $item_value];
172
        }
173
174
        return $item_values;
175
    }
176
177
    public static function printQueryParamsAsKeyValue(
178
        array $cleanQueryParams,
179
        string $quote = "\"",
180
        string $delimiter = ":",
181
        int $spacesIndentation = 4,
182
        string $braces = "{}",
183
        int $closingBraceIndentation = 0
184
    ): string {
185
        $output = "{$braces[0]}\n";
186
        foreach ($cleanQueryParams as $parameter => $value) {
187
            if (!is_array($value)) {
188
                $output .= str_repeat(" ", $spacesIndentation);
189
                $output .= "$quote$parameter$quote$delimiter $quote$value$quote,\n";
190
            } else {
191
                if (array_keys($value)[0] === 0) {
192
                    // List query param (eg filter[]=haha should become "filter[]": "haha")
193
                    $output .= str_repeat(" ", $spacesIndentation);
194
                    $output .= "$quote$parameter" . "[]$quote$delimiter $quote$value[0]$quote,\n";
195
                } else {
196
                    // Hash query param (eg filter[name]=john should become "filter[name]": "john")
197 View Code Duplication
                    foreach ($value as $item => $itemValue) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
198
                        if(!is_array($itemValue))
199
                            continue;
200
201
                        $return = self::recursiveItemValue("[$item]", $itemValue);
202
203
                        unset($value[$item]);
204
205
                        $value = array_merge($value, $return);
206
                    }
207
208
                    foreach ($value as $item => $itemValue) {
209
                        $item = strpos($item, '[')!==false ? $item : "[$item]";
210
211
                        $output .= str_repeat(" ", $spacesIndentation);
212
                        $output .= "$quote$parameter" . "$item$quote$delimiter $quote$itemValue$quote,\n";
213
                    }
214
                }
215
            }
216
        }
217
218
        return $output . str_repeat(" ", $closingBraceIndentation) . "{$braces[1]}";
219
    }
220
}
221