picea/src/FileFetcher.php

75 lines
1.9 KiB
PHP

<?php declare(strict_types=1);
namespace Picea;
class FileFetcher
{
protected array $folderList = [];
public array $supportedExtensionList = [
"phtml", "php", "html",
];
public function __construct(?array $folderList = null) {
if ( $folderList !== null ) {
$this->folderList = $folderList;
}
}
public function addFolder(string $folder, int $order = 100) : void
{
$folder = rtrim($folder, DIRECTORY_SEPARATOR);
$this->folderList[$folder] = [
'path' => $folder,
'order' => $order,
];
}
public function addFolders(array $folderList) : void
{
$this->folderList = array_replace($this->folderList, $folderList);
}
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";
if ( file_exists($file) ) {
return $file;
}
}
}
# Fallback on full-path
foreach($this->folderList as $folder) {
$file = $folder['path'] . DIRECTORY_SEPARATOR . $fileName;
if ( file_exists($file) ) {
return $file;
}
}
throw new \RuntimeException("Given view file `$fileName` can not be found within given folder list..");
}
public function getFilePath(string $fileName) : string
{
return $this->findFile($fileName);
}
public function getFileContent(string $fileName) : string
{
return file_get_contents($this->getFilePath($fileName));
}
}