Skip to content

feat(user): enhance user service with caching and refactor menu filtering logic#655

Merged
zds-s merged 2 commits into
masterfrom
patch-menus
Jul 19, 2025
Merged

feat(user): enhance user service with caching and refactor menu filtering logic#655
zds-s merged 2 commits into
masterfrom
patch-menus

Conversation

@zds-s

@zds-s zds-s commented Jul 19, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • 新功能

    • 用户信息查询现已支持缓存,提升了重复请求时的响应速度。
  • 重构

    • 优化了当前用户菜单的生成方式,提升了菜单加载的效率和层级结构展示的准确性。
  • 测试

    • 增加了密码更新测试中的缓存清理和令牌刷新,确保测试环境状态准确。
    • 测试中密码获取逻辑统一,支持动态密码配置。

@coderabbitai

coderabbitai Bot commented Jul 19, 2025

Copy link
Copy Markdown
📝 Walkthrough

"""

Walkthrough

本次变更主要对用户菜单过滤和用户信息获取逻辑进行了重构和优化。CurrentUser 类的菜单过滤方法去除了递归和参数,改为基于权限直接构建菜单树;UserService 增加了缓存机制,减少对用户信息的重复查询。测试中对密码获取和缓存失效进行了调整。

Changes

文件/区域 变更摘要
app/Http/CurrentUser.php 重构 filterCurrentUser,移除递归和参数,直接基于权限构建菜单树;删除 globalMenuTreeListfilterMenu 方法;构造函数注入 MenuService
app/Service/Permission/UserService.php 构造函数新增 CacheInterface 依赖;getInfo 方法增加缓存逻辑,优先从缓存获取用户信息。
tests/Feature/Admin/GetTokenTrait.php getToken 方法改用 getPassword 获取密码,新增 getPassword 方法,统一密码管理。
tests/Feature/Admin/PermissionControllerTest.php 测试中新增空菜单断言;密码更新后刷新用户并清理缓存;新增获取新 token 流程。

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CurrentUser
    participant MenuService

    User ->> CurrentUser: filterCurrentUser()
    CurrentUser ->> MenuService: getMenusByPermissions(permissions, status)
    MenuService -->> CurrentUser: 返回菜单列表
    CurrentUser ->> CurrentUser: 构建菜单树
    CurrentUser -->> User: 返回菜单树
Loading
sequenceDiagram
    actor Caller
    participant UserService
    participant Cache
    participant UserRepository

    Caller ->> UserService: getInfo(id)
    UserService ->> Cache: has(id)
    alt 缓存命中
        Cache -->> UserService: 返回用户数据
        UserService -->> Caller: 返回用户数据
    else 缓存未命中
        UserService ->> UserRepository: find(id)
        UserRepository -->> UserService: 返回用户数据
        UserService ->> Cache: set(id, 用户数据, 60秒)
        UserService -->> Caller: 返回用户数据
    end
Loading

Possibly related PRs

Suggested labels

size:L

Poem

🐇
代码轻盈跳跃新,
菜单树下不递归。
用户信息有缓存,
密码获取更灵活。
测试添步更严谨,
兔子欢跃庆更新,
代码世界更清新!

"""


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 42aed69 and 76ea161.

