diff --git a/Preloader.php b/Preloader.php new file mode 100644 index 000000000..6afdb9b08 --- /dev/null +++ b/Preloader.php @@ -0,0 +1,152 @@ +ignores[] = $path; + + return $this; + } + + /** + * Add a path to preload + * + * @param string $path Path to preload + * + * @return Preloader + * + * @since 1.0.0 + */ + public function includePath(string $path) : self + { + $this->includes[] = $path; + + return $this; + } + + /** + * Load paths + * + * @return void + * + * @since 1.0.0 + */ + public function load() : void + { + foreach ($this->includes as $include) { + if (\in_array($include, ['.', '..']) + || \in_array($include, $this->ignores) + ) { + continue; + } + + if (\is_dir($include)) { + $this->loadDir($include); + } elseif (\is_file($include)) { + $this->loadFile($include); + } + } + } + + /** + * Load directory paths + * + * @param string $path Path to load + * + * @return void + * + * @since 1.0.0 + */ + private function loadDir(string $path) : void + { + $fh = \opendir($path); + + if ($fh === false) { + return; + } + + while ($file = \readdir($fh)) { + if (\in_array($file, ['.', '..']) + || \in_array($file, $this->ignores) + ) { + continue; + } + + if (\is_dir($path . '/' . $file)) { + $this->loadDir($path . '/' . $file); + } elseif (\is_file($path . '/' . $file)) { + $this->loadFile($path . '/' . $file); + } + } + + \closedir($fh); + } + + /** + * Load file + * + * @param string $path Path to load + * + * @return void + * + * @since 1.0.0 + */ + private function loadFile(string $path) : void + { + if (\in_array($path, $this->ignores) + || \substr($path, -\strlen('.php')) !== '.php' + ) { + return; + } + + require_once($path); + } +}