Skip to content

Conversation

@GautierDele
Copy link
Member

@GautierDele GautierDele commented Apr 24, 2025

closes #15
closes #16

Summary by CodeRabbit

  • Bug Fixes

    • Corrected the registration of stub files to ensure the correct alias is used for control stubs.
    • Updated policy logic to use the appropriate method for permission checks.
  • Refactor

    • Improved the logic for resolving control names by checking for a static control method on the model.
    • Removed unused import statements from stub files and cleaned up comments.
  • Tests

    • Added comprehensive tests to verify policy authorization methods and stub registration.
    • Updated test models and policies to better align with the new control resolution logic.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 24, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces several targeted changes across the codebase. Stub file aliasing is corrected to match actual filenames, and unused import statements are removed from stub files. In the core logic, the resolveControlName method in the Control class now checks for a static control method on the model before falling back to conventional resolution. All policy authorization methods are updated to use the applies method instead of should. Additionally, new feature tests are added to verify policy method invocations, and test support classes are adjusted to align with these changes.

Changes

File(s) Change Summary
src/AccessServiceProvider.php, tests/Unit/StubsTest.php Corrected stub alias registration from 'controller.stub' to 'control.stub' and updated corresponding test.
src/Console/stubs/control.stub
src/Console/stubs/perimeter.overlay.stub
src/Console/stubs/perimeter.plain.stub
Removed unused import statements for the base controller class from stub files.
src/Console/ControlMakeCommand.php
src/Console/PerimeterMakeCommand.php
Removed a redundant docblock comment from the buildClass method.
src/Controls/Control.php Modified resolveControlName to check for a static control method on the model before using fallback logic.
src/Policies/ControlledPolicy.php Replaced all calls to should with applies in policy authorization methods.
tests/Feature/PoliciesTest.php Added new feature tests for all standard policy methods to verify correct method invocation and expected results.
tests/Support/Models/Model.php Added a public static $control property referencing ModelControl to the Model class.
tests/Support/Policies/ModelPolicy.php Changed import to use the custom Model class from test support instead of Eloquent's base model.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Policy
    participant Control
    participant Model

    User->>Policy: Calls policy method (e.g., view, create)
    Policy->>Control: Calls applies()
    Control->>Model: Checks for static control() method
    alt control() exists
        Model-->>Control: Returns custom control class
    else control() does not exist
        Control->>Control: Uses fallback logic to resolve control class
    end
    Control-->>Policy: Returns authorization result
    Policy-->>User: Returns true/false
Loading

Assessment against linked issues