📒 Files selected for processing (3)
  • app/Http/CurrentUser.php (3 hunks)
  • tests/Feature/Admin/GetTokenTrait.php (1 hunks)
  • tests/Feature/Admin/PermissionControllerTest.php (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
app/Http/CurrentUser.php (2)
app/Model/Permission/User.php (2)
  • User (45-139)
  • getPermissions (130-133)
app/Service/Permission/MenuService.php (1)
  • MenuService (22-95)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
  • GitHub Check: Test on PHP8.1 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.3 Swoole-v6.0.2
  • GitHub Check: Test on PHP8.2 Swow-develop
  • GitHub Check: Test on PHP8.3 Swow-develop
  • GitHub Check: Test on PHP8.1 Swoole-master
  • GitHub Check: Test on PHP8.2 Swoole-master
  • GitHub Check: Test on PHP8.2 Swoole-v5.1.6
  • GitHub Check: Test on PHP8.1 Swoole-v6.0.2
  • GitHub Check: Test on PHP8.1 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.3 Swoole-v5.1.6
  • GitHub Check: Test on PHP8.2 Swoole-v6.0.2
  • GitHub Check: Test on PHP8.1 Swoole-v5.1.6
  • GitHub Check: Test on PHP8.3 Swoole-master
  • GitHub Check: Test on PHP8.2 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.3 Swoole-v6.0.2
  • GitHub Check: Test on PHP8.3 Swow-develop
  • GitHub Check: Test on PHP8.1 Swow-develop
  • GitHub Check: Test on PHP8.2 Swow-develop
  • GitHub Check: build Code coverage report (ubuntu-latest, 8.1, v5.1.3)
  • GitHub Check: build Code coverage report (ubuntu-latest, 8.1, v5.1.3)
🔇 Additional comments (10)
tests/Feature/Admin/GetTokenTrait.php (3)

38-38: 改进:使用动态密码获取

将硬编码密码替换为 getPassword() 方法调用,提高了测试的灵活性,允许在不同测试场景中使用不同的密码。


40-40: 格式改进:使用完全限定函数名

使用 \is_array 代替 is_array 提高了代码一致性,这是一个良好的实践。


49-55: 新增方法:灵活的密码获取逻辑

getPassword() 方法提供了良好的回退机制:如果类中存在 $password 属性则使用它,否则使用默认值 '123456'。这种设计支持在测试中动态指定密码,特别适用于密码更新测试场景。

tests/Feature/Admin/PermissionControllerTest.php (4)

22-24: 新增导入:支持缓存管理

添加了 ApplicationContextCacheInterface 的导入,为测试中的缓存操作提供支持。这与 UserService 中新增的缓存机制相对应。


43-43: 测试改进:验证空菜单数据

添加了对空菜单数据的断言,确保在用户没有菜单权限时返回空数组。这是对新的菜单过滤逻辑的有效测试。


119-119: 格式改进:增加空白行

在角色菜单同步后添加空白行,提高了代码的可读性。


231-241: 关键改进:缓存失效和令牌刷新

在密码更新测试中添加了重要的缓存管理逻辑:

  1. 用户刷新后显式删除缓存条目
  2. 重新获取令牌以确保使用新密码

这确保了测试在密码更新后使用最新状态,避免了缓存导致的测试失败。

app/Http/CurrentUser.php (3)

15-18: 导入更新:支持重构后的菜单逻辑

添加了 Status 枚举和 MenuService 的导入,为重构后的菜单过滤逻辑提供支持。


29-30: 构造函数更新:注入 MenuService

在构造函数中注入 MenuService 依赖,支持新的菜单获取逻辑。依赖注入的使用符合良好的设计模式。


53-81: 重大重构:简化菜单过滤逻辑

filterCurrentUser 方法进行了重大重构,显著简化了菜单过滤逻辑:

优点:

  • 移除了复杂的递归过滤逻辑
  • 直接通过 MenuService 查询具有用户权限的菜单
  • 使用更直观的数组操作构建菜单树
  • 代码更易理解和维护

实现逻辑:

  1. 获取用户权限名称的唯一集合
  2. 如果无权限则返回空数组
  3. 通过 MenuService 查询状态正常且匹配权限的菜单
  4. 构建菜单树:先建立 ID 映射,再根据 parent_id 建立层级关系

这种实现方式更加高效,避免了不必要的递归操作。

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or PR title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. enhancement labels Jul 19, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
app/Service/Permission/UserService.php (1)

44-53: 重置密码后需要清除缓存

当用户密码被重置时,应该清除相关的缓存以避免返回过期数据。

 public function resetPassword(?int $id): bool
 {
     if ($id === null) {
         return false;
     }
     $entity = $this->repository->findById($id);
     $entity->resetPassword();
     $entity->save();
+    // 清除用户缓存
+    $this->cache->delete('user:info:' . $id);
     return true;
 }
🧹 Nitpick comments (1)
app/Http/CurrentUser.php (1)

53-80: 菜单过滤逻辑重构得很好!

新的实现移除了递归,使用引用构建树形结构,性能更优。

建议考虑以下小优化:

  1. 添加用户空值检查:
 public function filterCurrentUser(): array
 {
+    $user = $this->user();
+    if ($user === null) {
+        return [];
+    }
-    $permissions = $this->user()
+    $permissions = $user
         ->getPermissions()
         ->pluck('name')
         ->unique()
         ->toArray();
  1. 可以考虑将树形结构构建逻辑提取为一个通用方法,便于其他地方复用。
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4139090 and 42aed69.

📒 Files selected for processing (2)
  • app/Http/CurrentUser.php (3 hunks)
  • app/Service/Permission/UserService.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
app/Service/Permission/UserService.php (3)
app/Model/Permission/User.php (1)
  • User (45-139)
app/Repository/IRepository.php (1)
  • findById (121-124)
app/Service/IService.php (1)
  • findById (75-78)
🔇 Additional comments (2)
app/Service/Permission/UserService.php (1)

28-32: 构造函数变更看起来不错!

依赖注入的实现正确,使用了只读属性。

app/Http/CurrentUser.php (1)

27-31: 构造函数更新正确!

MenuService 的依赖注入实现得当。

Comment thread app/Service/Permission/UserService.php
@zds-s
zds-s merged commit dc501ca into master Jul 19, 2025
37 checks passed
@zds-s
zds-s deleted the patch-menus branch July 19, 2025 11:13
@codecov

codecov Bot commented Jul 19, 2025

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 0.00%. Comparing base (4139090) to head (76ea161).
Report is 1 commits behind head on master.

Additional details and impacted files
@@      Coverage Diff      @@
##   master   #655   +/-   ##
=============================
=============================

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot mentioned this pull request Sep 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant