<?php

namespace Application\Service\Extension\Validator\customer;

use Application\Service\Extension\Validator\BaseCustomValidator;
use Application\Service\Extension\Validator\CustomerValidatorInterface;

class StringValidator extends BaseCustomValidator implements CustomerValidatorInterface
{
    /**
     * 最小长度
     * @var
     */
    public int $min = 0;

    /**
     * @var
     */
    public int $max = 0;


    public int $notEqual = 0;

    public int $equal = 0;

    public string $encoding = 'UTF-8';

    public bool $strict = false;

    public function isValid($value, $attribute)
    {
        if (!$this->strict && is_scalar($value) && !is_string($value)) {
            $value = (string)$value;
        }

        if (!is_string($value)) {
            return ['{attribute} 必须是一个字符串.', []];
        }

        $length = mb_strlen($value, $this->encoding);

        if ($this->min !== 0 && $length < $this->min) {
            return ['{attribute} 至少包含 {min} 个字符.', ['min' => $this->min]];
        }

        if ($this->max !== 0 && $length > $this->max) {
            return ['{attribute} 至多包含 {max} 个字符.', ['max' => $this->max]];
        }

        if ($this->notEqual !== 0 && $length === $this->notEqual) {
            return ['{attribute} 不能为 {length} 个字符.', ['length' => $this->notEqual]];
        }

        if ($this->equal !== 0 && $length !== $this->equal) {
            return ['{attribute} 必须包含 {length} 个字符.', ['length' => $this->equal]];
        }

        return null;
    }
}