<?php

declare(strict_types=1);

namespace apexl\Io\modules\validation\ValidationRules;

use ValueError;

final readonly class CharLength extends ValidationRule
{
    protected final const string NAME = 'length';

    public function __construct(int $min = 0, ?int $max = null)
    {
        if ($min === 0 && $max === null) {
            throw new ValueError('`$min` or `$max` must be supplied');
        }

        $config = trim(sprintf('%s,%s', $min, $max ?? ''), ',');

        return parent::__construct($config);
    }

    public function toValidatorString(): string
    {
        [$min, $max] = array_pad(explode(',', $this->config), 2, null);

        $rules = [sprintf('min:%d', $min)];
        if ($max) {
            $rules[] = sprintf('max:%d', $max);
        }

        return implode('|', $rules);
    }

}
