<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use app\validate\domain\DomainValidatorInterface;


/**
 * 控制器基类
 * Request 注入、验证器调用、DomainValidator
 * @package app
 */
abstract class BaseController
{
    /**
     * 请求对象
     * @var Request
     */
    protected $request;

    /**
     * 应用对象
     * @var App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造函数
     * @param App $app
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;
        $this->initialize();
    }


    /**
     * 初始化方法
     */
    protected function initialize()
    {}


    /**
     * 验证数据
     * @param array $data
     * @param string|array $validate
     * @param array $message
     * @param bool $batch
     * @return bool
     */
    protected function validate(array $data, string|array $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {

                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 验证域验证器
     * @param DomainValidatorInterface $validator
     * @param array $data
     * @param string $scene
     * @return bool
     */
    protected function validateDomain(DomainValidatorInterface $validator, array $data, string $scene = '')
    {
        $result = $validator->validate($data, $scene);
        if (!($result['ok'] ?? false)) {
            $errors = $result['errors'] ?? [];
            $firstError = reset($errors);
            $firstKey = key($errors);
            throw new ValidateException(
                is_string($firstError) ? $firstError : '',
                $firstKey
            );
        }
        return true;
    }
}