<?php declare(strict_types=1);

namespace Newland\NeosFiltering\DataSource;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Neos\Service\DataSource\DataSourceInterface;

/**
 * Wrapper for a data source that filters the results to only include the
 * whitelisted values.
 */
class DataSourceFilter implements DataSourceInterface
{

    /** @var DataSourceInterface */
    protected $dataSource;

    /** @var string[] */
    protected $allowedValues;

    public function __construct(DataSourceInterface $dataSource, array $allowedValues)
    {
        $this->dataSource = $dataSource;
        $this->allowedValues = $allowedValues;
    }

    public static function getIdentifier()
    {
        return 'newland-neosfiltering-wrapper';
    }

    public function getData(NodeInterface $node = null, array $arguments)
    {
        // Transform array of allowed values into hash for faster access times
        $allowed = [];
        foreach ($this->allowedValues as $value) {
            $allowed[$value] = true;
        }

        return array_filter(
            $this->dataSource->getData($node, $arguments),
            function (array $item) use (&$allowed) {
                return $allowed[$item['value']] ?? false;
            }
        );
    }
}
