<?php

namespace Velis\Dto\Validators;

use Attribute;

/**
 * String length checking validator.
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
#[Attribute]
class LengthRange extends BaseValidator
{
    public function __construct(
        public ?int $min = null,
        public ?int $max = null,
        public string $message = 'Invalid length'
    ) {
    }

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

        $strlen = mb_strlen($value);

        // Instead of just checking size, we can set a custom message for each invalidation variant.
        return $this->checkMin($strlen) && $this->checkMax($strlen);
    }

    /**
     * When our string is too short, we set a custom message and return false.
     */
    private function checkMin(int $strlen): bool
    {
        if ($this->min !== null && $strlen < $this->min) {
            $this->message = 'Value is too short';

            return false;
        }

        return true;
    }

    /**
     * When our string is too long, we set a custom message and return false.
     */
    private function checkMax(int $strlen): bool
    {
        if ($this->max !== null && $strlen > $this->max) {
            $this->message = 'Value is too long';

            return false;
        }

        return true;
    }
}
