Passed
Push — analysis-Rv0oP9 ( 29410c )
by Arnaud
05:23
created

Util::isUrlFileExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil;
12
13
use Symfony\Component\Filesystem\Filesystem;
14
15
class Util
16
{
17
    /** @var Filesystem */
18
    protected static $fs;
19
20
    /**
21
     * Return a Symfony\Component\Filesystem instance.
22
     *
23
     * @return Filesystem
24
     */
25
    public static function getFS(): Filesystem
26
    {
27
        if (!self::$fs instanceof Filesystem) {
28
            self::$fs = new Filesystem();
29
        }
30
31
        return self::$fs;
32
    }
33
34
    /**
35
     * Checks if a date is valid.
36
     *
37
     * @param string $date
38
     * @param string $format
39
     *
40
     * @return bool
41
     */
42
    public static function isDateValid(string $date, string $format = 'Y-m-d'): bool
43
    {
44
        $d = \DateTime::createFromFormat($format, $date);
45
46
        return $d && $d->format($format) === $date;
47
    }
48
49
    /**
50
     * Date to DateTime.
51
     *
52
     * @param mixed $date
53
     *
54
     * @return \DateTime
55
     */
56
    public static function dateToDatetime($date): \DateTime
57
    {
58
        // DateTime
59
        if ($date instanceof \DateTime) {
60
            return $date;
61
        }
62
        // timestamp or 'AAAA-MM-DD'
63
        if (is_numeric($date)) {
64
            return (new \DateTime())->setTimestamp($date);
65
        }
66
        // string (ie: '01/01/2019', 'today')
67
        if (is_string($date)) {
68
            return new \DateTime($date);
69
        }
70
    }
71
72
    /**
73
     * Formats a class name.
74
     *
75
     * ie: "Cecil\Step\PostProcessHtml" become "PostProcessHtml"
76
     *
77
     * @param \object $class
78
     * @param array   $options
79
     *
80
     * @return string
81
     */
82
    public static function formatClassName($class, array $options = []): string
83
    {
84
        $lowercase = false;
85
        extract($options);
86
87
        $className = substr(strrchr(get_class($class), '\\'), 1);
88
        if ($lowercase) {
1 ignored issue
show
introduced by
The condition $lowercase is always false.
Loading history...
89
            $className = strtolower($className);
90
        }
91
92
        return $className;
93
    }
94
95
    /**
96
     * Test if a string is an external URL or not.
97
     *
98
     * @param string $url
99
     *
100
     * @return bool
101
     */
102
    public static function isExternalUrl(string $url): bool
103
    {
104
        return (bool) preg_match('~^(?:f|ht)tps?://~i', $url);
105
    }
106
107
    /**
108
     * Test if a remote file exists or not.
109
     *
110
     * @param string $remoteFile
111
     *
112
     * @return bool
113
     */
114
    public static function isUrlFileExists(string $remoteFile): bool
115
    {
116
        $handle = @fopen($remoteFile, 'r');
117
        if (is_resource($handle)) {
118
            return true;
119
        }
120
121
        return false;
122
    }
123
124
    /**
125
     * Converts an array of strings into a path.
126
     *
127
     * @param string $path
128
     *
129
     * @return string
130
     */
131
    public static function joinPath(string ...$path): string
132
    {
133
        array_walk($path, function (&$value, $key) {
134
            $value = str_replace('\\', '/', $value);
135
            $value = rtrim($value, '/');
136
            $value = $key == 0 ? $value : ltrim($value, '/');
137
        });
138
139
        return implode('/', $path);
140
    }
141
142
    /**
143
     * Converts an array of strings into a system path.
144
     *
145
     * @param string $path
146
     *
147
     * @return string
148
     */
149
    public static function joinFile(string ...$path): string
150
    {
151
        array_walk($path, function (&$value, $key) use (&$path) {
152
            $value = str_replace(['\\', '/'], [DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $value);
153
            $value = rtrim($value, DIRECTORY_SEPARATOR);
154
            $value = $key == 0 ? $value : ltrim($value, DIRECTORY_SEPARATOR);
155
            // unset entry with empty value
156
            if (empty($value)) {
157
                unset($path[$key]);
158
            }
159
        });
160
161
        return implode(DIRECTORY_SEPARATOR, $path);
162
    }
163
164
    /**
165
     * Converts an array to a string.
166
     *
167
     * ie: [0 => 'A', 1 => B] become "0:A, 1:B"
168
     *
169
     * @param array  $array
170
     * @param string $separator Separtor between the key and the value in the result string
171
     *
172
     * @return string
173
     */
174
    public static function arrayToString(array $array, string $separator = ':'): string
175
    {
176
        $string = '';
177
178
        foreach ($array as $key => $value) {
179
            $string .= sprintf('%s%s%s, ', $key, $separator, $value);
180
        }
181
182
        return substr($string, 0, -2);
183
    }
184
185
    /**
186
     * Combines an array into a string.
187
     *
188
     * @param array  $array
189
     * @param string $keyToKey   The key that become the key of the new array
190
     * @param string $keyToValue The key that become the value of the new array
191
     * @param string $separator  The separtor between the key and the value in the result string
192
     *
193
     * @return string
194
     */
195
    public static function combineArrayToString(
196
        array $array,
197
        string $keyToKey,
198
        string $keyToValue,
199
        string $separator = ':'
200
    ): string {
201
        $string = '';
202
203
        foreach ($array as $subArray) {
204
            $string .= sprintf('%s%s%s, ', $subArray[$keyToKey], $separator, $subArray[$keyToValue]);
205
        }
206
207
        return substr($string, 0, -2);
208
    }
209
210
    /**
211
     * Simplified version file_get_contents() with error handler.
212
     *
213
     * @param string $filename
214
     *
215
     * @return string|false
216
     */
217
    public static function fileGetContents($filename)
218
    {
219
        set_error_handler(
220
            function ($severity, $message, $file, $line) {
221
                throw new \ErrorException($message, 0, $severity, $file, $line, null);
222
            }
223
        );
224
225
        try {
226
            $return = file_get_contents($filename);
227
        } catch (\Exception $e) {
228
            $return = false;
229
        }
230
        restore_error_handler();
231
232
        return $return;
233
    }
234
235
    /**
236
     * Returns MIME content type and subtype of a file.
237
     *
238
     * ie: ['text', 'text/plain']
239
     *
240
     * @param string $filename
241
     *
242
     * @return string[]
243
     */
244
    public static function getMimeType(string $filename): array
245
    {
246
        if (false === $subtype = mime_content_type($filename)) {
247
            throw new \Exception(sprintf('Can\'t get MIME content type of "%s"', $filename));
248
        }
249
        $type = explode('/', $subtype)[0];
250
251
        return [
252
            $type,
253
            $subtype,
254
        ];
255
    }
256
}
257