<?php

namespace App\Models\traits;

trait Filter
{
    /**
     * 过滤
     */
    public function scopeFilter($query)
    {
        $filters = $this->getFilterClass($query);
        if ($filters) {

            return $filters->apply($query);
        }

        return $query;
    }

    //自动获取过滤的类
    private function getFilterClass($query)
    {
        $prefix = 'App\Filters\\';
        $filterClass = $this->getModelFilterClass($query);
        if (!$filterClass) {
            $currentClass = get_class($this);
            $className = substr(strrchr($currentClass, '\\'), 1). 'Filter';
        }
        $filterClass = $prefix.$className;
        if (class_exists($filterClass)) {

            return new $filterClass();
        }
        $filterClass = $prefix.'Filters';

        return new $filterClass();
    }

    //查看 model是否有 getModelClassName 方法
    private function getModelFilterClass($query)
    {
        $model = $query->getModel();
        $className = '';
        if (method_exists($model, 'getFilterClassName')) {
            $className = $model->getFilterClassName();
        }

        return $className;
    }

}