Objective Addressed Explanation
Correct stub alias registration to match actual stub filename (#15)
Update test assertions to reflect corrected stub filename (#15)
Replace calls to should with applies in ControlledPolicy authorization methods (#16)

Possibly related PRs

  • Lomkit/laravel-access-control#10: Introduced initial command registration and stub publishing setup, including the addition of stub files; the current PR corrects and builds upon this setup.

Poem

In the warren of code, a fix hops through,
Stub names aligned, old imports bid adieu.
Controls now peek for a method so sly,
Policies ask "applies"—no longer just "should I?"
Tests multiply, ensuring all is right,
As rabbits rejoice in the soft morning light.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b69e9c9 and da7a0e7.

📒 Files selected for processing (1)
  • tests/Feature/PoliciesTest.php (1 hunks)
✨ 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.
    • 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 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 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
Contributor

@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: 1

🧹 Nitpick comments (2)
tests/Feature/PoliciesTest.php (2)

91-103: Fix typo in test method name

There's a typo in the test method name: test_policies_calls_force_delete_methoforceDeleted_properly should likely be test_policies_calls_force_delete_method_properly.

Otherwise, the test correctly verifies the forceDelete policy method.

-    public function test_policies_calls_force_delete_methoforceDeleted_properly(): void
+    public function test_policies_calls_force_delete_method_properly(): void

1-104: Consider adding negative test cases

The current tests verify that policy methods return true when Gates are defined to return true. Consider adding negative test cases where Gates return false to ensure the full policy behavior is tested.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd5890b and b69e9c9.

📒 Files selected for processing (12)
  • src/AccessServiceProvider.php (1 hunks)
  • src/Console/ControlMakeCommand.php (0 hunks)
  • src/Console/PerimeterMakeCommand.php (0 hunks)
  • src/Console/stubs/control.stub (0 hunks)
  • src/Console/stubs/perimeter.overlay.stub (0 hunks)
  • src/Console/stubs/perimeter.plain.stub (0 hunks)
  • src/Controls/Control.php (1 hunks)
  • src/Policies/ControlledPolicy.php (7 hunks)
  • tests/Feature/PoliciesTest.php (1 hunks)
  • tests/Support/Models/Model.php (2 hunks)
  • tests/Support/Policies/ModelPolicy.php (1 hunks)
  • tests/Unit/StubsTest.php (1 hunks)
💤 Files with no reviewable changes (5)
  • src/Console/stubs/perimeter.plain.stub
  • src/Console/PerimeterMakeCommand.php
  • src/Console/ControlMakeCommand.php
  • src/Console/stubs/perimeter.overlay.stub
  • src/Console/stubs/control.stub
🧰 Additional context used
🧬 Code Graph Analysis (4)
tests/Support/Policies/ModelPolicy.php (1)
tests/Support/Models/Model.php (1)
  • Model (12-43)
src/Controls/Control.php (1)
src/Controls/HasControl.php (1)
  • control (22-27)
src/Policies/ControlledPolicy.php (1)
src/Controls/Control.php (1)
  • applies (49-68)
tests/Feature/PoliciesTest.php (4)
tests/Support/Models/Model.php (1)
  • Model (12-43)
tests/Support/Models/User.php (1)
  • User (10-64)
tests/Support/Policies/ModelPolicy.php (1)
  • ModelPolicy (8-11)
src/Policies/ControlledPolicy.php (7)
  • view (59-62)
  • viewAny (46-49)
  • create (71-74)
  • update (84-87)
  • delete (97-100)
  • restore (110-113)
  • forceDelete (123-126)
🔇 Additional comments (18)
src/AccessServiceProvider.php (1)

89-89: Corrected stub file registration alias.

The change fixes the stub file alias from 'controller.stub' to 'control.stub', ensuring that the alias matches the actual filename being published. This correction aligns the registration with the actual stub file path and provides consistency in the stub naming convention.

tests/Unit/StubsTest.php (1)

15-15: Updated test expectation to match corrected stub alias.

This change aligns with the fix in AccessServiceProvider.php, ensuring that the test correctly verifies that the control stub is properly registered with its matching alias. The test expectation now correctly matches the implementation.

tests/Support/Policies/ModelPolicy.php (1)

6-6: Updated Model import to use custom test Model.

The import change properly connects the policy to the custom test Model class instead of Laravel's base Model. This change aligns with the enhancement of the control-based authorization system where the Model now has an explicit reference to its control class.

tests/Support/Models/Model.php (2)

9-9: Added import for ModelControl class.

Properly imports the ModelControl class needed for the static control property.


18-19: Added explicit control class reference.

This addition establishes a direct link between the Model and its corresponding Control class through a static property. This supports the updated control resolution logic that checks for a static control property or method on the model class before falling back to conventional resolution.

src/Policies/ControlledPolicy.php (7)

48-48: Method name changed from 'should' to 'applies'

The policy method now uses applies instead of should method on the Control instance. This change is consistent with the new method name in the Control class that evaluates whether a control applies to a user and model.


61-61: Method name changed from 'should' to 'applies'

Correctly updated to use the applies method for the view policy.


73-73: Method name changed from 'should' to 'applies'

Correctly updated to use the applies method for the create policy.


86-86: Method name changed from 'should' to 'applies'

Correctly updated to use the applies method for the update policy.


99-99: Method name changed from 'should' to 'applies'

Correctly updated to use the applies method for the delete policy.


112-112: Method name changed from 'should' to 'applies'

Correctly updated to use the applies method for the restore policy.


125-125: Method name changed from 'should' to 'applies'

Correctly updated to use the applies method for the forceDelete policy.

tests/Feature/PoliciesTest.php (6)

11-23: Test verifies 'view' policy method properly

Great test for verifying the view policy method. The test creates a model, gets the current user, instantiates the policy, and verifies the expected result.


25-35: Test verifies 'viewAny' policy method properly

Good test for the viewAny policy method. This is an important test as it verifies proper handling of policies that don't require a specific model instance.


37-47: Test verifies 'create' policy method properly

The test correctly verifies that the create policy method functions as expected.


49-61: Test verifies 'update' policy method properly

Good test for the update policy method. The test appropriately creates a model instance for testing.


63-75: Test verifies 'delete' policy method properly

This test properly verifies the delete policy function.


77-89: Test verifies 'restore' policy method properly

This test properly verifies the restore policy function.

Comment on lines +237 to +242
// @TODO: The auto guess here is strange, we specify the models / controls everywhere, is there a better way of doing this ? (In policies guess the model as Laravel is doing ?)
// @TODO: Discussed with Lucas G

if (method_exists($modelName, 'control')) {
return $modelName::control()::class;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Enhanced control resolution by checking for static control method

Good enhancement! The resolveControlName method now checks if the model class has a static control method and uses it if available, before falling back to the conventional naming resolution.

However, the TODO comments suggest there are concerns about the auto-guessing approach. Consider addressing these TODOs before finalizing this PR or creating follow-up tickets to track these concerns.


🏁 Script executed:

#!/bin/bash
# Check if any models in the codebase implement the static control method
echo "Looking for models that implement static control method..."
rg -l "public static function control\(" --type php

Length of output: 208


🏁 Script executed:

#!/bin/bash
# Inspect the HasControl trait definition
echo "Inspecting HasControl trait:"
rg -Hn "trait HasControl" --type php

# List all references to HasControl to see where it's used
echo "Listing all references to HasControl:"
rg -Hn "HasControl" --type php

Length of output: 677


🏁 Script executed:

#!/bin/bash
# Check for any control() method definitions in HasControl trait
echo "Inspecting HasControl trait for control() methods:"
rg -Hn "function control" -C3 src/Controls/HasControl.php

Length of output: 589


Resolve TODOs for auto-guess behavior in resolveControlName

We’ve confirmed that no application models override the static control() method (only the HasControl trait provides it), so the fallback “auto guess” path remains lightly tested and the TODO comments at lines 237–242 still stand:

// @TODO: The auto guess here is strange, we specify the models / controls everywhere, is there a better way of doing this ? (In policies guess the model as Laravel is doing ?)
// @TODO: Discussed with Lucas G

if (method_exists($modelName, 'control')) {
    return $modelName::control()::class;
}

Please address these by one of the following:

  • Implement a more robust naming strategy (e.g., Laravel‐style policy guessing).
  • Remove or resolve the lingering TODOs.
  • If it’s out of scope for this PR, convert them into tracked tickets for follow-up.

@GautierDele GautierDele merged commit 5212205 into master Apr 24, 2025
20 of 21 checks passed
@GautierDele GautierDele deleted the fix/control-calls branch April 24, 2025 18:37
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.

3 participants