Files
wh-api/app/Scope/CompanyScope.php
ykxiao 0b2299c427
Some checks failed
Build Docker / build (push) Has been cancelled
协程版仓库后端项目
2025-07-08 14:59:47 +08:00

73 lines
2.0 KiB
PHP
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Author: ykxiao
* Date: 2024/12/24
* Time: 下午3:19
* Description:
*
* (c) ykxiao <yk_9001@hotmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
declare(strict_types=1);
namespace App\Scope;
use App\Context\QueueContext;
use App\Context\UserContext;
use App\Utils\TableUtils;
use Exception;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\Database\Model\Scope;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
/**
* Author: ykxiao
* Date: 2025/5/7
* Time: 下午4:38
* Description: 作用域类,用于限制查询结果为当前公司、供应商的记录。
*
* (c) ykxiao <yk_9001@hotmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
class CompanyScope implements Scope
{
use TableUtils;
#[Inject]
protected Redis $redis;
/**
* 将当前用户所属公司的条件应用于查询构建器。
*
* @param Builder $builder 查询构建器实例。
* @param Model $model 模型实例,通常是想要应用作用域的模型。
* @return Builder 应用了作用域条件的查询构建器实例。
* @throws Exception
*/
public function apply(Builder $builder, Model $model): Builder
{
// 尝试从上下文中获取当前用户信息
$user = QueueContext::getUser() ?? UserContext::getCurrentUser();
$company = $user['company'];
// 如果没有找到用户信息,则不应用任何条件,直接返回查询构建器
if (!$user || !$company) {
return $builder;
}
// 如果存在 company_id应用企业作用域
if (!empty($companyId = $company['id'] ?? null)) {
return self::hasColumn($model, 'company_id')
? $builder->where($model->getTable() . '.company_id', $companyId)
: $builder;
}
return $builder;
}
}