ResultOperation.php 7.3 KB
Newer Older
D
Devil 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace think\db\concern;

use Closure;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\helper\Str;
use think\Model;

/**
 * 查询数据处理
 */
trait ResultOperation
{
    /**
     * 是否允许返回空数据(或空模型)
     * @access public
     * @param bool $allowEmpty 是否允许为空
     * @return $this
     */
    public function allowEmpty(bool $allowEmpty = true)
    {
        $this->options['allow_empty'] = $allowEmpty;
        return $this;
    }

    /**
     * 设置查询数据不存在是否抛出异常
     * @access public
     * @param bool $fail 数据不存在是否抛出异常
     * @return $this
     */
    public function failException(bool $fail = true)
    {
        $this->options['fail'] = $fail;
        return $this;
    }

    /**
     * 处理数据
     * @access protected
     * @param array $result 查询数据
     * @return void
     */
    protected function result(array &$result): void
    {
        if (!empty($this->options['json'])) {
            $this->jsonResult($result, $this->options['json'], true);
        }

        if (!empty($this->options['with_attr'])) {
            $this->getResultAttr($result, $this->options['with_attr']);
        }

        $this->filterResult($result);
    }

    /**
     * 处理数据集
     * @access public
     * @param array $resultSet 数据集
     * @return void
     */
    protected function resultSet(array &$resultSet): void
    {
        if (!empty($this->options['json'])) {
            foreach ($resultSet as &$result) {
                $this->jsonResult($result, $this->options['json'], true);
            }
        }

        if (!empty($this->options['with_attr'])) {
            foreach ($resultSet as &$result) {
                $this->getResultAttr($result, $this->options['with_attr']);
            }
        }

        if (!empty($this->options['visible']) || !empty($this->options['hidden'])) {
            foreach ($resultSet as &$result) {
                $this->filterResult($result);
            }
        }

        // 返回Collection对象
        $resultSet = new Collection($resultSet);
    }

    /**
     * 处理数据的可见和隐藏
     * @access protected
     * @param array $result 查询数据
     * @return void
     */
    protected function filterResult(&$result): void
    {
        $array = [];
        if (!empty($this->options['visible'])) {
            foreach ($this->options['visible'] as $key) {
                $array[] = $key;
            }
            $result = array_intersect_key($result, array_flip($array));
        } elseif (!empty($this->options['hidden'])) {
            foreach ($this->options['hidden'] as $key) {
                $array[] = $key;
            }
            $result = array_diff_key($result, array_flip($array));
        }
    }

    /**
     * 使用获取器处理数据
     * @access protected
     * @param array $result   查询数据
     * @param array $withAttr 字段获取器
     * @return void
     */
    protected function getResultAttr(array &$result, array $withAttr = []): void
    {
        foreach ($withAttr as $name => $closure) {
            $name = Str::snake($name);

            if (strpos($name, '.')) {
                // 支持JSON字段 获取器定义
                [$key, $field] = explode('.', $name);

                if (isset($result[$key])) {
                    $result[$key][$field] = $closure($result[$key][$field] ?? null, $result[$key]);
                }
            } else {
                $result[$name] = $closure($result[$name] ?? null, $result);
            }
        }
    }

    /**
     * 处理空数据
     * @access protected
D
Devil 已提交
152
     * @return array|Model|null|static
D
Devil 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    protected function resultToEmpty()
    {
        if (!empty($this->options['fail'])) {
            $this->throwNotFound();
        } elseif (!empty($this->options['allow_empty'])) {
            return !empty($this->model) ? $this->model->newInstance() : [];
        }
    }

    /**
     * 查找单条记录 不存在返回空数据(或者空模型)
     * @access public
     * @param mixed $data 数据
D
Devil 已提交
170
     * @return array|Model|static
D
Devil 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
     */
    public function findOrEmpty($data = null)
    {
        return $this->allowEmpty(true)->find($data);
    }

    /**
     * JSON字段数据转换
     * @access protected
     * @param array $result           查询数据
     * @param array $json             JSON字段
     * @param bool  $assoc            是否转换为数组
     * @param array $withRelationAttr 关联获取器
     * @return void
     */
    protected function jsonResult(array &$result, array $json = [], bool $assoc = false, array $withRelationAttr = []): void
    {
        foreach ($json as $name) {
            if (!isset($result[$name])) {
                continue;
            }

            $result[$name] = json_decode($result[$name], true);

            if (isset($withRelationAttr[$name])) {
                foreach ($withRelationAttr[$name] as $key => $closure) {
                    $result[$name][$key] = $closure($result[$name][$key] ?? null, $result[$name]);
                }
            }

            if (!$assoc) {
                $result[$name] = (object) $result[$name];
            }
        }
    }

    /**
     * 查询失败 抛出异常
     * @access protected
     * @return void
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    protected function throwNotFound(): void
    {
        if (!empty($this->model)) {
            $class = get_class($this->model);
            throw new ModelNotFoundException('model data Not Found:' . $class, $class, $this->options);
        }

        $table = $this->getTable();
        throw new DataNotFoundException('table data not Found:' . $table, $table, $this->options);
    }

    /**
     * 查找多条记录 如果不存在则抛出异常
     * @access public
     * @param array|string|Query|Closure $data 数据
D
Devil 已提交
229
     * @return array|Collection|static[]
D
Devil 已提交
230 231
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
D
Devil 已提交
232 233 234 235 236 237 238 239 240 241
     */
    public function selectOrFail($data = null)
    {
        return $this->failException(true)->select($data);
    }

    /**
     * 查找单条记录 如果不存在则抛出异常
     * @access public
     * @param array|string|Query|Closure $data 数据
D
Devil 已提交
242
     * @return array|Model|static
D
Devil 已提交
243 244
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
D
Devil 已提交
245 246 247 248 249 250 251
     */
    public function findOrFail($data = null)
    {
        return $this->failException(true)->find($data);
    }

}