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

refactor: Dokan REST base controllers and docs #2544

Merged
merged 7 commits into from
Mar 4, 2025
Merged

Conversation

mrabbani
Copy link
Member

@mrabbani mrabbani commented Jan 29, 2025

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

  • Full PR Link

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

  • Documentation

    • Restructured Dokan REST Controllers documentation.
    • Added new "Table of Contents" section.
    • Updated implementation details for creating REST controllers.
    • Clarified controller hierarchy and naming conventions.
  • Refactor

    • Renamed REST controller classes.
    • Updated base controller inheritance.
    • Introduced new base controller classes with standardized methods.
    • Deprecated old REST controller implementations.
  • New Features

    • Added new methods for REST response preparation.
    • Enhanced error handling for invalid resource IDs.
    • Introduced VendorAuthorizable trait for vendor capability checks.

These changes improve the modularity and extensibility of Dokan's REST API architecture.

Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

Walkthrough

The pull request introduces a comprehensive restructuring of the Dokan REST API controllers. Key changes include renaming and refactoring existing abstract controller classes, introducing new base controllers for different user roles (admin, vendor, customer), and updating the documentation. The modifications aim to improve the modularity, extensibility, and clarity of the REST API implementation by providing more consistent base classes and clearer implementation guidelines.

Changes

File Change Summary
docs/api/api.md Restructured documentation with new ToC, updated controller naming, and revised implementation guidelines. Added new methods and error handling information.
includes/Abstracts/DokanRESTAdminController.php Updated to extend DokanBaseAdminController, added deprecation notice, removed specific properties and methods.
includes/Abstracts/DokanRESTBaseController.php Marked as deprecated, changed inheritance to DokanBaseController, removed previous properties and methods.
includes/Abstracts/DokanRESTCustomerController.php Updated to extend DokanBaseCustomerController, added deprecation notice, removed specific properties and methods.
includes/Abstracts/DokanRESTVendorController.php Updated to extend DokanBaseVendorController, added deprecation notice, removed specific properties and methods.
includes/REST/DokanBaseAdminController.php New base admin controller with namespace and permission check method.
includes/REST/DokanBaseController.php New base REST controller with collection response formatting.
includes/REST/DokanBaseCustomerController.php New base customer controller with login permission check.
includes/REST/DokanBaseVendorController.php New base vendor controller with vendor permission check.
includes/Traits/VendorAuthorizable.php New trait for vendor capability checks with permission method.

Suggested labels

Ready to Merge, :+1: Dev Review Done

Suggested reviewers

  • shohag121

Poem

🐰 Hop, hop, REST controllers dance!
Refactored code takes a new stance
Base classes shine, clean and bright
Modularity brings pure delight
Dokan's API, a rabbit's dream so neat! 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings

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

@mrabbani mrabbani self-assigned this Jan 29, 2025
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 (11)
includes/REST/DokanBaseAdminController.php (1)

8-8: Update version placeholder.

Replace DOKAN_SINCE with the actual version number.

includes/REST/DokanBaseVendorController.php (1)

8-8: Update version placeholders.

Replace DOKAN_SINCE with the actual version number in both the class and method documentation.

Also applies to: 24-24

includes/REST/DokanBaseCustomerController.php (3)

5-5: Remove unnecessary use statement.

The use WeDevs\Dokan\REST\DokanBaseController; statement is unnecessary since the class is in the same namespace.

-use WeDevs\Dokan\REST\DokanBaseController;

10-10: Update version placeholders.

Replace DOKAN_SINCE with the actual version number in both the class and method documentation.

Also applies to: 26-26


30-32: Consider additional customer validation.

The current permission check only verifies if a user is logged in. Consider adding validation for the 'customer' role or capabilities if needed.

 public function check_permission() {
-    return is_user_logged_in();
+    return is_user_logged_in() && current_user_can( 'customer' );
 }
includes/REST/DokanBaseController.php (2)

10-10: Replace DOKAN_SINCE placeholder with actual version number.

The @SInCE tag contains a placeholder that needs to be replaced with the actual version number where this class was introduced.


23-34: Fix parameter documentation inconsistency.

