<?php

namespace Validate;

use Api\PhpUtils\Validate\Validate;
use App\Exception\custom\Code;
use App\Exception\custom\ParamException;
use Yaf\Dispatcher;


class BaseValidate extends Validate
{
    /**
     * 参数校验
     * @return array | boolean
     * @throws
     */
    public function validate()
    {
        $params = Dispatcher::getInstance()->getRequest()->getRequest();
        $result = $this->batch()->check($params);
        if (!$result) {
            $msg = $this->getError() ? array_shift($this->error) : "参数错误";
            throw new ParamException([
                'msg'  => $msg,
                "code" => Code::PARAM
            ]);
        } else {
            return true;
        }
    }

    protected function isPositiveInteger($value)
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        } else {
            return false;
        }
    }

    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    protected function idcard($value){
        $weight   = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        $codes    = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

        if(strlen($value)!=18){
            return false;
        }

        $validate = substr($value, 0, 17);
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += $validate[$i] * $weight[$i];
        }

        return $codes[$sum % 11] === substr($value, 17, 1);
    }
}