73 lines
2.2 KiB
PHP
Executable File
73 lines
2.2 KiB
PHP
Executable File
<?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'] ?? '';
|
||
}
|
||
}
|
||
}
|