<?php

namespace Velis\Dto\Validators;

use Attribute;

#[Attribute]
class ArrayLengthRange extends BaseValidator
{
    public function __construct(
        private readonly ?int $min = null,
        private readonly ?int $max = null
    ) {
    }

    public function validate($value): bool
    {
        if (!is_array($value)) {
            return false;
        }

        $length = count($value);

        return $this->checkMin($length) && $this->checkMax($length);
    }

    private function checkMin(int $length): bool
    {
        if ($this->min !== null && $length < $this->min) {
            $this->message = sprintf('Array must contain at least %s elements', $this->min);

            return false;
        }

        return true;
    }

    private function checkMax(int $length): bool
    {
        if ($this->max !== null && $length > $this->max) {
            $this->message = sprintf('Array must not contain more than %s elements', $this->max);

            return false;
        }

        return true;
    }
}
