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

Utils   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 211
Duplicated Lines 9.48 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 37
lcom 0
cbo 0
dl 20
loc 211
rs 9.44
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getFullUrl() 0 6 1
B getRouteClassAndMethodNames() 0 18 7
A replaceUrlParameterPlaceholdersWithValues() 0 21 4
A dumpException() 0 13 2
A deleteDirectoryAndContents() 0 7 1
A printPhpValue() 0 13 3
B printQueryParamsAsString() 10 36 8
A recursiveItemValue() 0 20 3
B printQueryParamsAsKeyValue() 10 44 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
138
                        $return = self::recursiveItemValue("[$item]", $itemValue);
139
140
                        unset($value[$item]);
141
142
                        $value = array_merge($value, $return);
143
                    }
144
145
                    // Hash query param (eg filter[name]=john should become "filter[name]": "john")
146
                    foreach ($value as $item => $itemValue) {
147
                        $item = strpos($item, '[')!==false ? str_replace(['%5B', '%5D'], ['[', ']'], urlencode($item)) : '[' . urlencode($item) . ']';
148
                        $qs .= "$paramName" . $item . '=' . urlencode($itemValue) . '&';
149
                    }
150
                }
151
            }
152
        }
153
154
        return rtrim($qs, '&');
155
    }
156
157
    private static function recursiveItemValue($item, $item_value)
158
    {
159
        $item_values = [];
160
161
        if (is_array($item_value)) {
162
            foreach ($item_value as $key => $value) {
163
                $item_values = array_merge(
164
                    $item_values,
165
                    self::recursiveItemValue(
166
                        sprintf("%s[%s]", $item, $key),
167
                        $value
168
                    )
169
                );
170
            }
171
        } else {
172
            return [$item => $item_value];
173
        }
174
175
        return $item_values;
176
    }
177
178
    public static function printQueryParamsAsKeyValue(
179
        array $cleanQueryParams,
180
        string $quote = "\"",
181
        string $delimiter = ":",
182
        int $spacesIndentation = 4,
183
        string $braces = "{}",
184
        int $closingBraceIndentation = 0
185
    ): string {
186
        $output = "{$braces[0]}\n";
187
        foreach ($cleanQueryParams as $parameter => $value) {
188
            if (!is_array($value)) {
189
                $output .= str_repeat(" ", $spacesIndentation);
190
                $output .= "$quote$parameter$quote$delimiter $quote$value$quote,\n";
191
            } else {
192
                if (array_keys($value)[0] === 0) {
193
                    // List query param (eg filter[]=haha should become "filter[]": "haha")
194
                    $output .= str_repeat(" ", $spacesIndentation);
195
                    $output .= "$quote$parameter" . "[]$quote$delimiter $quote$value[0]$quote,\n";
196
                } else {
197
                    // Hash query param (eg filter[name]=john should become "filter[name]": "john")
198 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...
199
                        if (!is_array($itemValue)) {
200
                            continue;
201
                        }
202
203
                        $return = self::recursiveItemValue("[$item]", $itemValue);
204
205
                        unset($value[$item]);
206
207
                        $value = array_merge($value, $return);
208
                    }
209
210
                    foreach ($value as $item => $itemValue) {
211
                        $item = strpos($item, '[')!==false ? $item : "[$item]";
212
213
                        $output .= str_repeat(" ", $spacesIndentation);
214
                        $output .= "$quote$parameter" . "$item$quote$delimiter $quote$itemValue$quote,\n";
215
                    }
216
                }
217
            }
218
        }
219
220
        return $output . str_repeat(" ", $closingBraceIndentation) . "{$braces[1]}";
221
    }
222
}
223