Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 支持插件生成模型文件到插件目录下 #479

Closed
wants to merge 1 commit into from

Conversation

gladtoeatu
Copy link
Contributor

@gladtoeatu gladtoeatu commented Nov 28, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new command for generating model files for plugins in Hyperf applications, enhancing plugin development efficiency.
    • Added options for specifying plugin names when creating models.
  • Bug Fixes

    • Improved error handling for cases where plugin names or columns are not provided.

@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 28, 2024
Copy link

coderabbitai bot commented Nov 28, 2024

Walkthrough

The changes introduce a new command class PluginGenModelCommand within the Hyperf application framework. This command facilitates the generation of model files for plugins, extending the existing ModelCommand class. It includes methods for handling model creation, error checking for plugin names, and managing file paths and namespaces. The command is registered as plugin:gen:model, allowing users to specify the plugin name and generate corresponding model classes based on the database schema.

Changes

File Change Summary
app/Command/PluginGenModelCommand.php - Added class PluginGenModelCommand
- Implemented constructor and several methods for model generation, including createModel, getPathByPluginName, getPluginModelClass, getPathWithExtension, and getPluginNamespace.

Poem

In the land of code where rabbits play,
A new command hops in to save the day.
Models for plugins, quick as a flash,
With paths and namespaces, they’ll surely dash!
So gather your plugins, let’s generate,
With plugin:gen:model, it’s never too late! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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 anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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 the enhancement label Nov 28, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
app/Command/PluginGenModelCommand.php (1)

47-170: Ensure consistent language in error messages

The error messages are a mix of Chinese and English (e.g., '插件名称不能为空', 'Invalid plugin config'). For better consistency and maintainability, consider using the same language throughout all error messages.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 666fd46 and e6e761c.

📒 Files selected for processing (1)
  • app/Command/PluginGenModelCommand.php (1 hunks)

