Skip to content

Dynamic binding gates #158

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

15g-lucas
Copy link
Member

@15g-lucas 15g-lucas commented Mar 26, 2025

closes #156

The purpose of this PR is to automatically bind all the gates of a model (before, only the view, viewAny, delete, restore... methods were available).

It will therefore be possible to add a new authorization (e.g. whether or not the user has the right to download the resource).

What's more, if the gate doesn't have a name in the configuration file, I've made sure to generate one automatically.

It would be a good idea to update the documentation to explain this.

I look forward to your feedback on this feature :)

Summary by CodeRabbit

  • Refactor
    • Improved and streamlined the application’s permission handling, enhancing flexibility and responsiveness.
    • Updated method signatures for improved clarity and functionality.
    • Enhanced validation rules by dynamically retrieving valid gate methods from the associated policy, replacing the previous hardcoded list.

Copy link
Contributor

coderabbitai bot commented Mar 26, 2025

Walkthrough

The pull request refactors the authorization logic in two key areas. In the Response class, the buildGatesForModel method is simplified by replacing multiple conditional checks with a streamlined approach using array_combine and array_map. In the SearchRules class, the static list of valid gate methods in the validate method has been replaced by dynamically retrieving and filtering the policy methods from the Gate facade. These changes maintain the core authorization behavior while making the code more concise and adaptable.

Changes

File(s) Change Summary
src/Http/Response.php Refactored buildGatesForModel to use array_combine and array_map, replacing multiple conditional checks with a concise mapping approach.
src/Rules/SearchRules.php Modified the validate method to dynamically generate the list of valid gates from the model's policy via Gate::getPolicyFor, replacing the previous static list.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Response
    Caller->>Response: buildGatesForModel(gates)
    Response->>Response: Map each gate using array_map & array_combine
    Response-->>Caller: Return authorization array
Loading
sequenceDiagram
    participant Client
    participant SearchRules
    participant GateFacade
    Client->>SearchRules: validate(input)
    SearchRules->>GateFacade: getPolicyFor(resource::$model)
    GateFacade-->>SearchRules: Return policy object
    SearchRules->>SearchRules: Filter policy methods (exclude before, after, __call, __construct)
    SearchRules-->>Client: Return dynamic validation rules with valid gates
Loading

Assessment against linked issues

Objective Addressed Explanation
Customize Gate in request (#156)

Poem

I'm a bunny hopping through the code,
Skipping conditionals down the road,
Arrays now map with graceful art,
Gates dynamically crafted smart,
With every hop, a cleaner node! 🐇💻


📜 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 4a0b5e1 and b605fd3.

📒 Files selected for processing (1)
  • src/Http/Response.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Http/Response.php

🪧 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 0

🧹 Nitpick comments (2)
src/Http/Response.php (1)

35-38: Cleaner implementation of gate binding with dynamic naming!

The refactored implementation elegantly handles dynamic gate binding using array functions. This approach is more maintainable than the previous version and supports custom gate names via configuration.

Consider adding a null check in case $gates is empty to avoid potential errors:

 protected function buildGatesForModel(Model $model, Resource $resource, array $gates)
 {
+    if (empty($gates)) {
+        return [];
+    }
     return array_combine(
         array_map(fn($gate) => config("rest.gates.names.authorized_to_{$gate}", "authorized_to_{$gate}"), $gates),
         array_map(fn($gate) => $resource->authorizedTo($gate, $model), $gates)
     );
 }
src/Rules/SearchRules.php (1)

72-74: Great implementation of dynamic gate discovery!

This approach dynamically fetches all available policy methods, making the authorization system more flexible and maintainable. New gates will be automatically recognized without code changes.

Consider extracting this logic to a helper method for reusability and improved readability:

+    /**
+     * Get valid gates from the resource policy.
+     *
+     * @return array
+     */
+    protected function getValidGatesFromPolicy(): array
+    {
+        $policy = Gate::getPolicyFor($this->resource::$model);
+        if (!$policy) {
+            return [];
+        }
+        
+        return array_filter(
+            get_class_methods($policy), 
+            fn($method) => !in_array($method, ['before', 'after', '__call', '__construct'])
+        );
+    }

     public function validate(string $attribute, mixed $value, Closure $fail): void
     {
         if ($attribute !== '') {
             $attribute .= '.';
         }

-        $policy = Gate::getPolicyFor($this->resource::$model);
-        $validGates = $policy ? get_class_methods($policy) : [];
-        $validGates = array_filter($validGates, fn($method) => !in_array($method, ['before', 'after', '__call', '__construct']));
+        $validGates = $this->getValidGatesFromPolicy();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d6141f9 and ed74e0a.

📒 Files selected for processing (2)
  • src/Http/Response.php (1 hunks)
  • src/Rules/SearchRules.php (3 hunks)
🔇 Additional comments (2)
src/Rules/SearchRules.php (2)

12-12: New Gate facade import supports dynamic policy discovery.

This import is necessary for the dynamic policy and gate retrieval implemented below.


97-97:

✅ Verification successful

Dynamic validation rule for gates enhances flexibility.

Using the dynamically generated $validGates array instead of a hardcoded list makes the system more flexible and future-proof. New gates will be automatically validated without requiring code changes.

Let's check for any potentially missed gates by comparing this dynamic approach with the previous hardcoded approach:


🏁 Script executed:

#!/bin/bash
# Find any references to hardcoded gate lists in the codebase
echo "Looking for hardcoded gate lists that might need updating..."
rg -A 2 -B 2 "viewAny|forceDelete" --type php | grep -v "/vendor/"

Length of output: 14615


Dynamic validation rule verified – no additional issues detected

The dynamic approach using $validGates has been confirmed to properly encompass the gate values referenced throughout the codebase. The search for hardcoded gate lists (particularly those containing names like "forceDelete", "restore", "view", etc.) did not reveal any overlooked, hardcoded values. This confirms that new gates will be automatically supported without further code changes.

@GautierDele
Copy link
Member

The idea seems really nice but the tests aren't passing 😄

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.

Customize Gate in request
2 participants