<?php

namespace app\validate;

use think\Validate;

class Category extends Validate
{
    protected $rule =  [
        'parent_id|父级分类'       => 'require|number',
        'model_id|所属模型'  => 'require|number|gt:0',
        'title|标题'       => 'require|max:100',
        'description|描述' => 'max:255',
        'route|路由' =>"routeValidate",
        'category_key|标识' =>"alphaDash",
    ];

    protected $message = [
        'model_id'     => '所属模型必需选择',
        'route.routeValidate'     => '路由不符合指定规范',
        'route.unique'     => '路由已存在',
    ];

    protected function routeValidate($value)
    {
        $chars =preg_replace('/\s+/','',
            "/^(
              
                [\/]{1} 
                
                (
                
                
                (
               
                ([A-Za-z0-9_-]*[A-Za-z_-]+)
                |
                ([A-Za-z_-]+[A-Za-z0-9_-]*)
                )
                
                |
                
                 (
                ([A-Za-z0-9_-]+[A-Za-z_-]+[A-Za-z0-9_-]+)
                |
                ([A-Za-z_-]+[A-Za-z0-9_-]+[A-Za-z_-]+)
                )
                
                )
                
                
                )+
                
               $/");

        if (  preg_match($chars, $value)){
            return true;

        }else{

            return "路由不符合指定规范";

        }
    }

    // edit 验证场景定义
    public function sceneEdit()
    {
        $id =  input('id/d', 0);
        return $this->append('route', 'unique:category,route,' .$id . '|unique:article,route' . '|unique:special_route,route'  )
            ->append("category_key",'unique:category,category_key,' .$id );
    }
    public function sceneAdd()
    {
        return $this->append('route', 'unique:category,route|unique:article,route|unique:special_route,route')
            ->append("category_key",'unique:category,category_key' );
    }

}