The method documentation doesn't match the implementation:

  • Parameter list shows $items but method uses $total_items
  • @since tag contains DOKAN_SINCE placeholder

Update the documentation to match the implementation:

     /**
      * Format item's collection for response
      *
      * @since DOKAN_SINCE
      *
      * @param object $response
      * @param object $request
-     * @param array  $items
      * @param int    $total_items
      *
      * @return object
      */
docs/api/api.md (4)

8-11: Consider renaming 'DokanBaseBaseController'.

The name 'DokanBaseBaseController' is redundant with double "Base". Consider renaming to 'DokanBaseController' to match the actual class name in the codebase.


15-39: Enhance implementation guidelines documentation.

The documentation should list all required methods that need to be implemented when extending the base controllers. Consider adding:

  • register_routes()
  • get_items()
  • get_item()
  • create_item()
  • update_item()
  • delete_item()

75-77: Use Dokan text domain for error messages.

The error message uses WooCommerce's text domain. Replace with Dokan's text domain:

-            return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), array( 'status' => 404 ) );
+            return new WP_Error( 'dokan_rest_invalid_id', __( 'Invalid resource ID.', 'dokan' ), array( 'status' => 404 ) );

91-91: Implement the TODO comment in the example.

The example contains a TODO comment for API response formatting. Consider implementing it to provide a complete example.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a12a17e and ce9d06e.

📒 Files selected for processing (9)
  • docs/api/api.md (2 hunks)
  • includes/Abstracts/DokanRESTAdminController.php (1 hunks)
  • includes/Abstracts/DokanRESTBaseController.php (1 hunks)
  • includes/Abstracts/DokanRESTCustomerController.php (1 hunks)
  • includes/Abstracts/DokanRESTVendorController.php (1 hunks)
  • includes/REST/DokanBaseAdminController.php (1 hunks)
  • includes/REST/DokanBaseController.php (1 hunks)
  • includes/REST/DokanBaseCustomerController.php (1 hunks)
  • includes/REST/DokanBaseVendorController.php (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: e2e tests (3, 3)
  • GitHub Check: e2e tests (2, 3)
  • GitHub Check: e2e tests (1, 3)
  • GitHub Check: api tests (1, 1)
🔇 Additional comments (18)
includes/Abstracts/DokanRESTAdminController.php (4)

5-5: Good use of the new base class.
Switching to DokanBaseAdminController is aligned with the refactoring approach and clarifies the scope of admin-specific functionality.


6-6: No concerns with this blank line.
It's just a formatting change with no functional impact.


11-11: Deprecation notice is consistent with the new class hierarchy.
This is a clear and explicit warning for users to migrate to the recommended base class.


15-15: Extending the new base class improves modularity and maintainability.
This aligns with your PR goal of refactoring the Dokan REST controllers for a clearer role-based separation.

includes/Abstracts/DokanRESTBaseController.php (4)

5-5: Aligned usage of the new base controller.
Using DokanBaseController simplifies inheritance and consolidates shared logic.


11-11: Clear deprecation reference.
Good job providing a direct pointer to the new implementation so developers know where to migrate.


15-15: Extending DokanBaseController ensures consistent fundamental features.
This is a solid approach, centralizing shared REST functionality.


10-10: Verify that the version is correct.
Make sure 3.14.4 matches the actual release version in which this deprecation becomes effective.

✅ Verification successful

Version 3.14.4 is correctly referenced

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Searching for references to 3.14.4 to confirm version usage aligns with PR's release targets.
rg "3\.14\.4"

Length of output: 360

includes/Abstracts/DokanRESTCustomerController.php (4)

5-5: Use of the new base customer controller is appropriate.
It clearly indicates the scope of the functionality for customer endpoints only.


11-11: Deprecation documentation is clear.
Minimal friction for developers to migrate.


15-15: Extending the new base class improves maintainability and clarity.
This is consistent with the rest of the refactoring in this PR.


10-10: Confirm the documented version is accurate.
Likewise, ensure 3.14.4 is indeed the intended version for these changes.

✅ Verification successful

Version 3.14.4 is correctly documented
The version number is consistently used across the codebase, including release notes, documentation, and related controller classes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Searching for references to 3.14.4 to confirm if it's consistently used throughout the codebase.
rg "3\.14\.4"

Length of output: 360

includes/Abstracts/DokanRESTVendorController.php (2)

10-11: LGTM! Version number is correctly specified.

The version number is properly updated from the placeholder to a specific version (3.14.4).


11-11: Verify the deprecation constant.

The deprecation notice uses DOKAN_SINCE constant. Please ensure this constant is defined and contains the correct version number.

Also applies to: 15-15

includes/REST/DokanBaseAdminController.php (1)

26-28: LGTM! Permission check is appropriate.

Using manage_woocommerce capability is the correct approach for admin-level operations.

includes/REST/DokanBaseVendorController.php (1)

28-30: Verify the 'dokandar' capability.

The permission check uses the 'dokandar' capability. Let's verify this capability is registered:

✅ Verification successful

'dokandar' capability is properly registered ✓

The capability is registered during installation and assigned to both 'shop_manager' and 'administrator' roles in includes/Install/Installer.php.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for dokandar capability registration
rg -B 2 -A 2 "dokandar.*capability|add_cap.*dokandar"

Length of output: 798

includes/REST/DokanBaseController.php (1)

16-21: LGTM! Proper REST API namespace definition.

The namespace property follows REST API versioning best practices with a protected scope.

docs/api/api.md (1)

93-100: LGTM! Well-documented filter.

The filter documentation follows WordPress standards and provides clear information about parameters.

Comment on lines 35 to 66
public function format_collection_response( $response, $request, $total_items ) {
if ( $total_items === 0 ) {
return $response;
}

// Pagination values for headers.
$per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 );
$page = (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 );

$response->header( 'X-WP-Total', (int) $total_items );

$max_pages = ceil( $total_items / $per_page );

$response->header( 'X-WP-TotalPages', (int) $max_pages );
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->base ) ) );

