1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flynt\Utils; |
4
|
|
|
|
5
|
|
|
use DirectoryIterator; |
6
|
|
|
|
7
|
|
|
class FileLoader |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Iterates through a directory and executes the provided callback function |
11
|
|
|
* on each file or folder in the directory (excluding dot files). |
12
|
|
|
* |
13
|
|
|
* @since 0.1.0 |
14
|
|
|
* |
15
|
|
|
* @param string $dir Absolute path to the directory. |
16
|
|
|
* @param callable $callback The callback function. |
17
|
|
|
* |
18
|
|
|
* @return array An array of the callback results. |
19
|
|
|
*/ |
20
|
|
|
public static function iterateDir($dir, callable $callback) |
21
|
|
|
{ |
22
|
|
|
$output = []; |
23
|
|
|
|
24
|
|
|
if (!is_dir($dir)) { |
25
|
|
|
return $output; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$directoryIterator = new DirectoryIterator($dir); |
29
|
|
|
|
30
|
|
|
foreach ($directoryIterator as $file) { |
31
|
|
|
if ($file->isDot()) { |
32
|
|
|
continue; |
33
|
|
|
} |
34
|
|
|
$callbackResult = call_user_func($callback, $file); |
35
|
|
|
array_push($output, $callbackResult); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return $output; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Recursively require all files in a specific directory. |
43
|
|
|
* |
44
|
|
|
* By default, requires all php files in a specific directory once. |
45
|
|
|
* Optionally able to specify the files in an array to load in a certain order. |
46
|
|
|
* Starting and trailing slashes will be stripped for the directory and all files provided. |
47
|
|
|
* |
48
|
|
|
* @since 0.1.0 |
49
|
|
|
* |
50
|
|
|
* @param string $dir Directory to search through. |
51
|
|
|
* @param array $files Optional array of files to include. If this is set, only the files specified will be loaded. |
52
|
|
|
*/ |
53
|
|
|
public static function loadPhpFiles($dir, $files = []) |
54
|
|
|
{ |
55
|
|
|
$dir = trim($dir, '/'); |
56
|
|
|
|
57
|
|
|
if (count($files) === 0) { |
58
|
|
|
$dir = get_template_directory() . '/' . $dir; |
59
|
|
|
|
60
|
|
|
self::iterateDir($dir, function ($file) { |
61
|
|
|
if ($file->isDir()) { |
62
|
|
|
$dirPath = trim(str_replace(get_template_directory(), '', $file->getPathname()), '/'); |
63
|
|
|
self::loadPhpFiles($dirPath); |
64
|
|
|
} elseif ($file->isFile() && $file->getExtension() === 'php') { |
65
|
|
|
$filePath = $file->getPathname(); |
66
|
|
|
require_once $filePath; |
67
|
|
|
} |
68
|
|
|
}); |
69
|
|
|
} else { |
70
|
|
|
array_walk($files, function ($file) use ($dir) { |
71
|
|
|
$filePath = $dir . '/' . ltrim($file, '/'); |
72
|
|
|
|
73
|
|
|
if (!locate_template($filePath, true, true)) { |
74
|
|
|
trigger_error( |
75
|
|
|
sprintf('Error locating %s for inclusion', $filePath), |
76
|
|
|
E_USER_ERROR |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
}); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|