<?php

namespace Application\Service\Extension\Validator\customer;

use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Validator\BaseCustomValidator;

class NumberValidator extends BaseCustomValidator
{
    public int $min = 0;

    public int $max = 0;

    public bool $integerOnly;

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

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

    public function isValid($value, $attribute)
    {
        if ($this->isNotNumber($value)) {
            return ['{attribute} is invalid.', []];
        }

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

        if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
            return $this->formatMessage('{attribute} 必须是一个整数.', [
                'attribute' => $this->getAttributeLabel($attribute)
            ]);
        } elseif ($this->min !== 0 && $value < $this->min) {
            return ['{attribute} must be no less than {min}.', ['min' => $this->min]];
        } elseif ($this->max !== 0 && $value > $this->max) {
            return ['{attribute} must be no greater than {max}.', ['max' => $this->max]];
        }

        return null;
    }

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