<?php

namespace Application\Service\Extension\ValidatorV2;

use Application\Service\Extension\ValidatorV2\exceptions\InvalidValidatorArgumentException;
use Application\Service\Extension\ValidatorV2\rules\Required;


/**
 * @method Required required($field) 必填
 * @method number($field)
 * @method default($field)
 * @method function($field)
 */
class Container
{
    private array $validators = [];

    private array $rules = [];

    private array $validatorProviders = [
        'required' => Required::class
    ];


    public function __construct($validators)
    {
        if (is_string($validators)) {
            $validators = array($validators);
        }
        $this->validators = $validators;
    }

    /**
     * @param string $validatorName
     * @return Container
     */
    public function select($validatorName = 'default')
    {
        return function ($validatorName) {
            return $this;
        };
    }

    public function __call($name, $arguments)
    {
        if (!$this->offsetExists($name)) {
            if (!isset($this->validatorProviders[$name])) {
                throw new InvalidValidatorArgumentException("没有 {$name} 这个验证器。");
            }

            // 实例化验证器
            $validation = new $this->validatorProviders[$name]();

            $name = spl_object_hash($validation);

            $this->offsetSet($name, $validation);
        }

        return $this->offsetGet($name);
    }

    public function isValid($validatorName = 'default'): bool
    {
        foreach ($this->rules[$validatorName] as $rule) {
            if ($this->valid($rule) !== true) {
                return false;
            }
        }

        return true;
    }

    public function valid(array $rules): bool
    {
        list($attributes, $rule) = $rules;

        return true;
    }
}