FilesystemLoader in 6.0.1
For me the new 6.x API feels better, however I've encountered an issue with the FilesystemLoader component.
In the original TwigPHP implementation, the FilesystemLoader ( https://twig.symfony.com/doc/3.x/api.html#built-in-loaders ) is capable of loading from multiple directories. In contrast, the current implementation in Twing v6.0.1 seems to only load files from the current working directory (CWD). The abstract FS implementation is a great idea, but I really miss the paths parameter of the previous version.
Is there some utility function or parameter that I overlooked? Or you consider this feature to be the responsibility of the FS implementation?
My hacky solution was to implement a wrapper that can recieve these paths:
function cwdfs(fs: TwingFilesystemLoaderFilesystem, paths: string | string[]): TwingFilesystemLoaderFilesystem {
if (!Array.isArray(paths)) paths = [paths];
return {
readFile: (filePath, callback: any) => {
findPath(filePath, (err, fullPath) => {
if (err) return callback(err);
fs.readFile(fullPath!, callback);
});
},
stat: (filePath, callback: any) => {
findPath(filePath, (err, fullPath) => {
if (err) return callback(err);
fs.stat(fullPath!, callback);
});
},
};
function findPath(filePath: string, callback: (err: Error | null, path?: string) => void) {
let checkedPaths = 0;
for (let p of paths) {
const fullPath = join(p, filePath);
fs.stat(fullPath, (err, stats) => {
if (!err && stats!.isFile()) {
return callback(null, fullPath);
}
if (++checkedPaths === paths.length) {
callback(new Error(`File not found: ${filePath}`));
}
});
}
}
}
const loader = createFilesystemLoader(
cwdfs(require('node:fs'), ['path1', 'path2'])
);