Comment on lines +58 to +62
if (empty($columns)) {
$this->output?->error(
sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle the case when columns are empty by exiting the method or throwing an exception

When no columns are found in the table, you output an error message but continue execution. If the intention is to stop processing when no columns are found, consider returning early or throwing an exception to prevent unnecessary execution.

Apply this diff to return early after the error message:

if (empty($columns)) {
    $this->output?->error(
        sprintf('Query columns empty, maybe table `%s` does not exist. You can check it in the database.', $table)
    );
+   return;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (empty($columns)) {
$this->output?->error(
sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
);
}
if (empty($columns)) {
$this->output?->error(
sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
);
return;
}

Comment on lines +110 to +113
if (! is_file($jsonPath)) {
$this->output?->error('插件缺少配置文件');
exit();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using exit() inside methods; use exceptions or return statements instead

Consistently using exit() within methods can lead to abrupt termination of the script. It's better practice to throw an exception or handle errors in a way that can be managed by the calling code.

Apply this diff to replace exit() with throwing an exception:

if (! is_file($jsonPath)) {
    $this->output?->error('插件缺少配置文件');
-   exit();
+   throw new RuntimeException('插件缺少配置文件');
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +46 to +49
if (! $this->input->getOption('plugin')) {
$this->output?->error('插件名称不能为空');
exit();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using exit() inside methods; use exceptions or return statements instead

Using exit() within a method can abruptly terminate the entire script, which is generally discouraged in object-oriented programming. It's better to throw an exception or return early to allow the application to handle the error gracefully.

Apply this diff to replace exit() with throwing an exception:

if (! $this->input->getOption('plugin')) {
    $this->output?->error('插件名称不能为空');
-   exit();
+   throw new RuntimeException('插件名称不能为空');
}

Committable suggestion skipped: line range outside the PR's diff.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (4)
app/Command/PluginGenModelCommand.php (4)

131-135: Add type hinting to method parameters for clarity and type safety

The method getPluginModelClass does not specify the type of the $class parameter. Adding a type declaration improves code readability and helps prevent type-related errors.

Modify the method signature:

- private function getPluginModelClass($class): string
+ private function getPluginModelClass(string $class): string

153-154: Correct the DocBlock formatting for proper documentation parsing

The closing */ of the DocBlock is misplaced, which can cause issues with documentation tools and IDE parsing.

Adjust the DocBlock:

  * @return string
- * @noinspection PhpSameParameterValueInspection*/
+ * @noinspection PhpSameParameterValueInspection
+ */

60-61: Improve error message grammar for better comprehension

The error message contains grammatical errors that could confuse users. Refining the message enhances clarity.

Revise the error message:

 sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
+sprintf('Query columns are empty. Maybe the table `%s` does not exist. You can check it in the database.', $table)

167-181: Simplify and ensure correctness in path manipulation logic

The method getPluginNamespace has complex logic that could be simplified for better readability and maintenance. Ensuring the correctness of path handling is crucial, especially when dealing with file systems.

Consider refactoring the method to make the path manipulation clearer and more robust. For example:

-$ext = pathinfo($path, PATHINFO_EXTENSION);

-if ($ext !== '') {
-    $path = substr($path, 0, -(strlen($ext) + 1));
-} else {
-    $path = trim($path, '/') . '/';
-}

-return str_replace('/', '\\', $path);
+$path = rtrim(str_replace('/', '\\', $path), '\\') . '\\';
+return $path;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 666fd46 and e6e761c.

📒 Files selected for processing (1)
  • app/Command/PluginGenModelCommand.php (1 hunks)

Comment on lines +118 to +122
foreach ($psrArray as $value => $key) {
if ($key === 'src') {
$this->pluginModelNamespace = $value . 'Model';
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the foreach loop variable names to properly extract namespace and path

In the foreach loop, the variables $value and $key are reversed, leading to incorrect assignment of the namespace. The correct structure should have $key as the namespace and $value as the path.

Update the loop:

-foreach ($psrArray as $value => $key) {
-    if ($key === 'src') {
-        $this->pluginModelNamespace = $value . 'Model';
+foreach ($psrArray as $namespace => $path) {
+    if ($path === 'src') {
+        $this->pluginModelNamespace = $namespace . 'Model';
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
foreach ($psrArray as $value => $key) {
if ($key === 'src') {
$this->pluginModelNamespace = $value . 'Model';
}
}
foreach ($psrArray as $namespace => $path) {
if ($path === 'src') {
$this->pluginModelNamespace = $namespace . 'Model';
}
}

Comment on lines +111 to +112
$this->output?->error('插件缺少配置文件');
exit();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace exit() with an exception for consistent error handling

Similar to previous instances, using exit() is not recommended. Throwing an exception ensures the error can be caught and managed appropriately.

Change the code to:

 if (! is_file($jsonPath)) {
     $this->output?->error('插件缺少配置文件');
-    exit();
+    throw new RuntimeException('插件缺少配置文件');
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +46 to +49
if (! $this->input->getOption('plugin')) {
$this->output?->error('插件名称不能为空');
exit();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using exit(); throw an exception for better error handling

Using exit() within methods is discouraged as it abruptly ends script execution and can lead to unexpected behavior. Instead, throwing an exception allows for proper error handling and keeps the application flow manageable.

Consider modifying the code as follows:

 if (! $this->input->getOption('plugin')) {
     $this->output?->error('插件名称不能为空');
-    exit();
+    throw new RuntimeException('插件名称不能为空');
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (! $this->input->getOption('plugin')) {
$this->output?->error('插件名称不能为空');
exit();
}
if (! $this->input->getOption('plugin')) {
$this->output?->error('插件名称不能为空');
throw new RuntimeException('插件名称不能为空');
}

Comment on lines +58 to +62
if (empty($columns)) {
$this->output?->error(
sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add return or throw an exception after error message to prevent unintended execution

After displaying the error message when columns are empty, the method continues execution, which may cause further errors. You should halt execution by returning early or throwing an exception.

Suggested fix:

 if (empty($columns)) {
     $this->output?->error(
         sprintf('Query columns empty. Maybe the table `%s` does not exist. You can check it in the database.', $table)
     );
+    return;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (empty($columns)) {
$this->output?->error(
sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
);
}
if (empty($columns)) {
$this->output?->error(
sprintf('Query columns empty, maybe is table `%s` does not exist.You can check it in database.', $table)
);
return;
}

Comment on lines +115 to +117
$jsonArray = json_decode(file_get_contents($jsonPath), true);
$psrArray = $jsonArray['composer']['psr-4'];

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate JSON structure before accessing nested keys to prevent errors

Accessing $jsonArray['composer']['psr-4'] without checking if these keys exist can lead to undefined index errors. Ensure the JSON structure contains the expected keys.

Implement validation:

+$composerConfig = $jsonArray['composer'] ?? null;
+if (!$composerConfig || !isset($composerConfig['psr-4'])) {
+    throw new RuntimeException('Invalid composer configuration in plugin JSON.');
+}
-$psrArray = $jsonArray['composer']['psr-4'];
+$psrArray = $composerConfig['psr-4'];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$jsonArray = json_decode(file_get_contents($jsonPath), true);
$psrArray = $jsonArray['composer']['psr-4'];
$jsonArray = json_decode(file_get_contents($jsonPath), true);
$composerConfig = $jsonArray['composer'] ?? null;
if (!$composerConfig || !isset($composerConfig['psr-4'])) {
throw new RuntimeException('Invalid composer configuration in plugin JSON.');
}
$psrArray = $composerConfig['psr-4'];

@zds-s
Copy link
Member

zds-s commented Nov 28, 2024

  1. 插件生态的东西应该提到 https://github.com/mineadmin/appstore
  2. 模型生成、hyperf 官方已经很完善了。可以指定 path 和 namespace

@zds-s zds-s closed this Dec 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants