Skip to content

Commit

Permalink
Merge pull request #57 from veewee/improved-function-autoloading
Browse files Browse the repository at this point in the history
Improve function autolaoding
  • Loading branch information
veewee committed Nov 3, 2023
2 parents 8dda371 + edb7694 commit 43c8e0e
Show file tree
Hide file tree
Showing 2 changed files with 199 additions and 167 deletions.
28 changes: 25 additions & 3 deletions build/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
require $root.'/vendor/autoload.php';
$src = $root.'/src';
$target = $src.'/bootstrap.php';
$tab = ' ';

// Clear file first!
write($target, '', WriteMode::TRUNCATE);
Expand All @@ -28,14 +29,35 @@
->sortByName()
->getIterator();

$autoload = <<<'EOPHP'
foreach ($functions as $function => $file) {
if (!\function_exists($function)) {
require_once $file;
}
}
EOPHP;


/** @var callable(list<SplFileInfo>):string $build */
$build = pipe(
static fn (iterable $files): iterable => map(
$files,
static fn (SplFileInfo $file): string => 'require_once __DIR__.\'/'.$file->getRelativePathname().'\';'
static function (SplFileInfo $file) use ($tab): string {
$path = $file->getRelativePathname();
$function = $file->getFilenameWithoutExtension();
$namespace = str_replace('/', '\\', $file->getRelativePath());

return sprintf($tab.'$functions[\'%s\'] = __DIR__.\'/%s\';', $namespace.'\\'.$function, $path);
}
),
static fn (iterable $codeLines): iterable => concat(['<?php declare(strict_types=1);', ''], $codeLines),
static fn (iterable $codeLines): iterable => concat($codeLines, ['']),
static fn (iterable $codeLines): iterable => concat([
'<?php declare(strict_types=1);',
'',
'(static function (): void {',
$tab . '/** @var array<string, string> $functions */',
$tab . '$functions = [];',
], $codeLines),
static fn (iterable $codeLines): iterable => concat($codeLines, ['', $autoload, '})();', '']),
static fn (iterable $codeLines): string => join($codeLines, PHP_EOL)
);

Expand Down
Loading

0 comments on commit 43c8e0e

Please sign in to comment.