• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 12673986434

08 Jan 2025 03:42PM UTC coverage: 84.455% (+0.001%) from 84.454%
12673986434

Pull #9385

github

web-flow
Merge 06e47f0ee into e475fd8fa
Pull Request #9385: refactor: Fix phpstan expr.resultUnused

20699 of 24509 relevant lines covered (84.45%)

190.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.27
/system/Helpers/filesystem_helper.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
use CodeIgniter\Exceptions\InvalidArgumentException;
15

16
// CodeIgniter File System Helpers
17

18
if (! function_exists('directory_map')) {
5✔
19
    /**
20
     * Create a Directory Map
21
     *
22
     * Reads the specified directory and builds an array
23
     * representation of it. Sub-folders contained with the
24
     * directory will be mapped as well.
25
     *
26
     * @param string $sourceDir      Path to source
27
     * @param int    $directoryDepth Depth of directories to traverse
28
     *                               (0 = fully recursive, 1 = current dir, etc)
29
     * @param bool   $hidden         Whether to show hidden files
30
     */
31
    function directory_map(string $sourceDir, int $directoryDepth = 0, bool $hidden = false): array
32
    {
33
        try {
34
            $fp = opendir($sourceDir);
37✔
35

36
            $fileData  = [];
36✔
37
            $newDepth  = $directoryDepth - 1;
36✔
38
            $sourceDir = rtrim($sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
36✔
39

40
            while (false !== ($file = readdir($fp))) {
36✔
41
                // Remove '.', '..', and hidden files [optional]
42
                if ($file === '.' || $file === '..' || ($hidden === false && $file[0] === '.')) {
36✔
43
                    continue;
36✔
44
                }
45

46
                if (is_dir($sourceDir . $file)) {
36✔
47
                    $file .= DIRECTORY_SEPARATOR;
30✔
48
                }
49

50
                if (($directoryDepth < 1 || $newDepth > 0) && is_dir($sourceDir . $file)) {
36✔
51
                    $fileData[$file] = directory_map($sourceDir . $file, $newDepth, $hidden);
29✔
52
                } else {
53
                    $fileData[] = $file;
36✔
54
                }
55
            }
56

57
            closedir($fp);
36✔
58

59
            return $fileData;
36✔
60
        } catch (Throwable) {
1✔
61
            return [];
1✔
62
        }
63
    }
64
}
65

66
if (! function_exists('directory_mirror')) {
5✔
67
    /**
68
     * Recursively copies the files and directories of the origin directory
69
     * into the target directory, i.e. "mirror" its contents.
70
     *
71
     * @param bool $overwrite Whether individual files overwrite on collision
72
     *
73
     * @throws InvalidArgumentException
74
     */
75
    function directory_mirror(string $originDir, string $targetDir, bool $overwrite = true): void
76
    {
77
        if (! is_dir($originDir = rtrim($originDir, '\\/'))) {
4✔
78
            throw new InvalidArgumentException(sprintf('The origin directory "%s" was not found.', $originDir));
×
79
        }
80

81
        if (! is_dir($targetDir = rtrim($targetDir, '\\/'))) {
4✔
82
            @mkdir($targetDir, 0755, true);
×
83
        }
84

85
        $dirLen = strlen($originDir);
4✔
86

87
        /**
88
         * @var SplFileInfo $file
89
         */
90
        foreach (new RecursiveIteratorIterator(
4✔
91
            new RecursiveDirectoryIterator($originDir, FilesystemIterator::SKIP_DOTS),
4✔
92
            RecursiveIteratorIterator::SELF_FIRST
4✔
93
        ) as $file) {
4✔
94
            $origin = $file->getPathname();
4✔
95
            $target = $targetDir . substr($origin, $dirLen);
4✔
96

97
            if ($file->isDir()) {
4✔
98
                if (! is_dir($target)) {
2✔
99
                    mkdir($target, 0755);
1✔
100
                }
101
            } elseif (! is_file($target) || ($overwrite && is_file($target))) {
3✔
102
                copy($origin, $target);
3✔
103
            }
104
        }
105
    }
106
}
107

108
if (! function_exists('write_file')) {
5✔
109
    /**
110
     * Write File
111
     *
112
     * Writes data to the file specified in the path.
113
     * Creates a new file if non-existent.
114
     *
115
     * @param string $path File path
116
     * @param string $data Data to write
117
     * @param string $mode fopen() mode (default: 'wb')
118
     */
119
    function write_file(string $path, string $data, string $mode = 'wb'): bool
120
    {
121
        try {
122
            $fp = fopen($path, $mode);
58✔
123

124
            flock($fp, LOCK_EX);
56✔
125

126
            for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result) {
56✔
127
                if (($result = fwrite($fp, substr($data, $written))) === false) {
56✔
128
                    break;
×
129
                }
130
            }
131

132
            flock($fp, LOCK_UN);
56✔
133
            fclose($fp);
56✔
134

135
            return is_int($result);
56✔
136
        } catch (Throwable) {
2✔
137
            return false;
2✔
138
        }
139
    }
140
}
141

