Passed
Push — develop ( bcbf5d...e03cb7 )
by Mikaël
08:55
created

Utils::createDirectory()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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