This repository has been archived on 2025-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
notes-cronard/src/TaskFetcher.php
2023-01-26 18:49:56 +00:00

102 lines
3.0 KiB
PHP

<?php namespace Notes\Cronard;
use Kash\HandleCacheTrait;
use Notes\ObjectResolver;
use Psr\SimpleCache\CacheInterface;
use RuntimeException, DirectoryIterator, Generator, Closure;
class TaskFetcher {
use HandleCacheTrait;
protected array $folderList;
protected Closure $callback;
public array $defaultMethods = [ 'GET', 'POST' ];
protected array $annotations;
public function __construct( ?array $folderList = null, ?array $annotations = null, ? CacheInterface $cache = null)
{
$this->cache = $cache;
if ($folderList !== null) {
$this->folderList = $folderList;
}
if ($annotations !== null) {
$this->annotations = $annotations;
}
else {
$this->annotations = [
'method' => [ Annotation\Method\Cronard::class, Attribute\Method\Cronard::class ],
];
}
}
public function addFolder($folder) : void
{
$this->folderList[] = $folder;
}
public function setFolderList(array $list) : void
{
$this->folderList = $list;
}
public function scan(? array $folders = null) : Generator
{
foreach($folders ?: $this->folderList as $namespace => $folder) {
if ( ! file_exists($folder) ) {
throw new RuntimeException(sprintf("Folder `%s` can not be found or scanned", $folder));
}
foreach (new DirectoryIterator($folder) as $fileinfo) {
if ( ! $fileinfo->isDot() ) {
if ( $fileinfo->isDir() ) {
foreach($this->scan([ "{$namespace}\\" . $fileinfo->getBasename() => $fileinfo->getPathname() ]) as $ns2 => $fi2) {
yield $ns2 => $fi2;
}
}
else {
yield $namespace => $fileinfo;
}
}
}
}
}
public function compile() : array
{
return $this->handleCaching(substr(md5(serialize($this->annotations)), 0, 7), function() : array {
foreach($this->scan() as $namespace => $file) {
if ( $file->getExtension() !== "php" ) {
continue;
}
$class = $this->generateClassname($file->getBasename(".php"), $namespace);
# Should generate an equivalent of Ulmus's object reflection here !
$objectResolver = new ObjectResolver($class, true, true, false, true);
$taskList = $objectResolver->getAnnotationListFromClassname( $this->annotations['method'], false );
foreach($taskList as $func => $cronard) {
foreach($cronard as $task) {
$list[] = [ 'class' => $class, 'method' => $func, 'annotation' => $task ];
}
}
}
return $list;
});
}
protected function generateClassname($file, $namespace)
{
return "\\$namespace\\$file";
}
}