* * 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'] ?? ''; } } }