Completed
Push — master ( 759e1c...4c6993 )
by Lorenzo
04:47
created

FileHelper::getFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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 witout 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 witout 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 witout 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 witout 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