Completed
Push — 2.x ( aec113...79378e )
by Mikaël
45:36
created

Utils::getContentFromUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 8
dl 0
loc 8
ccs 7
cts 7
cp 1
crap 2
rs 10
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace WsdlToPhp\PackageGenerator\Generator;
4
5
use WsdlToPhp\PackageGenerator\ConfigurationReader\GeneratorOptions;
6
7
class Utils
8
{
9
    /**
10
     * Gets upper case word among a string from the end or from the beginning part
11
     * @param string $optionValue
12
     * @param string $string the string from which we can extract the part
13
     * @return string
14
     */
15 510
    public static function getPart($optionValue, $string)
16
    {
17 510
        $elementType = '';
18 510
        $string = str_replace('_', '', $string);
19 510
        $string = preg_replace('/([0-9])/', '', $string);
20 510
        if (!empty($string)) {
21 85
            switch ($optionValue) {
22 425
                case GeneratorOptions::VALUE_END:
23 30
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
24 30
                    $partsCount = count($parts);
0 ignored issues
show
Bug introduced by
It seems like $parts can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

24
                    $partsCount = count(/** @scrutinizer ignore-type */ $parts);
Loading history...
25 30
                    if (!empty($parts[$partsCount - 1])) {
26 24
                        $elementType = mb_substr($string, mb_strrpos($string, implode('', array_slice($parts, -1))) - 1);
27 12
                    } else {
28 12
                        for ($i = $partsCount - 1; $i >= 0; $i--) {
29 12
                            $part = trim($parts[$i]);
30 12
                            if (!empty($part)) {
31 6
                                break;
32
                            }
33 6
                        }
34 12
                        $elementType = mb_substr($string, ((count($parts) - 2 - $i) + 1) * -1);
35
                    }
36 30
                    break;
37 400
                case GeneratorOptions::VALUE_START:
38 450
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
39 450
                    $partsCount = count($parts);
40 450
                    if (empty($parts[0]) && !empty($parts[1])) {
41 450
                        $elementType = mb_substr($string, 0, mb_strlen($parts[1]) + 1);
42 225
                    } else {
43 18
                        for ($i = 0; $i < $partsCount; $i++) {
44 18
                            $part = trim($parts[$i]);
45 18
                            if (!empty($part)) {
46 18
                                break;
47
                            }
48 9
                        }
49 18
                        $elementType = mb_substr($string, 0, $i);
50
                    }
51 450
                    break;
52 25
                case GeneratorOptions::VALUE_NONE:
53 24
                    $elementType = $string;
54 24
                    break;
55 3
                default:
56 6
                    break;
57 3
            }
58 255
        }
59 510
        return $elementType;
60
    }
61
    /**
62
     * Get content from url using a proxy or not
63
     * @param string $url
64
     * @param string $basicAuthLogin
65
     * @param string $basicAuthPassword
66
     * @param string $proxyHost
67
     * @param string $proxyPort
68
     * @param string $proxyLogin
69
     * @param string $proxyPassword
70
     * @param array $contextOptions
71
     * @return string
72
     */
73 12
    public static function getContentFromUrl($url, $basicAuthLogin = null, $basicAuthPassword = null, $proxyHost = null, $proxyPort = null, $proxyLogin = null, $proxyPassword = null, array $contextOptions = [])
74
    {
75 12
        $context = null;
76 12
        $options = self::getStreamContextOptions($basicAuthLogin, $basicAuthPassword, $proxyHost, $proxyPort, $proxyLogin, $proxyPassword, $contextOptions);
77 12
        if (!empty($options)) {
78 9
            $context = stream_context_create($options);
79 3
        }
80 12
        return file_get_contents($url, false, $context);
81
    }
82
    /**
83
     * @param string $basicAuthLogin
84
     * @param string $basicAuthPassword
85
     * @param string $proxyHost
86
     * @param string $proxyPort
87
     * @param string $proxyLogin
88
     * @param string $proxyPassword
89
     * @param array $contextOptions
90
     * @return string[]
91
     */
92 36
    public static function getStreamContextOptions($basicAuthLogin = null, $basicAuthPassword = null, $proxyHost = null, $proxyPort = null, $proxyLogin = null, $proxyPassword = null, array $contextOptions = [])
93
    {
94 36
        $proxyOptions = $basicAuthOptions = [];
95 36
        if (!empty($basicAuthLogin) && !empty($basicAuthPassword)) {
96
            $basicAuthOptions = [
97
                'http' => [
98
                    'header' => [
99 18
                        sprintf('Authorization: Basic %s', base64_encode(sprintf('%s:%s', $basicAuthLogin, $basicAuthPassword))),
100 9
                    ],
101 9
                ],
102 9
            ];
103 9
        }
104 36
        if (!empty($proxyHost)) {
105
            $proxyOptions = [
106
                'http' => [
107 18
                    'proxy' => sprintf('tcp://%s%s', $proxyHost, empty($proxyPort) ? '' : sprintf(':%s', $proxyPort)),
108
                    'header' => [
109 18
                        sprintf('Proxy-Authorization: Basic %s', base64_encode(sprintf('%s:%s', $proxyLogin, $proxyPassword))),
110 9
                    ],
111 9
                ],
112 9
            ];
113 9
        }
114 36
        return array_merge_recursive($contextOptions, $proxyOptions, $basicAuthOptions);
115
    }
116
    /**
117
     * Returns the value with good type
118
     * @param mixed $value the value
119
     * @param string $knownType the value
120
     * @return mixed
121
     */
122 318
    public static function getValueWithinItsType($value, $knownType = null)
123
    {
124 318
        if (is_int($value) || (!is_null($value) && in_array($knownType, [
125 156
            'time',
126 78
            'positiveInteger',
127 78
            'unsignedLong',
128 78
            'unsignedInt',
129 78
            'short',
130 78
            'long',
131 78
            'int',
132 78
            'integer',
133 318
        ], true))) {
134 18
            return intval($value);
135 318
        } elseif (is_float($value) || (!is_null($value) && in_array($knownType, [
136 156
            'float',
137 78
            'double',
138 78
            'decimal',
139 318
        ], true))) {
140 6
            return floatval($value);
141 318
        } elseif (is_bool($value) || (!is_null($value) && in_array($knownType, [
142 156
            'bool',
143 78
            'boolean',
144 318
        ], true))) {
145 18
            return ($value === 'true' || $value === true || $value === 1 || $value === '1');
146
        }
147 312
        return $value;
148
    }
149
    /**
150
     * @param string $origin
151
     * @param string $destination
152
     * @return string
153
     */
154 210
    public static function resolveCompletePath($origin, $destination)
155
    {
156 210
        $resolvedPath = $destination;
157 210
        if (!empty($destination) && mb_strpos($destination, 'http://') === false && mb_strpos($destination, 'https://') === false && !empty($origin)) {
158 210
            if (mb_substr($destination, 0, 2) === './') {
159 12
                $destination = mb_substr($destination, 2);
160 6
            }
161 210
            $destinationParts = explode('/', $destination);
162 210
            $fileParts = pathinfo($origin);
163 210
            $fileBasename = (is_array($fileParts) && array_key_exists('basename', $fileParts)) ? $fileParts['basename'] : '';
164 210
            $parts = parse_url(str_replace('/' . $fileBasename, '', $origin));
165 210
            $scheme = (is_array($parts) && array_key_exists('scheme', $parts)) ? $parts['scheme'] : '';
166 210
            $host = (is_array($parts) && array_key_exists('host', $parts)) ? $parts['host'] : '';
167 210
            $path = (is_array($parts) && array_key_exists('path', $parts)) ? $parts['path'] : '';
168 210
            $path = str_replace('/' . $fileBasename, '', $path);
169 210
            $pathParts = explode('/', $path);
170 210
            $finalPath = implode('/', $pathParts);
171 210
            foreach ($destinationParts as $locationPart) {
172 210
                if ($locationPart == '..') {
173 12
                    $finalPath = mb_substr($finalPath, 0, mb_strrpos($finalPath, '/', 0));
174 6
                } else {
175 210
                    $finalPath .= '/' . $locationPart;
176
                }
177 105
            }
178 210
            $port = (is_array($parts) && array_key_exists('port', $parts)) ? $parts['port'] : '';
179
            /**
180
             * Remote file
181
             */
182 210
            if (!empty($scheme) && !empty($host)) {
183 6
                $resolvedPath = str_replace('urn', 'http', $scheme) . '://' . $host . (!empty($port) ? ':' . $port : '') . str_replace('//', '/', $finalPath);
184 207
            } elseif (empty($scheme) && empty($host) && count($pathParts)) {
185
                /**
186
                 * Local file
187
                 */
188 204
                if (is_file($finalPath)) {
189 204
                    $resolvedPath = $finalPath;
190 102
                }
191 102
            }
192 105
        }
193 210
        return $resolvedPath;
194
    }
195
    /**
196
     * Clean comment
197
     * @param string $comment the comment to clean
198
     * @param string $glueSeparator ths string to use when gathering values
199
     * @param bool $uniqueValues indicates if comment values must be unique or not
200
     * @return string
201
     */
202 348
    public static function cleanComment($comment, $glueSeparator = ',', $uniqueValues = true)
203
    {
204 348
        if (!is_scalar($comment) && !is_array($comment)) {
0 ignored issues
show
introduced by
The condition is_scalar($comment) is always true.
Loading history...
205 6
            return '';
206
        }
207 342
        return trim(str_replace('*/', '*[:slash:]', is_scalar($comment) ? $comment : implode($glueSeparator, $uniqueValues ? array_unique($comment) : $comment)));
0 ignored issues
show
introduced by
The condition is_scalar($comment) is always true.
Loading history...
208
    }
209
    /**
210
     * Clean a string to make it valid as PHP variable
211
     * See more about the used regular expression at {@link http://www.regular-expressions.info/unicode.html}:
212
     * - \p{L} for any valid letter
213
     * - \p{N} for any valid number
214
     * - /u for supporting unicode
215
     * @param string $string the string to clean
216
     * @param bool $keepMultipleUnderscores optional, allows to keep the multiple consecutive underscores
217
     * @return string
218
     */
219 1164
    public static function cleanString($string, $keepMultipleUnderscores = true)
220
    {
221 1164
        $cleanedString = preg_replace('/[^\p{L}\p{N}_]/u', '_', $string);
222 1164
        if (!$keepMultipleUnderscores) {
223 240
            $cleanedString = preg_replace('/[_]+/', '_', $cleanedString);
224 120
        }
225 1164
        return $cleanedString;
226
    }
227
    /**
228
     * @param string $namespacedClassName
229
     * @return string
230
     */
231 444
    public static function removeNamespace($namespacedClassName)
232
    {
233 444
        $elements = explode('\\', $namespacedClassName);
234 444
        return (string) array_pop($elements);
235
    }
236
    /**
237
     * @param string $directory
238
     * @param int $permissions
239
     * @return bool
240
     */
241 492
    public static function createDirectory($directory, $permissions = 0775)
242
    {
243 492
        if (!is_dir($directory)) {
244 54
            mkdir($directory, $permissions, true);
245 27
        }
246 492
        return true;
247
    }
248
    /**
249
     * Save schemas to schemasFolder
250
     * Filename will be extracted from schemasUrl or default schema.wsdl will be used
251
     * @param string $destinationFolder
252
     * @param string $schemasFolder
253
     * @param string $schemasUrl
254
     * @param string $content
255
     * @return string
256
     */
257 12
    public static function saveSchemas($destinationFolder, $schemasFolder, $schemasUrl, $content)
258
    {
259 12
        if (($schemasFolder === null) || empty($schemasFolder)) {
260
            // if null or empty schemas folder was provided
261
            // default schemas folder will be wsdl
262 6
            $schemasFolder = 'wsdl';
263 3
        }
264 12
        $schemasPath = rtrim($destinationFolder, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . rtrim($schemasFolder, DIRECTORY_SEPARATOR);
265
        // Here we must cover all possible variants
266 12
        if ((mb_strpos(mb_strtolower($schemasUrl), '.wsdl') !== false) || (mb_strpos(mb_strtolower($schemasUrl), '.xsd') !== false) || (mb_strpos(mb_strtolower($schemasUrl), '.xml') !== false)) {
267 12
            $filename = basename($schemasUrl);
268 6
        } else {
269
            // if $url is like http://example.com/index.php?WSDL default filename will be schema.wsdl
270 6
            $filename = 'schema.wsdl';
271
        }
272 12
        self::createDirectory($schemasPath);
273 12
        file_put_contents($schemasPath . DIRECTORY_SEPARATOR . $filename, $content);
274 12
        return $schemasPath . DIRECTORY_SEPARATOR . $filename;
275
    }
276
}
277