Completed
Push — develop ( f0062e...5ed25a )
by Mikaël
31:25
created

Utils::getContentFromUrlContextOptions()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 17
cts 17
cp 1
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 14
nc 4
nop 8
crap 5

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 admong 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 472
    public static function getPart($optionValue, $string)
16
    {
17 472
        $elementType = '';
18 472
        $string = str_replace('_', '', $string);
19 472
        $string = preg_replace('/([0-9])/', '', $string);
20 472
        if (!empty($string)) {
21
            switch ($optionValue) {
22 472
                case GeneratorOptions::VALUE_END:
23 12
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
24 12
                    $partsCount = count($parts);
25 12
                    if ($partsCount == 0) {
26
                        $elementType = $string;
27 12
                    } elseif (!empty($parts[$partsCount - 1])) {
28 12
                        $elementType = substr($string, strrpos($string, implode('', array_slice($parts, -1))) - 1);
29 9
                    } else {
30
                        for ($i = $partsCount - 1; $i >= 0; $i--) {
31
                            $part = trim($parts[$i]);
32
                            if (!empty($part)) {
33
                                break;
34
                            }
35
                        }
36
                        $elementType = substr($string, ((count($parts) - 2 - $i) + 1) * -1);
37
                    }
38 12
                    break;
39 460
                case GeneratorOptions::VALUE_START:
40 460
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
41 460
                    $partsCount = count($parts);
42 460
                    if ($partsCount == 0) {
43
                        $elementType = $string;
44 460
                    } elseif (empty($parts[0]) && !empty($parts[1])) {
45 460
                        $elementType = substr($string, 0, strlen($parts[1]) + 1);
46 345
                    } else {
47 16
                        for ($i = 0; $i < $partsCount; $i++) {
48 16
                            $part = trim($parts[$i]);
49 16
                            if (!empty($part)) {
50 16
                                break;
51
                            }
52 12
                        }
53 16
                        $elementType = substr($string, 0, $i);
54
                    }
55 460
                    break;
56
                default:
57
                    break;
58
            }
59 354
        }
60 472
        return $elementType;
61
    }
62
    /**
63
     * Get content from url using a proxy or not
64
     * @param string $url
65
     * @param string $basicAuthLogin
66
     * @param string $basicAuthPassword
67
     * @param string $proxyHost
68
     * @param string $proxyPort
69
     * @param string $proxyLogin
70
     * @param string $proxyPassword
71
     * @param array $contextOptions
72
     * @return string
73
     */
74 8
    public static function getContentFromUrl($url, $basicAuthLogin = null, $basicAuthPassword = null, $proxyHost = null, $proxyPort = null, $proxyLogin = null, $proxyPassword = null, array $contextOptions = array())
75
    {
76 8
        $context = null;
77 8
        $options = self::getStreamContextOptions($basicAuthLogin, $basicAuthPassword, $proxyHost, $proxyPort, $proxyLogin, $proxyPassword, $contextOptions);
78 8
        if (!empty($options)) {
79 5
            $context = stream_context_create($options);
80 3
        }
81 8
        return file_get_contents($url, false, $context);
82
    }
83
    /**
84
     * @param string $basicAuthLogin
85
     * @param string $basicAuthPassword
86
     * @param string $proxyHost
87
     * @param string $proxyPort
88
     * @param string $proxyLogin
89
     * @param string $proxyPassword
90
     * @param array $contextOptions
91
     * @return string[]
92
     */
93
    public static function getStreamContextOptions($basicAuthLogin = null, $basicAuthPassword = null, $proxyHost = null, $proxyPort = null, $proxyLogin = null, $proxyPassword = null, array $contextOptions = array())
94 24
    {
95
        $proxyOptions = $basicAuthOptions = array();
96 24
        if (!empty($basicAuthLogin) && !empty($basicAuthPassword)) {
97 24
            $basicAuthOptions = array(
98 24
                'http' => array(
99
                    'header' => array(
100
                        sprintf('Authorization: Basic %s', base64_encode(sprintf('%s:%s', $basicAuthLogin, $basicAuthPassword))),
101
                    ),
102 12
                ),
103 9
            );
104 9
        }
105 9
        if (!empty($proxyHost)) {
106 9
            $proxyOptions = array(
107 24
                'http' => array(
108
                    'proxy' => sprintf('tcp://%s%s', $proxyHost, empty($proxyPort) ? '' : sprintf(':%s', $proxyPort)),
109
                    'header' => array(
110 12
                        sprintf('Proxy-Authorization: Basic %s', base64_encode(sprintf('%s:%s', $proxyLogin, $proxyPassword))),
111
                    ),
112 12
                ),
113 9
            );
114 9
        }
115 9
        return array_merge_recursive($contextOptions, $proxyOptions, $basicAuthOptions);
116 9
    }
117 24
    /**
118
     * Returns the value with good type
119
     * @param mixed $value the value
120
     * @param string $knownType the value
121
     * @return mixed
122
     */
123
    public static function getValueWithinItsType($value, $knownType = null)