if ( $page > 1 ) {
$prev_page = $page - 1;
if ( $prev_page > $max_pages ) {
$prev_page = $max_pages;
}
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
}
if ( $max_pages > $page ) {
$next_page = $page + 1;
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
}

return $response;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for pagination parameters.

The pagination logic needs additional validation to handle edge cases:

  1. Negative page numbers
  2. Negative per_page values
  3. Upper limit on per_page to prevent resource exhaustion
     public function format_collection_response( $response, $request, $total_items ) {
         if ( $total_items === 0 ) {
             return $response;
         }
 
         // Pagination values for headers.
-        $per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 );
-        $page     = (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 );
+        $per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 );
+        $per_page = max( 1, min( 100, $per_page ) ); // Ensure between 1 and 100
+        $page     = max( 1, (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 ) );
📝 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
public function format_collection_response( $response, $request, $total_items ) {
if ( $total_items === 0 ) {
return $response;
}
// Pagination values for headers.
$per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 );
$page = (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 );
$response->header( 'X-WP-Total', (int) $total_items );
$max_pages = ceil( $total_items / $per_page );
$response->header( 'X-WP-TotalPages', (int) $max_pages );
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->base ) ) );
if ( $page > 1 ) {
$prev_page = $page - 1;
if ( $prev_page > $max_pages ) {
$prev_page = $max_pages;
}
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
}
if ( $max_pages > $page ) {
$next_page = $page + 1;
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
}
return $response;
}
public function format_collection_response( $response, $request, $total_items ) {
if ( $total_items === 0 ) {
return $response;
}
// Pagination values for headers.
$per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 );
$per_page = max( 1, min( 100, $per_page ) ); // Ensure between 1 and 100
$page = max( 1, (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 ) );
$response->header( 'X-WP-Total', (int) $total_items );
$max_pages = ceil( $total_items / $per_page );
$response->header( 'X-WP-TotalPages', (int) $max_pages );
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->base ) ) );
if ( $page > 1 ) {
$prev_page = $page - 1;
if ( $prev_page > $max_pages ) {
$prev_page = $max_pages;
}
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
}
if ( $max_pages > $page ) {
$next_page = $page + 1;
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
}
return $response;
}

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 (5)
includes/Traits/VendorAuthorizable.php (2)

