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

73 lines
2.2 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
declare(strict_types=1);
namespace App\Listener;
use App\Context\QueueContext;
use App\Context\UserContext;
use Hyperf\Database\Model\Events\Creating;
use Hyperf\Database\Model\Events\Saving;
use Hyperf\Event\Annotation\Listener;
use Psr\Container\ContainerInterface;
use Hyperf\Event\Contract\ListenerInterface;
/**
* Author: ykxiao
* Date: 2025/05/24
* Time: 下午4:27
* 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.
*/
#[Listener]
class AutoMainFieldsListener implements ListenerInterface
{
public function __construct(protected ContainerInterface $container)
{
}
public function listen(): array
{
return [
Creating::class,
Saving::class,
];
}
public function process(object $event): void
{
/**
* 在模型创建或保存事件中自动设置模型的company_id和creator_id等相关字段。
* 这个逻辑只在用户上下文存在且事件为Creating或Saving时触发。
*
* @param object $event 事件对象预期为Creating或Saving事件之一。
* @return void
*/
$user = QueueContext::getUser() ?? UserContext::getCurrentUser();
$company = $user['company'] ?? [];
$model = $event->getModel();
// 判断事件类型是否符合条件,以及用户上下文是否存在
if (!($event instanceof Creating || $event instanceof Saving) || !$user) {
return;
}
$schema = $model->getConnection()->getSchemaBuilder();
// 检查模型表是否有company_id字段若有则设置company_id
if ($schema->hasColumn($model->getTable(), 'company_id')) {
$model->company_id = $model->company_id ?? $company['id'] ?? 0;
}
// 检查模型表是否有creator_id和creator_name字段若有则设置对应的值
if ($schema->hasColumn($model->getTable(), 'creator_id')) {
$model->creator_id ??= $user['id'];
$model->creator_name ??= $user['name'] ?? '';
}
}
}