<?php

namespace Application\Service\Extension\ValidatorV2\validators;

use Application\Service\Extension\Helper\StringHelper;

class NumberValidator extends BaseValidator
{
    public $min = 0;

    public $max = 0;

    public bool $integerOnly = false;

    public string $integerPattern = '/^[+-]?\d+$/';

    public string $numberPattern = '/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/';


    public function max($value)
    {
        $this->max = $value;

        return $this;
    }

    public function min($value)
    {
        $this->min = $value;

        return $this;
    }

    public function valid($value, $attribute)
    {
        // 如果数字填写的是空值, 则不验证
        if ($value === '') {
            return null;
        }

        if ($this->isNotNumber($value)) {
            $this->error = ['{attribute} 格式错误.', [
                'attribute' => $attribute
            ]];
            return null;
        }

        $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;

        if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
            $this->error = ['{attribute} 格式错误.', [
                'attribute' => $attribute
            ]];
            return null;
        }

        if ($this->min !== 0 && $value < $this->min) {
            $this->error = ['{attribute} 不能小于 {min}', [
                'attribute' => $attribute,
                'min' => $this->min
            ]];
            return null;
        } elseif ($this->max !== 0 && $value > $this->max) {
            $this->error = ['{attribute} 不能大于 {max}.', [
                'attribute' => $attribute,
                'max' => $this->max
            ]];
        }

        return null;
    }

    private function isNotNumber($value): bool
    {
        return is_array($value)
            || is_bool($value)
            || (is_object($value) && !method_exists($value, '__toString'))
            || (!is_object($value) && !is_scalar($value) && $value !== null);
    }
}