142
if (! function_exists('delete_files')) {
5✔
143
    /**
144
     * Delete Files
145
     *
146
     * Deletes all files contained in the supplied directory path.
147
     * Files must be writable or owned by the system in order to be deleted.
148
     * If the second parameter is set to true, any directories contained
149
     * within the supplied base directory will be nuked as well.
150
     *
151
     * @param string $path   File path
152
     * @param bool   $delDir Whether to delete any directories found in the path
153
     * @param bool   $htdocs Whether to skip deleting .htaccess and index page files
154
     * @param bool   $hidden Whether to include hidden files (files beginning with a period)
155
     */
156
    function delete_files(string $path, bool $delDir = false, bool $htdocs = false, bool $hidden = false): bool
157
    {
158
        $path = realpath($path) ?: $path;
54✔
159
        $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
54✔
160

161
        try {
162
            foreach (new RecursiveIteratorIterator(
54✔
163
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
54✔
164
                RecursiveIteratorIterator::CHILD_FIRST
54✔
165
            ) as $object) {
54✔
166
                $filename = $object->getFilename();
51✔
167
                if (! $hidden && $filename[0] === '.') {
51✔
168
                    continue;
3✔
169
                }
170

171
                if (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) {
51✔
172
                    $isDir = $object->isDir();
40✔
173
                    if ($isDir && $delDir) {
40✔
174
                        rmdir($object->getPathname());
3✔
175

176
                        continue;
3✔
177
                    }
178
                    if (! $isDir) {
40✔
179
                        unlink($object->getPathname());
40✔
180
                    }
181
                }
182
            }
183

184
            return true;
53✔
185
        } catch (Throwable) {
1✔
186
            return false;
1✔
187
        }
188
    }
189
}
190

191
if (! function_exists('get_filenames')) {
5✔
192
    /**
193
     * Get Filenames
194
     *
195
     * Reads the specified directory and builds an array containing the filenames.
196
     * Any sub-folders contained within the specified path are read as well.
197
     *
198
     * @param string    $sourceDir   Path to source
199
     * @param bool|null $includePath Whether to include the path as part of the filename; false for no path, null for a relative path, true for full path
200
     * @param bool      $hidden      Whether to include hidden files (files beginning with a period)
201
     * @param bool      $includeDir  Whether to include directories
202
     */
203
    function get_filenames(
204
        string $sourceDir,
205
        ?bool $includePath = false,
206
        bool $hidden = false,
207
        bool $includeDir = true
208
    ): array {
209
        $files = [];
723✔
210

211
        $sourceDir = realpath($sourceDir) ?: $sourceDir;
723✔
212
        $sourceDir = rtrim($sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
723✔
213

214
        try {
215
            foreach (new RecursiveIteratorIterator(
723✔
216
                new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS),
723✔
217
                RecursiveIteratorIterator::SELF_FIRST
723✔
218
            ) as $name => $object) {
723✔
219
                $basename = pathinfo($name, PATHINFO_BASENAME);
722✔
220
                if (! $hidden && $basename[0] === '.') {
722✔
221
                    continue;
645✔
222
                }
223

224
                if ($includeDir || ! $object->isDir()) {
721✔
225
                    if ($includePath === false) {
721✔
226
                        $files[] = $basename;
3✔
227
                    } elseif ($includePath === null) {
718✔
228
                        $files[] = str_replace($sourceDir, '', $name);
1✔
229
                    } else {
230
                        $files[] = $name;
717✔
231
                    }
232
                }
233
            }
234
        } catch (Throwable) {
1✔
235
            return [];
1✔
236
        }
237

238
        sort($files);
722✔
239

240
        return $files;
722✔
241
    }
242
}
243