9-9: Update @SInCE tag with actual version number.

Replace the placeholder "DOKAN_SINCE" with the actual version number where this trait was introduced.


13-15: Consider enhancing the permission check implementation.

A few suggestions to improve the implementation:

  1. Add return type declaration for PHP 7.4+ compatibility
  2. Consider adding error handling for edge cases
  3. Make the method name more specific about what permission it's checking
-    public function check_permission() {
+    public function check_vendor_permission(): bool {
         return current_user_can( 'dokandar' );
     }
docs/api/api.md (3)

42-47: Enhance error handling in prepare_item_for_response example.

The error message could be more helpful by suggesting what methods need to be implemented. Also, consider using a more specific error code.

     return new WP_Error(
-        'invalid-method',
+        'dokan-method-not-implemented',
         sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
         array( 'status' => 405 )
     );

124-125: Complete the TODO implementation in prepare_item_for_response.

The example should include a basic implementation to demonstrate proper response formatting.

Would you like me to provide a complete example implementation for the prepare_item_for_response method?


Line range hint 79-113: Enhance the admin controller example with proper error handling and validation.

The example could be improved in several areas:

  1. Add input validation for the collection parameters
  2. Include proper error handling for the permission check
  3. Document the expected response format
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce9d06e and 47ed7e2.

📒 Files selected for processing (3)
  • docs/api/api.md (2 hunks)
  • includes/REST/DokanBaseVendorController.php (1 hunks)
  • includes/Traits/VendorAuthorizable.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • includes/REST/DokanBaseVendorController.php
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
docs/api/api.md

11-11: Link fragments should be valid
null

(MD051, link-fragments)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: e2e tests (3, 3)
  • GitHub Check: e2e tests (2, 3)
  • GitHub Check: api tests (1, 1)
  • GitHub Check: e2e tests (1, 3)
🔇 Additional comments (2)
docs/api/api.md (2)

14-21: LGTM! Clear hierarchy explanation.

The documentation clearly explains the controller hierarchy and role-specific implementations.


53-70: Well-documented trait usage.

The VendorAuthorizable trait documentation is clear and includes a practical example.

- [VendorAuthorizable Trait](#vendorauthorizable-trait)
- [Example Implementations](#example-implementations)
- [Admin Controller Example](#admin-controller-example)
- [Vendor Controller Example](#vendor-controller-example)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix invalid link fragment in table of contents.

The link fragment for "Vendor Controller Example" is not properly defined in the document. Add a corresponding heading with the correct ID.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

11-11: Link fragments should be valid
null

(MD051, link-fragments)

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)
docs/api/api.md (2)

24-24: Add default namespace information.

Consider adding information about the default namespaces for each base controller type (e.g., 'dokan/v1/admin' for DokanBaseAdminController).


124-124: Implement the TODO in example code.

The example includes a TODO comment for API response formatting. Consider implementing a basic example to demonstrate the expected response format.

Would you like me to provide an example implementation for the API response formatting?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47ed7e2 and 47badce.

📒 Files selected for processing (1)
  • docs/api/api.md (2 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
docs/api/api.md

11-11: Link fragments should be valid
null

(MD051, link-fragments)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: e2e tests (3, 3)
  • GitHub Check: e2e tests (2, 3)
  • GitHub Check: api tests (1, 1)
  • GitHub Check: e2e tests (1, 3)
🔇 Additional comments (3)
docs/api/api.md (3)

11-11: Fix invalid link fragment in table of contents.

The link fragment for "Vendor Controller Example" is not properly defined in the document. Add a corresponding heading with the correct ID.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

11-11: Link fragments should be valid
null

(MD051, link-fragments)


14-14: Consider renaming base controller for consistency.

Based on previous discussions, consider using DokanBaseController instead of DokanBaseBaseController for better naming consistency.


57-70: Well-documented trait usage!

The documentation clearly explains the purpose and implementation of the VendorAuthorizable trait with a practical example.

*/
public function prepare_item_for_response( $user_data, $request ) {
// TODO: Implement API response formatting
return apply_filters( 'dokan_rest_prepare_admin', $response, $user_data, $request );
}
}
```
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add missing vendor controller example.

The table of contents references a "Vendor Controller Example" section, but the implementation is missing. Consider adding an example that demonstrates vendor-specific functionality using the VendorAuthorizable trait.

Would you like me to provide an example implementation for the vendor controller?

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 (3)
includes/REST/DokanBaseController.php (3)

21-21: Consider exposing a $version property.

Following previous feedback from another reviewer, if you wish to allow flexible versioning (e.g., v2), consider defining a dedicated $version property and referencing it within $namespace.


28-31: Remove or utilize the $items parameter.

Your doc block references $items as a parameter, but it’s unused in the method body. This may cause confusion about the actual usage of the parameter.


28-34: Add param types in doc blocks for clarity.

For enhanced clarity and consistency in WordPress docs, specify types in the doc blocks (e.g., $request as WP_REST_Request, $response as WP_REST_Response).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47badce and 2560103.

📒 Files selected for processing (1)
  • includes/REST/DokanBaseController.php (1 hunks)
🔇 Additional comments (2)
includes/REST/DokanBaseController.php (2)

41-42: Revisit pagination input validation (Duplicate of previous suggestion).

As previously suggested, consider validating pagination parameters to handle edge cases (negative or excessively large values) to avoid unintended resource usage.


49-49: Verify that $this->rest_base is declared in child classes.

This abstract class assumes $this->rest_base has been set elsewhere. Confirm this property is properly assigned and documented in extending classes to prevent undefined property errors.

@mrabbani
Copy link
Member Author

mrabbani commented Mar 3, 2025

@MdAsifHossainNadim vai, pls fix the merge conflict.

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

🔭 Outside diff range comments (1)
docs/api/api.md (1)

74-128: ⚠️ Potential issue

Admin Controller Example – Undefined Variable Warning

The Admin Controller Example is comprehensive and effectively demonstrates setting up routes and overriding methods. However, in the prepare_item_for_response method, the variable $response is referenced without prior initialization. This may lead to runtime errors. Consider initializing $response (even with a placeholder value) before it’s passed to apply_filters. For example:

-        return apply_filters( 'dokan_rest_prepare_admin', $response, $user_data, $request );
+        $response = []; // Initialize response structure
+        return apply_filters( 'dokan_rest_prepare_admin', $response, $user_data, $request );
🧹 Nitpick comments (1)
docs/api/api.md (1)

55-60: VendorAuthorizable Trait Documentation

The documentation for the VendorAuthorizable trait is informative and explains its purpose well. To further enhance developer understanding, consider linking to the trait’s source file or adding a brief description of its internal behavior.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2560103 and cb3b695.

📒 Files selected for processing (1)
  • docs/api/api.md (2 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
docs/api/api.md

11-11: Link fragments should be valid
null

(MD051, link-fragments)

🔇 Additional comments (7)
docs/api/api.md (7)

3-11: TOC Navigation and Link Validation

The addition of a comprehensive Table of Contents significantly enhances document navigation. However, the link for "Vendor Controller Example" (#vendor-controller-example) does not appear to correspond to any header in the document. Please ensure that a matching section is added or update the link accordingly.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

11-11: Link fragments should be valid
null

(MD051, link-fragments)


22-30: Clear Instructions for REST Controller Creation

The "Creating a REST Controller" section is well-structured and clearly instructs developers to extend one of the Dokan base controllers and override the necessary methods. This guidance will help ensure proper implementation.


32-49: Placeholder in prepare_item_for_response Method

The provided placeholder for prepare_item_for_response—which returns a WP_Error to signal that the method is not implemented—is clear and effectively communicates that subclasses must override this method. Consider adding a brief note or sample implementation to further assist developers.


51-54: Extending Other Controllers Section

The explanation regarding extending other controllers and the introduction of the VendorAuthorizable trait is concise and helpful. This section clearly motivates the use of the trait for managing vendor capabilities.


62-68: Example Usage of VendorAuthorizable Trait

The code snippet demonstrating the inclusion and usage of the VendorAuthorizable trait is succinct and clear. It provides a good example for developers looking to incorporate vendor capability checks.


70-72: Explanation of check_permission Method

The additional explanation that the trait provides a check_permission method is clear. This helps set the expectation regarding the capabilities offered by the trait.


129-132: Concluding Section Clarity

The final remarks effectively summarize the document structure and the standardized format of the controllers. This enhances readability and sets clear expectations for developers.

Comment on lines 13 to 21
## Introduction
The Dokan REST Controllers provide a structured approach to handle REST API endpoints with role-based permissions. The hierarchy consists of a base controller (`DokanRESTBaseController`) and role-specific controllers (`DokanRESTAdminController`, `DokanRESTVendorController`, `DokanRESTCustomerController`).
Dokan REST Controllers provide a structured approach to managing REST API endpoints with role-based permissions. The hierarchy consists of a base controller, `DokanBaseController`, and role-specific controllers:

## Base REST Controller
The `DokanRESTBaseController` extends WordPress's `WP_REST_Controller` and provides common functionality for all Dokan REST endpoints.
- `DokanBaseAdminController`
- `DokanBaseVendorController`
- `DokanBaseCustomerController`

### Base Controller Implementation
```php
abstract class DokanRESTBaseController extends WP_REST_Controller {
protected $namespace = 'dokan/v1';
These controllers extend the core `WP_REST_Controller` and provide predefined functionalities for different user roles.

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

Consistency in Base Controller Naming

The introduction refers to a base controller as DokanBaseController, but the PR summary and enriched documentation indicate a renaming (e.g., to DokanBaseBaseController). For clarity and consistency, please verify and update the base controller’s name throughout the document.


🏁 Script executed:

#!/bin/bash
# Search for both possible base controller names in the documentation
echo "Searching for 'DokanBaseController' in docs/api/api.md:"
rg "DokanBaseController" docs/api/api.md

echo "Searching for 'DokanBaseBaseController' in docs/api/api.md:"
rg "DokanBaseBaseController" docs/api/api.md

Length of output: 559


Update the Base Controller Name for Consistency

The introduction in the docs/api/api.md file currently refers to the controller as DokanBaseController, but the updated PR summary and enriched documentation indicate that it should now be named DokanBaseBaseController. Please update the name throughout the document to maintain clarity and consistency. Specifically:

  • Replace DokanBaseController with DokanBaseBaseController in the introduction snippet (lines 13–21).

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)
includes/REST/DokanBaseController.php (2)

21-21: Consider including a $version property for clarity and maintainability.

A previous reviewer suggested exposing a $version property. This may help with clearer REST routing or debugging, especially if you plan to update the namespace regularly based on versioning.


30-30: Remove or utilize the $items parameter.

The $items parameter is declared but never used. This can lead to confusion for future maintainers.

- * @param array  $items
...
- public function format_collection_response( $response, $request, $total_items ) {
+ public function format_collection_response( $response, $request, $total_items ) {

Either remove $items if unnecessary or integrate it to provide additional context within the formatted response.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb3b695 and 9bc15c4.

📒 Files selected for processing (1)
  • includes/REST/DokanBaseController.php (1 hunks)
🔇 Additional comments (2)
includes/REST/DokanBaseController.php (2)

41-42: [Duplicate Comment] Add input validation for pagination parameters.

As noted in a previous review, the pagination logic lacks strict validation. Consider clamping the values or handling edge cases (e.g., negative or extremely large values).

 $per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 );
+$per_page = max( 1, min( 100, $per_page ) ); // Ensure between 1 and 100
 $page     = (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 );
+$page     = max( 1, $page );

49-49: Verify that $base is defined or derived correctly in child classes.

The expression $this->base ?? $this->rest_base assumes at least one property is set. If neither $this->base nor $this->rest_base is declared in a subclass, the generated URL might be invalid.

Please ensure each extending controller properly sets $this->base or $this->rest_base.

@mrabbani mrabbani merged commit 64e2a8d into develop Mar 4, 2025
6 checks passed
@mrabbani mrabbani deleted the refactor/rest-api branch March 4, 2025 04:55
@coderabbitai coderabbitai bot mentioned this pull request Mar 6, 2025
12 tasks
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