Test Failed
Pull Request — master (#2148)
by Arnaud
08:44 queued 03:50
created

File::isRemote()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Util;
15
16
use Cecil\Exception\RuntimeException;
17
use Symfony\Component\Filesystem\Filesystem;
18
use Symfony\Component\Mime\MimeTypes;
19
20
class File
21
{
22
    /** @var Filesystem */
23
    protected static $fs;
24
25
    /**
26
     * Returns a Symfony\Component\Filesystem instance.
27 1
     */
28
    public static function getFS(): Filesystem
29 1
    {
30 1
        if (!self::$fs instanceof Filesystem) {
31
            self::$fs = new Filesystem();
32
        }
33 1
34
        return self::$fs;
35
    }
36
37
    /**
38
     * file_get_contents() function with error handler.
39
     *
40
     * @return string|false
41 1
     */
42
    public static function fileGetContents(string $filename, bool $userAgent = false)
43 1
    {
44
        if (empty($filename)) {
45
            return false;
46
        }
47 1
48 1
        set_error_handler(
49 1
            function ($severity, $message, $file, $line) {
50 1
                throw new \ErrorException($message, 0, $severity, $file, $line, null);
51 1
            }
52
        );
53
54 1
        try {
55 1
            if ($userAgent) {
56 1
                $options = [
57 1
                    'http' => [
58 1
                        'method'          => 'GET',
59 1
                        'header'          => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36',
60 1
                        'follow_location' => true,
61 1
                    ],
62
                ];
63 1
64
                return file_get_contents($filename, false, stream_context_create($options));
65
            }
66 1
67 1
            return file_get_contents($filename);
68 1
        } catch (\ErrorException) {
69
            return false;
70 1
        } finally {
71
            restore_error_handler();
72
        }
73
    }
74
75
    /**
76
     * Returns the media type and subtype of a file.
77
     *
78
     * ie: ['text', 'text/plain']
79 1
     */
80
    public static function getMediaType(string $filename): array
81 1
    {
82
        try {
83
            if (false !== $subtype = mime_content_type($filename)) {
84 1
                return [explode('/', $subtype)[0], $subtype];
85
            }
86 1
            $mimeTypes = new MimeTypes();
87 1
            $subtype = $mimeTypes->guessMimeType($filename);
88 1
            if ($subtype === null) {
89 1
                throw new RuntimeException('Can\'t guess the media type.');
90
            }
91
92
            return [explode('/', $subtype)[0], $subtype];
93
        } catch (\Exception $e) {
94
            throw new RuntimeException(\sprintf('Can\'t get media type of "%s" (%s).', $filename, $e->getMessage()));
95 1
        }
96
    }
97 1
98
    /**
99
     * Returns the extension of a file.
100
     */
101 1
    public static function getExtension(string $filename): string
102 1
    {
103
        try {
104 1
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
105 1
            if (!empty($ext)) {
106
                return $ext;
107
            }
108 1
            // guess the extension
109
            $mimeTypes = new MimeTypes();
110
            $mimeType = $mimeTypes->guessMimeType($filename);
111 1
            if ($mimeType === null) {
112 1
                throw new RuntimeException('Can\'t guess the media type.');
113
            }
114
            $exts = $mimeTypes->getExtensions($mimeType);
115
116 1
            return $exts[0];
117
        } catch (\Exception $e) {
118
            throw new RuntimeException(\sprintf('Can\'t get extension of "%s" (%s).', $filename, $e->getMessage()));
119
        }
120 1
    }
121
122
    /**
123
     * exif_read_data() function with error handler.
124
     */
125
    public static function readExif(string $filename): array
126
    {
127 1
        if (empty($filename)) {
128
            return [];
129
        }
130 1
131 1
        set_error_handler(
132
            function ($severity, $message, $file, $line) {
133
                throw new \ErrorException($message, 0, $severity, $file, $line, null);
134
            }
135 1
        );
136
137
        try {
138
            if (!\function_exists('exif_read_data')) {
139 1
                throw new \ErrorException('`exif` extension is not available.');
140
            }
141
            $exif = exif_read_data($filename, null, true);
142
            if ($exif === false) {
143
                return [];
144
            }
145
146
            return $exif;
147
        } catch (\ErrorException) {
148
            return [];
149
        } finally {
150
            restore_error_handler();
151
        }
152
    }
153
154
    /**
155
     * Returns the real path of a relative file path.
156
     */
157
    public static function getRealPath(string $path): string
158
    {
159
        // if file exists
160
        $filePath = realpath(\Cecil\Util::joinFile(__DIR__, '/../', $path));
161
        if ($filePath !== false) {
162
            return $filePath;
163
        }
164
        // if Phar
165
        if (Platform::isPhar()) {
166
            return \Cecil\Util::joinPath(Platform::getPharPath(), str_replace('../', '/', $path));
167
        }
168
169
        throw new RuntimeException(\sprintf('Can\'t get the real path of file "%s".', $path));
170
    }
171
172
    /**
173
     * Tests if a file path is remote.
174
     */
175
    public static function isRemote(string $path): bool
176
    {
177
        return (bool) preg_match('~^(?:f|ht)tps?://~i', $path);
178
    }
179
180
    /**
181
     * Tests if a remote file exists.
182
     */
183
    public static function isRemoteExists(string $path): bool
184
    {
185
        if (self::isRemote($path)) {
186
            $handle = @fopen($path, 'r');
187
            if (\is_resource($handle)) {
188
                return true;
189
            }
190
        }
191
192
        return false;
193
    }
194
}
195