Completed
Branch feature/issue-89 (7b89b3)
by Mikaël
03:07
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 500
    public static function getPart($optionValue, $string)
16
    {
17 500
        $elementType = '';
18 500
        $string = str_replace('_', '', $string);
19 500
        $string = preg_replace('/([0-9])/', '', $string);
20 500
        if (!empty($string)) {
21
            switch ($optionValue) {
22 500
                case GeneratorOptions::VALUE_END:
23 12
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
24 12
                    $partsCount = count($parts);
25 12
                    if (!empty($parts[$partsCount - 1])) {
26 12
                        $elementType = substr($string, strrpos($string, implode('', array_slice($parts, -1))) - 1);
27 12
                    } 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 12
                    break;
37 488
                case GeneratorOptions::VALUE_START:
38 484
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
39 484
                    $partsCount = count($parts);
40 484
                    if (empty($parts[0]) && !empty($parts[1])) {
41 484
                        $elementType = substr($string, 0, strlen($parts[1]) + 1);
42 484
                    } else {
43 28
                        for ($i = 0; $i < $partsCount; $i++) {
44 28
                            $part = trim($parts[$i]);
45 28
                            if (!empty($part)) {
46 28
                                break;
47
                            }
48 28
                        }
49 28
                        $elementType = substr($string, 0, $i);
50
                    }
51 484
                    break;
52 4
                default:
53 4
                    break;
54 4
            }
55 500
        }
56 500
        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 8
    public static function getContentFromUrl($url, $basicAuthLogin = null, $basicAuthPassword = null, $proxyHost = null, $proxyPort = null, $proxyLogin = null, $proxyPassword = null, array $contextOptions = array())
71
    {
72 8
        $context = null;
73 8
        $options = self::getStreamContextOptions($basicAuthLogin, $basicAuthPassword, $proxyHost, $proxyPort, $proxyLogin, $proxyPassword, $contextOptions);
74 8
        if (!empty($options)) {
75 4
            $context = stream_context_create($options);
76 4
        }
77 8
        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 24
    public static function getStreamContextOptions($basicAuthLogin = null, $basicAuthPassword = null, $proxyHost = null, $proxyPort = null, $proxyLogin = null, $proxyPassword = null, array $contextOptions = array())
90
    {
91 24
        $proxyOptions = $basicAuthOptions = array();
92 24
        if (!empty($basicAuthLogin) && !empty($basicAuthPassword)) {
93
            $basicAuthOptions = array(
94
                'http' => array(
95
                    'header' => array(
96 12
                        sprintf('Authorization: Basic %s', base64_encode(sprintf('%s:%s', $basicAuthLogin, $basicAuthPassword))),
97 12
                    ),
98 12
                ),
99 12
            );
100 12
        }
101 24
        if (!empty($proxyHost)) {
102
            $proxyOptions = array(
103
                'http' => array(
104 12
                    'proxy' => sprintf('tcp://%s%s', $proxyHost, empty($proxyPort) ? '' : sprintf(':%s', $proxyPort)),
105
                    'header' => array(
106 12
                        sprintf('Proxy-Authorization: Basic %s', base64_encode(sprintf('%s:%s', $proxyLogin, $proxyPassword))),
107 12
                    ),
108 12
                ),
109 12
            );
110 12
        }
111 24
        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 128
    public static function getValueWithinItsType($value, $knownType = null)
120
    {
121 128
        if (is_int($value) || (!is_null($value) && in_array($knownType, array(
122 60
            'time',
123 60
            'positiveInteger',
124 60
            'unsignedLong',
125 60
            'unsignedInt',
126 60
            'short',
127 60
            'long',
128 60
            'int',
129 60
            'integer',
130 128
        ), true))) {
131 8
            return intval($value);
132 128
        } elseif (is_float($value) || (!is_null($value) && in_array($knownType, array(
133 60
            'float',
134 60
            'double',
135 60
            'decimal',
136 128
        ), true))) {
137 4
            return floatval($value);
138 128
        } elseif (is_bool($value) || (!is_null($value) && in_array($knownType, array(
139 60
            'bool',
140 60
            'boolean',
141 128
        ), true))) {
142 4
            return ($value === 'true' || $value === true || $value === 1 || $value === '1');
143
        }
144 128
        return $value;
145
    }
146
    /**
147
     * @param string $origin
148
     * @param string $destination
149
     * @return string
150
     */
151 200
    public static function resolveCompletePath($origin, $destination)
152
    {
153 200
        $resolvedPath = $destination;
154 200
        if (!empty($destination) && strpos($destination, 'http://') === false && strpos($destination, 'https://') === false && !empty($origin)) {
155 200
            if (substr($destination, 0, 2) === './') {
156 8
                $destination = substr($destination, 2);
157 8
            }
158 200
            $destinationParts = explode('/', $destination);
159 200
            $fileParts = pathinfo($origin);
160 200
            $fileBasename = (is_array($fileParts) && array_key_exists('basename', $fileParts)) ? $fileParts['basename'] : '';
161 200
            $parts = parse_url(str_replace('/' . $fileBasename, '', $origin));
162 200
            $scheme = (is_array($parts) && array_key_exists('scheme', $parts)) ? $parts['scheme'] : '';
163 200
            $host = (is_array($parts) && array_key_exists('host', $parts)) ? $parts['host'] : '';
164 200
            $path = (is_array($parts) && array_key_exists('path', $parts)) ? $parts['path'] : '';
165 200
            $path = str_replace('/' . $fileBasename, '', $path);
166 200
            $pathParts = explode('/', $path);
167 200
            $finalPath = implode('/', $pathParts);
168 200
            foreach ($destinationParts as $locationPart) {
169 200
                if ($locationPart == '..') {
170 8
                    $finalPath = substr($finalPath, 0, strrpos($finalPath, '/', 0));
171 8
                } else {
172 200
                    $finalPath .= '/' . $locationPart;
173
                }
174 200
            }
175 200
            $port = (is_array($parts) && array_key_exists('port', $parts)) ? $parts['port'] : '';
176
            /**
177
             * Remote file
178
             */
179 200
            if (!empty($scheme) && !empty($host)) {
180 4
                $resolvedPath = str_replace('urn', 'http', $scheme) . '://' . $host . (!empty($port) ? ':' . $port : '') . str_replace('//', '/', $finalPath);
181 200
            } elseif (empty($scheme) && empty($host) && count($pathParts)) {
182
                /**
183
                 * Local file
184
                 */
185 196
                if (is_file($finalPath)) {
186 196
                    $resolvedPath = $finalPath;
187 196
                }
188 196
            }
189 200
        }
190 200
        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 152
    public static function cleanComment($comment, $glueSeparator = ',', $uniqueValues = true)
200
    {
201 152
        if (!is_scalar($comment) && !is_array($comment)) {
202 4
            return '';
203
        }
204 148
        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 560
    public static function cleanString($string, $keepMultipleUnderscores = true)
217
    {
218 560
        $cleanedString = preg_replace('/[^\p{L}\p{N}_]/u', '_', $string);
219 560
        if (!$keepMultipleUnderscores) {
220 108
            $cleanedString = preg_replace('/[_]+/', '_', $cleanedString);
221 108
        }
222 560
        return $cleanedString;
223
    }
224
    /**
225
     * @param string $namespacedClassName
226
     * @return string
227
     */
228 212
    public static function removeNamespace($namespacedClassName)
229
    {
230 212
        $elements = explode('\\', $namespacedClassName);
231 212
        return (string) array_pop($elements);
232
    }
233
    /**
234
     * @param string $directory
235
     * @param int $permissions
236
     * @return bool
237
     */
238 236
    public static function createDirectory($directory, $permissions = 0775)
239
    {
240 236
        if (!is_dir($directory)) {
241 44
            mkdir($directory, $permissions, true);
242 44
        }
243 236
        return true;
244
    }
245
}
246