Files
picea/src/FileFetcher.php
T

119 lines
3.5 KiB
PHP

<?php declare(strict_types=1);
namespace Picea;
use RecursiveIteratorIterator, RecursiveDirectoryIterator;
class FileFetcher
{
protected array $folderList = [];
public array $supportedExtensionList = [
"phtml", "php", "html",
];
public function __construct(?array $folderList = null) {
if ( $folderList !== null ) {
$this->addFolders($folderList);
}
}
public function addFolder(string $folder, int $order = 100) : void
{
$folder = $this->normalizeFolder($folder);
$this->folderList[$folder] = [
'path' => $folder,
'order' => $order,
];
}
public function addFolders(array $folderList) : void
{
foreach($folderList as $folder) {
$this->addFolder($folder['path'], $folder['order']);
}
}
protected function normalizeFolder(string $path) : string
{
return rtrim($path, '/\\');
}
public function folderList(?array $set = null) : ?array
{
return $set === null ? $this->folderList : $this->folderList = $set;
}
public function findFile(string $fileName) : string
{
usort($this->folderList, fn($a, $b) => $a['order'] <=> $b['order']);
foreach($this->folderList() as $folder) {
foreach($this->supportedExtensionList as $extension) {
$file = $folder['path'] . DIRECTORY_SEPARATOR . "$fileName.$extension";
$file = str_replace([ '\\', '/' ], DIRECTORY_SEPARATOR, $file);
if ( file_exists($file) ) {
if ( is_dir($file) ) {
throw new \RuntimeException("Given view file `$fileName` is a folder, you must provide a valid filename.");
}
return $file;
}
}
}
# Fallback on full-path
foreach($this->folderList() as $folder) {
$file = $folder['path'] . DIRECTORY_SEPARATOR . $fileName;
$file = str_replace([ '\\', '/' ], DIRECTORY_SEPARATOR, $file);
if ( file_exists($file) ) {
if ( is_dir($file) ) {
throw new \RuntimeException("Given view file `$fileName` is a folder, you must provide a valid filename.");
}
return $file;
}
}
throw new \RuntimeException("Given view file `$fileName` can not be found within given folder list..");
}
public function getFileList() : array
{
usort($this->folderList, fn($a, $b) => $a['order'] <=> $b['order']);
$list = [];
foreach($this->folderList() as $folder) {
$path = $folder['path'] . "/";
$list[$path] = [];
if ( \file_exists($path) ) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach ($iterator as $file) {
if ($file->isFile() && in_array($file->getExtension(), $this->supportedExtensionList)) {
$list[$path][] = $file;
}
}
}
}
return $list;
}
public function getFilePath(string $fileName) : string
{
return $this->findFile($fileName);
}
public function getFileContent(string $fileName) : string
{
return file_get_contents($this->getFilePath($fileName));
}
}