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

Added logic to LanguageController for supporting Relation::morphMap([...]) #6

Merged
merged 3 commits into from
Nov 21, 2024

Conversation

kerwin-wildsea
Copy link
Contributor

@kerwin-wildsea kerwin-wildsea commented Nov 19, 2024

This PR includes a minor addition which allows the package to be used when a MorphMap is used on a model with InteractsWithLanguages.

I've chosen to use the already existing syntax of app($request->get('model')). So no other logic had to be changed.

That being said, if you prefer to have it as variable (i.e. $model = app($request->get('model'))) because it is now repeated four times in the controller, I don't mind changing it.

Summary by CodeRabbit

  • New Features

    • Enhanced language switching functionality with dynamic model handling.
  • Tests

    • Added a new test case for switching languages using morphMap functionality.

Copy link

coderabbitai bot commented Nov 19, 2024

Walkthrough

The changes involve modifications to the LanguageController class and the addition of a new test case in the LanguageSwitcherTest.php file. In the controller, the handling of the model_type attribute is updated to utilize the morph class dynamically instead of a static model string, affecting both record retrieval and creation. The test file introduces a new test case to validate language switching functionality using Laravel's morphMap, alongside an updated import statement to support this feature.

Changes

File Change Summary
src/Http/Controllers/LanguageController.php Updated index method to use getMorphClass() for model_type in both querying and creating records.
tests/src/LanguageSwitcherTest.php Added a new test case for language switching with morphMap; included an import statement for Relation.

Poem

In the code where rabbits hop,
Morph classes help us never stop.
With languages that switch with ease,
Our polymorphic hearts are sure to please!
Hooray for changes, big and small,
In the land of code, we celebrate all! 🐇✨


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.

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: 0

🧹 Outside diff range and nitpick comments (4)
src/Http/Controllers/LanguageController.php (2)

Line range hint 21-40: Optimize model instantiation to improve performance.

The code instantiates the same model multiple times using app($request->get('model')). This is inefficient and violates the DRY principle.

Consider refactoring to store the model instance in a variable:

     if (Schema::hasColumn(app($request->get('model'))->getTable(), 'lang')) {
-        $model = app($request->get('model'))->find($request->get('model_id'));
+        $modelClass = app($request->get('model'));
+        $model = $modelClass->find($request->get('model_id'));
         $model->lang = $request->get('lang');
         $model->save();
     } else {
+        $modelClass = app($request->get('model'));
+        $morphClass = $modelClass->getMorphClass();
         $lang = UserLanguage::query()
-            ->where('model_type', app($request->get('model'))->getMorphClass())
+            ->where('model_type', $morphClass)
             ->where('model_id', $request->get('model_id'))
             ->first();

         if ($lang) {
             $lang->lang = $request->get('lang');
             $lang->save();
         } else {
             UserLanguage::query()->create([
-                'model_type' => app($request->get('model'))->getMorphClass(),
+                'model_type' => $morphClass,
                 'model_id' => $request->get('model_id'),
                 'lang' => $request->get('lang'),
             ]);
         }
     }

Line range hint 21-22: Add error handling for invalid model class.

The code doesn't validate if the provided model class exists before attempting to instantiate it with app(). This could lead to uncaught exceptions.

Consider adding validation:

+    try {
+        $modelClass = app($request->get('model'));
+    } catch (\Throwable $e) {
+        Notification::make()
+            ->title('Invalid model class provided')
+            ->icon('heroicon-o-x-circle')
+            ->iconColor('danger')
+            ->send();
+        return back();
+    }
+
     if (Schema::hasColumn(app($request->get('model'))->getTable(), 'lang')) {
tests/src/LanguageSwitcherTest.php (2)

65-81: Consider reducing test duplication through shared setup

While the test implementation is correct, there's significant code duplication with the 'can switch language to ar' test. Consider extracting the common test logic into a shared function or data provider.

Example refactor:

function assertLanguageSwitch($lang, $useMorphMap = false) {
    if ($useMorphMap) {
        Relation::morphMap(['user' => get_class(auth()->user())]);
    }
    
    $response = get(route('languages.switcher', [
        'model' => get_class(auth()->user()),
        'model_id' => auth()->user()->id,
        'lang' => $lang,
    ]));

    $response->assertStatus(302);
    expect(auth('web')->user()->lang)->toBe($lang);
}

it('can switch language to ar', fn() => assertLanguageSwitch('ar'));
it('can switch language with morphMap', fn() => assertLanguageSwitch('ar', true));

69-73: Inconsistent auth guard usage

The test uses auth()->user() for retrieving the model and ID, but auth('web')->user() for verifying the language. Consider using consistent auth guard access throughout the test.

-    'model' => get_class(auth()->user()),
-    'model_id' => auth()->user()->id,
+    'model' => get_class(auth('web')->user()),
+    'model_id' => auth('web')->user()->id,

Also applies to: 78-78

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 53517a7 and 4f41db0.

📒 Files selected for processing (2)
  • src/Http/Controllers/LanguageController.php (2 hunks)
  • tests/src/LanguageSwitcherTest.php (2 hunks)
🔇 Additional comments (2)
src/Http/Controllers/LanguageController.php (1)

27-27: LGTM! Proper implementation of morphMap support.

The changes correctly implement support for morphMap by using getMorphClass() instead of the raw model string. This ensures proper polymorphic relationship mapping when models use Laravel's morphMap feature.

Also applies to: 36-36

tests/src/LanguageSwitcherTest.php (1)

3-3: LGTM! Import statement is correctly added

The import for Relation class is necessary for the new morphMap functionality being tested.

@3x1io 3x1io merged commit a40b786 into tomatophp:master Nov 21, 2024
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants