Completed
Push — master ( d2fe44...54d794 )
by Mikaël
659:50 queued 657:21
created

Utils::resolveCompletePath()   F

Complexity

Conditions 25
Paths 2561

Size

Total Lines 41
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 25

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 32
cts 32
cp 1
rs 2.6361
c 0
b 0
f 0
cc 25
eloc 27
nc 2561
nop 2
crap 25

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 756
    public static function getPart($optionValue, $string)
16
    {
17 756
        $elementType = '';
18 756
        $string = str_replace('_', '', $string);
19 756
        $string = preg_replace('/([0-9])/', '', $string);
20 756
        if (!empty($string)) {
21
            switch ($optionValue) {
22 756
                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 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 18
                    break;
37 738
                case GeneratorOptions::VALUE_START:
38 732
                    $parts = preg_split('/[A-Z]/', ucfirst($string));
39 732
                    $partsCount = count($parts);
40 732
                    if (empty($parts[0]) && !empty($parts[1])) {
41 732
                        $elementType = substr($string, 0, strlen($parts[1]) + 1);
42 488
                    } 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 28
                        }
49 42
                        $elementType = substr($string, 0, $i);
50
                    }
51 732
                    break;
52 4
                default:
53 6
                    break;
54 4
            }
55 504
        }
56 756
        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 8
            $context = stream_context_create($options);
76 4
        }
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 12
                    ),
98 12
                ),
99 12
            );
100 12
        }
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 12
                    ),
108 12
                ),
109 12
            );
110 12
        }
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 198
    public static function getValueWithinItsType($value, $knownType = null)
120
    {
121 198
        if (is_int($value) || (!is_null($value) && in_array($knownType, array(
122 96
            'time',
123 64
            'positiveInteger',
124 64
            'unsignedLong',
125 64
            'unsignedInt',
126 64
            'short',
127 64
            'long',
128 64
            'int',
129 64
            'integer',
130 181
        ), true))) {
131 18
            return intval($value);
132 198
        } elseif (is_float($value) || (!is_null($value) && in_array($knownType, array(
133 96
            'float',
134 64
            'double',
135 64
            'decimal',
136 181
        ), true))) {
137 6
            return floatval($value);
138 198
        } elseif (is_bool($value) || (!is_null($value) && in_array($knownType, array(
139 96
            'bool',
140 64
            'boolean',
141 181
        ), true))) {
142 6
            return ($value === 'true' || $value === true || $value === 1 || $value === '1');
143
        }
144 198
        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 8
            }
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 8
                } else {
172 300
                    $finalPath .= '/' . $locationPart;
173
                }
174 200
            }
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 298
            } elseif (empty($scheme) && empty($host) && count($pathParts)) {
182
                /**
183
                 * Local file
184
                 */
185 294
                if (is_file($finalPath)) {
186 294
                    $resolvedPath = $finalPath;
187 196
                }
188 196
            }
189 200
        }
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 234
    public static function cleanComment($comment, $glueSeparator = ',', $uniqueValues = true)
200
    {
201 234
        if (!is_scalar($comment) && !is_array($comment)) {
202 6
            return '';
203
        }
204 228
        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 846
    public static function cleanString($string, $keepMultipleUnderscores = true)
217
    {
218 846
        $cleanedString = preg_replace('/[^\p{L}\p{N}_]/u', '_', $string);
219 846
        if (!$keepMultipleUnderscores) {
220 168
            $cleanedString = preg_replace('/[_]+/', '_', $cleanedString);
221 112
        }
222 846
        return $cleanedString;
223
    }
224
    /**
225
     * @param string $namespacedClassName
226
     * @return string
227
     */
228 324
    public static function removeNamespace($namespacedClassName)
229
    {
230 324
        $elements = explode('\\', $namespacedClassName);
231 324
        return (string) array_pop($elements);
232
    }
233
    /**
234
     * @param string $directory
235
     * @param int $permissions
236
     * @return bool
237
     */
238 360
    public static function createDirectory($directory, $permissions = 0775)
239
    {
240 360
        if (!is_dir($directory)) {
241 42
            mkdir($directory, $permissions, true);
242 28
        }
243 360
        return true;
244
    }
245
}
246