<?php

namespace Velis\Mvc\Validators\Rules;

use Velis\Exception;

class ArrayOfType implements RuleInterface
{
    private string $type;

    public function __construct(string $type)
    {
        if (!in_array($type, Type::allowedTypes())) {
            throw new Exception("Invalid type {$type}");
        }

        $this->type = $type;
    }

    public function validate(array $data, string $fieldName): bool
    {
        return !array_key_exists($fieldName, $data)
            || is_array($data[$fieldName])
            && array_reduce($data[$fieldName], function ($acc, $item) {
                return $acc && (new Type($this->type))->validate(['value' => $item], 'value');
            }, true);
    }

    public function getErrorMessage($fieldName): string
    {
        return "The {$fieldName} must be an array of {$this->type} elements";
    }
}
