<?php

declare(strict_types=1);

namespace Dedi\SyliusTheme\Twig;

use Symfony\Component\Finder\Finder;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class ListFilesExtension extends AbstractExtension
{
    private readonly string $baseDirectory;

    public function __construct(string $baseDirectory)
    {
        $this->baseDirectory = $baseDirectory;
    }

    public function getFunctions()
    {
        return [
            new TwigFunction('list_files', [$this, '__invoke']),
        ];
    }

    public function __invoke(string $directory): array
    {
        $finder = new Finder();

        $files = $finder
            ->depth(0)
            ->sortByName()
            ->files()
            ->in(sprintf('%s%s%s', $this->baseDirectory, \DIRECTORY_SEPARATOR, $directory))
        ;

        $files = array_map(fn ($file) => $file->getFilename(), iterator_to_array($files));

        return $files;
    }
}
