Completed
Push — feature/issue-91 ( f0947a )
by Mikaël
02:05
created

Utils::getContentFromUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

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

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