124 580
    {
125
        if (is_int($value) || (!is_null($value) && in_array($knownType, array(
126 580
            'time',
127 580
            'positiveInteger',
128 435
            'unsignedLong',
129 435
            'unsignedInt',
130 435
            'short',
131 435
            'long',
132 435
            'int',
133 435
            'integer',
134 435
        ), true))) {
135 580
            return intval($value);
136 8
        } elseif (is_float($value) || (!is_null($value) && in_array($knownType, array(
137 580
            'float',
138 580
            'double',
139 435
            'decimal',
140 435
        ), true))) {
141 580
            return floatval($value);
142
        } elseif (is_bool($value) || (!is_null($value) && in_array($knownType, array(
143 580
            'bool',
144 580
            'boolean',
145 435
        ), true))) {
146 580
            return ($value === 'true' || $value === true || $value === 1 || $value === '1');
147 108
        }
148
        return $value;
149 564
    }
150
    /**
151
     * @param string $origin
152
     * @param string $destination
153
     * @return string
154
     */
155
    public static function resolveCompletePath($origin, $destination)
156 188
    {
157
        $resolvedPath = $destination;
158 188
        if (!empty($destination) && strpos($destination, 'http://') === false && strpos($destination, 'https://') === false && !empty($origin)) {
159 188
            if (substr($destination, 0, 2) === './') {
160 188
                $destination = substr($destination, 2);
161 8
            }
162 6
            $destinationParts = explode('/', $destination);
163 188
            $fileParts = pathinfo($origin);
164 188
            $fileBasename = (is_array($fileParts) && array_key_exists('basename', $fileParts)) ? $fileParts['basename'] : '';
165 188
            $parts = parse_url(str_replace('/' . $fileBasename, '', $origin));
166 188
            $scheme = (is_array($parts) && array_key_exists('scheme', $parts)) ? $parts['scheme'] : '';
167 188
            $host = (is_array($parts) && array_key_exists('host', $parts)) ? $parts['host'] : '';
168 188
            $path = (is_array($parts) && array_key_exists('path', $parts)) ? $parts['path'] : '';
169 188
            $path = str_replace('/' . $fileBasename, '', $path);
170 188
            $pathParts = explode('/', $path);
171 188
            $finalPath = implode('/', $pathParts);
172 188
            foreach ($destinationParts as $locationPart) {
173 188
                if ($locationPart == '..') {
174 188
                    $finalPath = substr($finalPath, 0, strrpos($finalPath, '/', 0));
175 8
                } else {
176 6
                    $finalPath .= '/' . $locationPart;
177 188
                }
178
            }
179 141
            $port = (is_array($parts) && array_key_exists('port', $parts)) ? $parts['port'] : '';
180 188
            /**
181
             * Remote file
182
             */
183
            if (!empty($scheme) && !empty($host)) {
184 188
                $resolvedPath = str_replace('urn', 'http', $scheme) . '://' . $host . (!empty($port) ? ':' . $port : '') . str_replace('//', '/', $finalPath);
185 4
            } elseif (empty($scheme) && empty($host) && count($pathParts)) {
186 187
                /**
187
                 * Local file
188
                 */
189
                if (is_file($finalPath)) {
190 184
                    $resolvedPath = $finalPath;
191 184
                }
192 138
            }
193 138
        }
194 141
        return $resolvedPath;
195 188
    }
196
    /**
197
     * Clean comment
198
     * @param string $comment the comment to clean
199
     * @param string $glueSeparator ths string to use when gathering values
200
     * @param bool $uniqueValues indicates if comment values must be unique or not
201
     * @return string
202
     */
203
    public static function cleanComment($comment, $glueSeparator = ',', $uniqueValues = true)
204 136
    {
205
        if (!is_scalar($comment) && !is_array($comment)) {
206 136
            return '';
207 4
        }
208
        return trim(str_replace('*/', '*[:slash:]', is_scalar($comment) ? $comment : implode($glueSeparator, $uniqueValues ? array_unique($comment) : $comment)));
209 132
    }
210
    /**
211
     * Clean a string to make it valid as PHP variable
212
     * See more about the used regular expression at {@link http://www.regular-expressions.info/unicode.html}:
213
     * - \p{L} for any valid letter
214
     * - \p{N} for any valid number
215
     * - /u for suporting unicode
216
     * @param string $string the string to clean
217
     * @param bool $keepMultipleUnderscores optional, allows to keep the multiple consecutive underscores
218
     * @return string
219
     */
220
    public static function cleanString($string, $keepMultipleUnderscores = true)
221 532
    {
222
        $cleanedString = preg_replace('/[^\p{L}\p{N}_]/u', '_', $string);
223 532
        if (!$keepMultipleUnderscores) {
224 532
            $cleanedString = preg_replace('/[_]+/', '_', $cleanedString);
225 96
        }
226 72
        return $cleanedString;
227 532
    }
228
    /**
229
     * @param string $namespacedClassName
230
     * @return string
231
     */
232
    public static function removeNamespace($namespacedClassName)
233 196
    {
234
        $elements = explode('\\', $namespacedClassName);
235 196
        return (string) array_pop($elements);
236 196
    }
237
    /**
238
     * @param string $directory
239
     * @param int $permissions
240
     * @return bool
241
     */
242
    public static function createDirectory($directory, $permissions = 0775)
243 220
    {
244
        if (!is_dir($directory)) {
245 220
            mkdir($directory, $permissions, true);
246 44
        }
247 33
        return true;
248 220
    }
249
}
250