<?php


namespace AutoAdmin\Bundle\Seo\Extractor;


use AutoAdmin\Bundle\Seo\Model\SeoPage;
use Symfony\Component\HttpFoundation\Request;
use Traversable;

class ExtractorManager
{
    private array $extractors;

    public function __construct(Traversable $extractors)
    {
        // aa_seo.extractor
        $this->extractors = array_map([$this, 'add'], iterator_to_array($extractors));
    }

    /**
     * todo: allow extractors to only handle a part of the data,
     * todo: in order to combine multiple extractors to rebuild SeoPage from different sources
     */
    public function extract(Request $request, object $subject, SeoPage $seoPage): ?SeoPage
    {
        $extracted = $seoPage;
        $route = $request->get('_route');

        /** @var ExtractorInterface $extractor */
        foreach ($this->extractors as $extractor) {
            if ($extractor->supports($subject, $route)) {
                /** @var SeoPage $extracted */
                $extracted = $extractor->extract($request, $subject, $extracted);
            }
        }

        return $extracted;
    }

    protected function add(ExtractorInterface $extractor): ExtractorInterface
    {
        return $extractor;
    }
}