244
if (! function_exists('get_dir_file_info')) {
5✔
245
    /**
246
     * Get Directory File Information
247
     *
248
     * Reads the specified directory and builds an array containing the filenames,
249
     * filesize, dates, and permissions
250
     *
251
     * Any sub-folders contained within the specified path are read as well.
252
     *
253
     * @param string $sourceDir    Path to source
254
     * @param bool   $topLevelOnly Look only at the top level directory specified?
255
     * @param bool   $recursion    Internal variable to determine recursion status - do not use in calls
256
     */
257
    function get_dir_file_info(string $sourceDir, bool $topLevelOnly = true, bool $recursion = false): array
258
    {
259
        static $fileData = [];
3✔
260
        $relativePath    = $sourceDir;
3✔
261

262
        try {
263
            $fp = opendir($sourceDir);
3✔
264

265
            // reset the array and make sure $sourceDir has a trailing slash on the initial call
266
            if ($recursion === false) {
2✔
267
                $fileData  = [];
2✔
268
                $sourceDir = rtrim(realpath($sourceDir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
2✔
269
            }
270

271
            // Used to be foreach (scandir($sourceDir, 1) as $file), but scandir() is simply not as fast
272
            while (false !== ($file = readdir($fp))) {
2✔
273
                if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
2✔
274
                    get_dir_file_info($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
1✔
275
                } elseif ($file[0] !== '.') {
2✔
276
                    $fileData[$file]                  = get_file_info($sourceDir . $file);
2✔
277
                    $fileData[$file]['relative_path'] = $relativePath;
2✔
278
                }
279
            }
280

281
            closedir($fp);
2✔
282

283
            return $fileData;
2✔
284
        } catch (Throwable) {
1✔
285
            return [];
1✔
286
        }
287
    }
288
}
289

290
if (! function_exists('get_file_info')) {
5✔
291
    /**
292
     * Get File Info
293
     *
294
     * Given a file and path, returns the name, path, size, date modified
295
     * Second parameter allows you to explicitly declare what information you want returned
296
     * Options are: name, server_path, size, date, readable, writable, executable, fileperms
297
     * Returns false if the file cannot be found.
298
     *
299
     * @param string       $file           Path to file
300
     * @param array|string $returnedValues Array or comma separated string of information returned
301
     *
302
     * @return array|null
303
     */
304
    function get_file_info(string $file, $returnedValues = ['name', 'server_path', 'size', 'date'])
305
    {
306
        if (! is_file($file)) {
6✔
307
            return null;
1✔
308
        }
309

310
        $fileInfo = [];
5✔
311

312
        if (is_string($returnedValues)) {
5✔
313
            $returnedValues = explode(',', $returnedValues);
2✔
314
        }
315

316
        foreach ($returnedValues as $key) {
5✔
317
            switch ($key) {
318
                case 'name':
5✔
319
                    $fileInfo['name'] = basename($file);
3✔
320
                    break;
3✔
321

322
                case 'server_path':
5✔
323
                    $fileInfo['server_path'] = $file;
3✔
324
                    break;
3✔
325

326
                case 'size':
5✔
327
                    $fileInfo['size'] = filesize($file);
3✔
328
                    break;
3✔
329

330
                case 'date':
5✔
331
                    $fileInfo['date'] = filemtime($file);
3✔
332
                    break;
3✔
333

334
                case 'readable':
2✔
335
                    $fileInfo['readable'] = is_readable($file);
1✔
336
                    break;
1✔
337

338
                case 'writable':
2✔
339
                    $fileInfo['writable'] = is_really_writable($file);
1✔
340
                    break;
1✔
341

342
                case 'executable':
2✔
343
                    $fileInfo['executable'] = is_executable($file);
1✔
344
                    break;
1✔
345

346
                case 'fileperms':
1✔
347
                    $fileInfo['fileperms'] = fileperms($file);
1✔
348
                    break;
1✔
349
            }
350
        }
351

352
        return $fileInfo;
5✔
353
    }
354
}
355

356
if (! function_exists('symbolic_permissions')) {
5✔
357
    /**
358
     * Symbolic Permissions
359
     *
360
     * Takes a numeric value representing a file's permissions and returns
361
     * standard symbolic notation representing that value
362
     *
363
     * @param int $perms Permissions
364
     */
365
    function symbolic_permissions(int $perms): string
366
    {
367
        if (($perms & 0xC000) === 0xC000) {
1✔
368
            $symbolic = 's'; // Socket
1✔
369
        } elseif (($perms & 0xA000) === 0xA000) {
1✔
370
            $symbolic = 'l'; // Symbolic Link
1✔
371
        } elseif (($perms & 0x8000) === 0x8000) {
1✔
372
            $symbolic = '-'; // Regular
1✔
373
        } elseif (($perms & 0x6000) === 0x6000) {
1✔
374
            $symbolic = 'b'; // Block special
1✔
375
        } elseif (($perms & 0x4000) === 0x4000) {
1✔
376
            $symbolic = 'd'; // Directory
1✔
377
        } elseif (($perms & 0x2000) === 0x2000) {
1✔
378
            $symbolic = 'c'; // Character special
1✔
379
        } elseif (($perms & 0x1000) === 0x1000) {
1✔
380
            $symbolic = 'p'; // FIFO pipe
1✔
381
        } else {
382
            $symbolic = 'u'; // Unknown
1✔
383
        }
384

385
        // Owner
386
        $symbolic .= ((($perms & 0x0100) !== 0) ? 'r' : '-')
1✔
387
                . ((($perms & 0x0080) !== 0) ? 'w' : '-')
1✔
388
                . ((($perms & 0x0040) !== 0) ? ((($perms & 0x0800) !== 0) ? 's' : 'x') : ((($perms & 0x0800) !== 0) ? 'S' : '-'));
1✔
389

390
        // Group
391
        $symbolic .= ((($perms & 0x0020) !== 0) ? 'r' : '-')
1✔
392
                . ((($perms & 0x0010) !== 0) ? 'w' : '-')
1✔
393
                . ((($perms & 0x0008) !== 0) ? ((($perms & 0x0400) !== 0) ? 's' : 'x') : ((($perms & 0x0400) !== 0) ? 'S' : '-'));
1✔
394

395
        // World
396
        $symbolic .= ((($perms & 0x0004) !== 0) ? 'r' : '-')
1✔
397
                . ((($perms & 0x0002) !== 0) ? 'w' : '-')
1✔
398
                . ((($perms & 0x0001) !== 0) ? ((($perms & 0x0200) !== 0) ? 't' : 'x') : ((($perms & 0x0200) !== 0) ? 'T' : '-'));
1✔
399

400
        return $symbolic;
1✔
401
    }
402
}
403

404
if (! function_exists('octal_permissions')) {
5✔
405
    /**
406
     * Octal Permissions
407
     *
408
     * Takes a numeric value representing a file's permissions and returns
409
     * a three character string representing the file's octal permissions
410
     *
411
     * @param int $perms Permissions
412
     */
413
    function octal_permissions(int $perms): string
414
    {
415
        return substr(sprintf('%o', $perms), -3);
5✔
416
    }
417
}
418

419
if (! function_exists('same_file')) {
5✔
420
    /**
421
     * Checks if two files both exist and have identical hashes
422
     *
423
     * @return bool Same or not
424
     */
425
    function same_file(string $file1, string $file2): bool
426
    {
427
        return is_file($file1) && is_file($file2) && md5_file($file1) === md5_file($file2);
11✔
428
    }
429
}
430

431
if (! function_exists('set_realpath')) {
5✔
432
    /**
433
     * Set Realpath
434
     *
435
     * @param bool $checkExistence Checks to see if the path exists
436
     */
437
    function set_realpath(string $path, bool $checkExistence = false): string
438
    {
439
        // Security check to make sure the path is NOT a URL. No remote file inclusion!
440
        if (preg_match('#^(http:\/\/|https:\/\/|www\.|ftp)#i', $path) || filter_var($path, FILTER_VALIDATE_IP) === $path) {
86✔
441
            throw new InvalidArgumentException('The path you submitted must be a local server path, not a URL');
1✔
442
        }
443

444
        // Resolve the path
445
        if (realpath($path) !== false) {
85✔
446
            $path = realpath($path);
82✔
447
        } elseif ($checkExistence && ! is_dir($path) && ! is_file($path)) {
12✔
448
            throw new InvalidArgumentException('Not a valid path: ' . $path);
1✔
449
        }
450

451
        // Add a trailing slash, if this is a directory
452
        return is_dir($path) ? rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $path;
84✔
453
    }
454
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc