Completed
Push — master ( 941c19...fba9d9 )
by Lorenzo
01:57
created

FileHelper::getMimeTypeByFinfo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace Padosoft\Io;
4
5
/**
6
 * Helper Class FileHelper
7
 * @package Padosoft\Io
8
 */
9
class FileHelper
10
{
11
    /**
12
     * Simple pathinfo wrapper.
13
     * @param string $filePath
14
     * @param int $fileInfOoptions
15
     * @return string
16
     * @see http://php.net/manual/en/function.pathinfo.php
17
     */
18
    public static function getPathinfoPart(string $filePath, int $fileInfOoptions) : string
19
    {
20
        if ($filePath === null || $filePath == '' || is_dir($filePath) || DirHelper::endsWithSlash($filePath)) {
21
            return '';
22
        }
23
24
        $info = pathinfo($filePath, $fileInfOoptions);
25
26
        if ($info == '.' && $fileInfOoptions == PATHINFO_DIRNAME) {
27
            return '';
28
        }
29
        return ($info !== null && $info != '') ? $info : '';
30
    }
31
32
    /**
33
     * Return the file name of file (without path and without extension).
34
     * Return empty string if $filePath is null, empty or is a directory.
35
     * Ex.: /public/upload/pippo.txt return '/public/upload'
36
     * @param string $filePath
37
     * @return string
38
     */
39
    public static function getDirname(string $filePath) : string
40
    {
41
        return self::getPathinfoPart($filePath, PATHINFO_DIRNAME);
42
    }
43
44
    /**
45
     * Return the file name of file (without path and with extension).
46
     * Return empty string if $filePath is null, empty or is a directory.
47
     * Ex.: /public/upload/pippo.txt return 'pippo.txt'
48
     * @param string $filePath
49
     * @return string
50
     */
51
    public static function getFilename(string $filePath) : string
52
    {
53
        return self::getPathinfoPart($filePath, PATHINFO_BASENAME);
54
    }
55
56
    /**
57
     * Return the file name of file (without path and without extension).
58
     * Return empty string if $filePath is null, empty or is a directory.
59
     * Ex.: /public/upload/pippo.txt return 'pippo'
60
     * @param string $filePath
61
     * @return string
62
     */
63
    public static function getFilenameWithoutExtension(string $filePath) : string
64
    {
65
        return self::getPathinfoPart($filePath, PATHINFO_FILENAME);
66
    }
67
68
    /**
69
     * Return the file name of file (without path and without extension).
70
     * Return empty string if $filePath is null, empty or is a directory.
71
     * Ex.: /public/upload/pippo.txt return '.txt'
72
     * @param string $filePath
73
     * @return string
74
     */
75
    public static function getFilenameExtension(string $filePath) : string
76
    {
77
        return self::getPathinfoPart($filePath, PATHINFO_EXTENSION);
78
    }
79
80
    /**
81
     * unlink file if exists.
82
     * Return false if exists and unlink fails or if filePath is a dir.
83
     * @param string $filePath
84
     * @return bool
85
     */
86
    public static function unlinkSafe(string $filePath) : bool
87
    {
88
        if (!FileHelper::fileExistsSafe($filePath)) {
89
            return false;
90
        }
91
92
        if (DirHelper::isDirSafe($filePath)) {
93
            return false;
94
        }
95
96
        return unlink($filePath);
97
    }
98
99
    /**
100
     * Check if passed file exists or not.
101
     * If dir passed return false.
102
     * @param string $filePath
103
     * @return bool
104
     */
105
    public static function fileExistsSafe(string $filePath) : bool
106
    {
107
        if ($filePath === null || $filePath == '') {
108
            return false;
109
        }
110
111
        if (DirHelper::isDirSafe($filePath)) {
112
            return false;
113
        }
114
115
        return file_exists($filePath);
116
    }
117
118
    /**
119
     * Find files matching a pattern (recursive with matched files in subdirs).
120
     * Returns an array containing the matched files (full path and not directories),
121
     * an empty array if no file matched or on error.
122
     * @param string $fileNamePattern if is null it set to base_path()/* if exists otherwise __DIR__/* . It support glob() string pattern.
123
     * @param int $flags glob() Valid flags
124
     * @return array of files (full path)
125
     */
126
    public static function findFiles(string $fileNamePattern, int $flags = 0)
127
    {
128
        $fallback = [];
129
130
        if (($fileNamePattern === null || $fileNamePattern == '') && function_exists('base_path')) {
131
            $fileNamePattern = DirHelper::addFinalSlash(base_path()) . '*';
132
        } elseif ($fileNamePattern === null || $fileNamePattern == '') {
133
            $fileNamePattern = __DIR__ . '/*';
134
        }
135
136
        if (DirHelper::endsWithSlash($fileNamePattern)) {
137
            $fileNamePattern .= '*';
138
        }
139
140
        $files = glob($fileNamePattern, $flags);
141
142
        //remove array of empty string
143
        $files = array_filter($files, function ($k) {
144
            return ($k !== null && $k != '');
145
        });
146
147
        if (empty($files)) {
148
            return $fallback;
149
        }
150
151
        foreach (glob(dirname($fileNamePattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
152
153
            if (empty($dir)) {
154
                continue;
155
            }
156
157
            $files = array_merge($files, self::findFiles($dir . '/' . basename($fileNamePattern), $flags));
158
            $files = array_filter($files, function ($k) {
159
                return ($k !== null && $k != '');
160
            });
161
        }
162
163
        $files = array_filter($files, function ($k) {
164
            return (!is_dir($k));
165
        });
166
167
        return $files === false ? $fallback : $files;
168
    }
169
170
    /**
171
     * Equals to file_put_contents but safe, i.e.
172
     * accept empty string and return false without raise an error,
173
     * accept a directory and return false without raise an error,
174
     * and if $forceCreateDirIfNotExists is set to true and path doesn't exists, file_put_contents fails
175
     * so, this class, try to create the complete path before save file.
176
     * @param string $filename file name including folder.
177
     * example :: /path/to/file/filename.ext or filename.ext
178
     * @param string $data The data to write.
179
     * @param bool $forceCreateDirIfNotExists if true and path not exists, try to create it.
180
     * @param string $modeMask The mask applied to dir if need to create some dir.
181
     * @param int $flags same flags used for file_put_contents.
182
     * @see more info: http://php.net/manual/en/function.file-put-contents.php
183
     * @return bool TRUE file created succesfully, return FALSE if failed to create file.
184
     */
185
    public static function filePutContentsSafe(
186
        string $filename,
187
        string $data,
188
        bool $forceCreateDirIfNotExists = true,
189
        string $modeMask = '0755',
190
        int $flags = 0
191
    ) : bool
192
    {
193
        if ($filename === null || $filename == '') {
194
            return false;
195
        }
196
197
        //check if a directory passed ($filename ends with slash)
198
        if (DirHelper::endsWithSlash($filename)) {
199
            return false;
200
        }
201
202
        $dirName = dirname($filename);
203
204
        if (!$forceCreateDirIfNotExists && !DirHelper::isDirSafe($dirName)) {
205
            return false;
206
        }
207
208
        if (!DirHelper::checkDirExistOrCreate(DirHelper::addFinalSlash($dirName), $modeMask)) {
209
            return false;
210
        }
211
212
        return file_put_contents($filename, $data, $flags);
213
    }
214
215
    /**
216
     * Return mime type of a passed file in optimized mode.
217
     * @param string $fullPathFile
218
     * @return string
219
     */
220
    public static function getMimeType(string $fullPathFile) : string
221
    {
222
        $mime_types = array(
223
224
            'txt' => 'text/plain',
225
            'htm' => 'text/html',
226
            'html' => 'text/html',
227
            'php' => 'text/html',
228
            'css' => 'text/css',
229
            'js' => 'application/javascript',
230
            'json' => 'application/json',
231
            'xml' => 'application/xml',
232
            'swf' => 'application/x-shockwave-flash',
233
            'flv' => 'video/x-flv',
234
235
            // images
236
            'png' => 'image/png',
237
            'jpe' => 'image/jpeg',
238
            'jpeg' => 'image/jpeg',
239
            'jpg' => 'image/jpeg',
240
            'gif' => 'image/gif',
241
            'bmp' => 'image/bmp',
242
            'ico' => 'image/vnd.microsoft.icon',
243
            'tiff' => 'image/tiff',
244
            'tif' => 'image/tiff',
245
            'svg' => 'image/svg+xml',
246
            'svgz' => 'image/svg+xml',
247
248
            // archives
249
            'zip' => 'application/zip',
250
            'rar' => 'application/x-rar-compressed',
251
            'exe' => 'application/x-msdownload',
252
            'msi' => 'application/x-msdownload',
253
            'cab' => 'application/vnd.ms-cab-compressed',
254
255
            // audio/video
256
            'mp3' => 'audio/mpeg',
257
            'qt' => 'video/quicktime',
258
            'mov' => 'video/quicktime',
259
260
            // adobe
261
            'pdf' => 'application/pdf',
262
            'psd' => 'image/vnd.adobe.photoshop',
263
            'ai' => 'application/postscript',
264
            'eps' => 'application/postscript',
265
            'ps' => 'application/postscript',
266
267
            // ms office
268
            'doc' => 'application/msword',
269
            'rtf' => 'application/rtf',
270
            'xls' => 'application/vnd.ms-excel',
271
            'ppt' => 'application/vnd.ms-powerpoint',
272
273
            // open office
274
            'odt' => 'application/vnd.oasis.opendocument.text',
275
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
276
        );
277
        $ext = strtolower(self::getFilenameExtension($fullPathFile));
278
        if (array_key_exists($ext, $mime_types)) {
279
            return $mime_types[$ext];
280
        }
281
        $mimetype = self::getMimeTypeByMime_content_type($fullPathFile);
282
        if (isNotNullOrEmpty($mimetype)) {
283
            return $mimetype;
284
        }
285
        $mimetype = self::getMimeTypeByFinfo($fullPathFile);
286
        if (isNotNullOrEmpty($mimetype)) {
287
            return $mimetype;
288
        }
289
        return 'application/octet-stream';
290
    }
291
292
    /**
293
     * Return mime type of a passed file using finfo
294
     * @param string $fullPathFile
295
     * @return string return empty string if it fails.
296
     */
297
    public static function getMimeTypeByFinfo(string $fullPathFile) : string
298
    {
299
        if (!function_exists('finfo_open')) {
300
            return '';
301
        }
302
        $finfo = finfo_open(FILEINFO_MIME);
303
        $mimetype = finfo_file($finfo, $fullPathFile);
304
        finfo_close($finfo);
305
        if ($mimetype === false) {
306
            return '';
307
        }
308
        return $mimetype;
309
    }
310
311
    /**
312
     * Return mime type of a passed file using mime_content_type()
313
     * @param string $fullPathFile
314
     * @return string return empty string if it fails.
315
     */
316
    public static function getMimeTypeByMime_content_type(string $fullPathFile) : string
317
    {
318
        if (!function_exists('mime_content_type')) {
319
            return '';
320
        }
321
        return mime_content_type($fullPathFile);
322
    }
323
}
324