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

Add Limited Operators Support for Resource Filtering #155

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

Jo0kker
Copy link
Contributor

@Jo0kker Jo0kker commented Mar 19, 2025

Description

This PR adds the ability to limit available filtering operators in a REST resource. This allows restricting search operations to a specific set of operators for security or performance reasons.

Main Changes

  1. Added a new $operators property in the Resource class
  2. Added operator validation in the SearchRequest
  3. Added tests to verify the proper functioning of limited operators

Technical Details

  • The $operators property is defined as an array of allowed operators
  • If $operators is empty, all operators are allowed (default behavior)
  • Validation is performed in the SearchRequest before search execution
  • Tests cover use cases with both allowed and disallowed operators

Tests

Added two new tests in SearchFilteringOperationsTest.php:

  • test_getting_a_list_of_resources_filtered_by_limited_operators()
  • test_getting_a_list_of_resources_filtered_by_limited_operators_with_invalid_operator()

API Impact

This modification is backward compatible because:

  • Default behavior remains unchanged (all operators allowed)
  • Existing resources don't need to be modified
  • Operator validation is transparent to the end user

Usage Example

class LimitedModelResource extends Resource
{
    public static $operators = ['=', '!=', '>', '<'];
    
    // ... rest of configuration
}

resolve #154

Summary by CodeRabbit

  • New Features

    • Enhanced search filtering now dynamically computes valid query operators based on the current request context, offering more flexible and robust search capabilities.
    • A new resource route for 'limited-models' has been added, enabling handling of related requests through the RESTful interface.
  • Bug Fixes

    • Improved feedback is provided when an unsupported filtering operator is used, ensuring clearer error messaging and a smoother user experience.
  • Tests

    • Added new tests to validate filtering operations with both valid and invalid operators, ensuring correct functionality and error handling.

Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

Walkthrough

The changes introduce a new trait, Operatable, to manage and dynamically compute operator rules during REST requests. The trait is integrated into the main Resource class, replacing hardcoded operator lists in filtering logic within SearchRules. Additionally, new test cases validate resource filtering with both valid and invalid operators. New components for a limited model resource—including a dedicated controller, resource class, and API route—have been added to support a specific operator set. These updates enhance the flexibility of operator management and provide dedicated endpoints for limited model operations.

Changes

File(s) Change Summary
src/Concerns/Resource/Operatable.php
src/Http/Resource.php
Introduced new Operatable trait with methods operators and getOperators; integrated trait into the Resource class to manage operator computation.
src/Rules/SearchRules.php Updated filtersRules to replace hardcoded operator arrays with a dynamic call to getOperators on the Resource instance.
tests/Feature/Controllers/SearchFilteringOperationsTest.php Added two new test methods to validate resource filtering: one with a valid operator and one with an invalid operator, ensuring proper response handling.
tests/Support/Http/Controllers/LimitedModelController.php
tests/Support/Rest/Resources/LimitedModelResource.php
tests/Support/Routes/api.php
Added a new Limited Model endpoint: created a controller and resource class (with a custom operator implementation) and registered a corresponding API resource route.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Route
    participant Controller
    participant Resource
    participant SearchRules

    Client->>API_Route: Send REST filter request
    API_Route->>Controller: Route request to LimitedModelController
    Controller->>Resource: Invoke getOperators(request)
    Resource->>Resource: (Operatable trait) Compute operators
    Resource->>SearchRules: Supply operator list for filtering
    SearchRules->>Resource: Validate/filter using dynamic operators
    Resource->>Controller: Return filtered data
    Controller->>Client: Respond with filtered resource list
Loading

Poem

I'm a code bunny, bouncing with glee,
Hopping through traits and tests so free.
Operators line up like carrots in a row,
Filtering the data with a nimble flow.
With each new route and resource we pave,
I celebrate these changes – oh so brave!
🐇💻 Hop on, CodeRabbit!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 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 3fcbb53 and e7d7ce2.

📒 Files selected for processing (2)
  • src/Concerns/Resource/Operatable.php (1 hunks)
  • tests/Feature/Controllers/SearchFilteringOperationsTest.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Concerns/Resource/Operatable.php
🧰 Additional context used
🧬 Code Definitions (1)
tests/Feature/Controllers/SearchFilteringOperationsTest.php (3)
tests/Support/Rest/Resources/LimitedModelResource.php (1) (1)
  • LimitedModelResource (8-16)
tests/Support/Models/Model.php (1) (1)
  • Model (10-112)
tests/Support/Traits/InteractsWithResource.php (1) (1)
  • assertResourcePaginated (13-47)
🔇 Additional comments (3)
tests/Feature/Controllers/SearchFilteringOperationsTest.php (3)

13-13: Appropriate import added for LimitedModelResource

The import for LimitedModelResource is correctly added to support the new test cases.


631-655: Well-structured test for valid limited operators

This test correctly verifies that filtering works with an explicitly allowed operator (equality operator) when using a resource with limited operators. The test creates appropriate test data, makes the search request, and verifies the response using the existing assertResourcePaginated method.

The test connects well with the PR's objective to limit available filtering operators in REST resources.


657-678: Well-implemented validation test for invalid operators

This test correctly verifies that the system rejects requests with operators that aren't allowed by the limited resource. The test properly checks both the error status code (422) and the structure of the error response, ensuring that the error message specifically relates to the operator field.

The test effectively validates the error handling aspect of the limited operators feature, which is critical for security and API robustness.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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.

@GautierDele
Copy link
Member

The idea seems nice but this might need to think about what could be given because for "in" and "not in" i'm manually changing the query builder, why did you have this feature in mind ?

This might also be the time to refactor "PerformSearch" and put Objects to handle these but i'll do it on my side

@Jo0kker
Copy link
Contributor Author

Jo0kker commented Mar 28, 2025

I preserved the existing logic for operators like in and not in

I added the PR to handle the ilike operator for PostgreSQL to support case-insensitive searches. Following that, I extended the functionality to allow customization of operators, enabling users to add or remove operators as needed.

If you plan to refactor PerformSearch using objects, I can adapt my PR accordingly.

Let me know if you need any changes.

#154

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.

filters ilike with postgres db
2 participants