<?php

namespace Application\Service\Extension\Validator\customer;

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

class FunctionValidator extends BaseCustomValidator
{
    public string $method = '';

    public string $targetClass = '';

    public function __construct(array $config = [])
    {
        parent::__construct($config);
        if (!$this->method) {
            throw new \Exception('没写method!!');
        }
        if (!$this->targetClass) {
            throw new \Exception('没写tergetClass');
        }
    }

    public function isValid($value, $attribute)
    {
        if (is_string($this->targetClass)) {
            $class = ValidatorApplication::createObejct($this->targetClass);
        } elseif (is_object($this->targetClass)){
            $class = $this->targetClass;
        }

        if (!method_exists($class, $this->method)) {
            throw new \Exception("没有{$this->method}这个方法");
        }

        return call_user_func_array([$class, $this->method], [$value, $attribute]);
    }
}
