-
Notifications
You must be signed in to change notification settings - Fork 206
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
Enhance/product category rest api #2510
base: develop
Are you sure you want to change the base?
Conversation
WalkthroughThis pull request introduces a new REST API controller for product categories in the Dokan framework. The changes include adding a new Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (3)
includes/REST/ProductCategoriesVendorController.php (1)
41-49
: Properly handle boolean 'hide_empty' parameterThe 'hide_empty' parameter is compared to the string 'true' in line 49, which may not handle other truthy values correctly. It's better to explicitly cast the parameter to a boolean or use WordPress's built-in functions to handle this.
Update the 'hide_empty' parameter in
get_collection_params()
:'hide_empty' => array( 'description' => 'Whether to hide terms not assigned to any posts.', 'type' => 'boolean', 'default' => false, + 'sanitize_callback' => 'rest_sanitize_boolean', ),
Then, adjust the assignment in your code:
- 'hide_empty' => $hide_empty === 'true', + 'hide_empty' => (bool) $hide_empty,tests/php/src/ProductCategory/ProductCategoryApiTest.php (2)
117-118
: Remove unnecessary 'search' parameter in exclude testIncluding the 'search' parameter may filter out categories and interfere with testing the 'exclude' parameter. Since you're testing exclusion, it's best to omit 'search' to ensure accurate results.
Apply this diff to remove the 'search' parameter:
- $request->set_param( 'search', 'term' );
146-146
: Remove unnecessary 'search' parameter in include testIn the
test_get_categories_with_include
method, setting the 'search' parameter could prevent the included category from appearing if it doesn't match the search term. Remove the 'search' parameter to focus solely on testing the 'include' functionality.Apply this diff to remove the 'search' parameter:
- $request->set_param( 'search', 'term' );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
includes/REST/Manager.php
(1 hunks)includes/REST/ProductCategoriesVendorController.php
(1 hunks)tests/php/src/ProductCategory/ProductCategoryApiTest.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: api tests (1, 1)
- GitHub Check: e2e tests (1, 3)
🔇 Additional comments (1)
includes/REST/Manager.php (1)
204-204
: New REST controller registered successfullyThe
ProductCategoriesVendorController
is properly added to the REST API class map, ensuring that the new endpoint is registered and functional.
$per_page = $request->get_param( 'per_page' ) ? $request->get_param( 'per_page' ) : 10; | ||
$page = $request->get_param( 'page' ) ? $request->get_param( 'page' ) : 1; | ||
$search = $request->get_param( 'search' ); | ||
$exclude = $request->get_param( 'exclude' ); | ||
$include = $request->get_param( 'include' ); | ||
$order = $request->get_param( 'order' ); | ||
$orderby = $request->get_param( 'orderby' ); | ||
$hide_empty = $request->get_param( 'hide_empty' ); | ||
$parent = $request->get_param( 'parent' ); | ||
$fields = $request->get_param( '_fields' ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Sanitize and validate request parameters
The request parameters such as 'order', 'orderby', 'parent', and others are not sanitized or validated. This could lead to unexpected behavior or security issues if invalid data is passed. It's important to add 'sanitize_callback' and 'validate_callback' functions to these parameters in your get_collection_params()
method.
For example, update the 'order' parameter:
'order' => array(
'description' => 'Order sort attribute ascending or descending.',
'type' => 'string',
'default' => 'ASC',
'enum' => array( 'ASC', 'DESC' ),
+ 'sanitize_callback' => 'sanitize_text_field',
+ 'validate_callback' => 'rest_validate_request_arg',
),
Similarly, add appropriate callbacks for 'orderby', 'parent', and other parameters to ensure they're properly sanitized and validated.
Committable suggestion skipped: line range outside the PR's diff.
$this->assertIsArray( $data ); | ||
$this->assertNotContains( $exclude, $data ); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct the assertion in exclude categories test
In the test_get_categories_with_exclude
method, the assertion on line 128 is incorrect because $data
is an array of category arrays, not category IDs. You need to extract the IDs before performing the assertion.
Apply this diff to fix the assertion:
- $this->assertNotContains( $exclude, $data );
+ $category_ids = wp_list_pluck( $data, 'id' );
+ $this->assertNotContains( (int) $exclude, $category_ids );
📝 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.
$this->assertIsArray( $data ); | |
$this->assertNotContains( $exclude, $data ); | |
} | |
$this->assertIsArray( $data ); | |
$category_ids = wp_list_pluck( $data, 'id' ); | |
$this->assertNotContains( (int) $exclude, $category_ids ); | |
} |
There was a problem hiding this 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 (4)
tests/php/src/ProductCategory/ProductCategoryApiTest.php (4)
37-39
: Fix indentation: Use spaces instead of tabsThe indentation in the test data creation uses tabs instead of spaces, which is inconsistent with the rest of the codebase.
Apply this diff to fix the indentation:
- 'taxonomy' => 'product_cat', - 'name' => 'Parent Category 1', + 'taxonomy' => 'product_cat', + 'name' => 'Parent Category 1',Also applies to: 44-46, 52-55, 60-63, 69-70
126-153
: Enhance pagination test with total count assertionWhile the pagination test covers basic scenarios, it would be more robust to verify the exact total count matches the expected number of categories (10 in this case: 2 parents + 2 children + 6 additional).
Add this assertion after line 151:
$this->assertArrayHasKey( 'X-WP-Total', $headers ); + $this->assertEquals( 10, $headers['X-WP-Total'] ); $this->assertArrayHasKey( 'X-WP-TotalPages', $headers ); + $this->assertEquals( 2, $headers['X-WP-TotalPages'] );
201-214
: Add edge cases to fields parameter testConsider adding tests for invalid field names to ensure the API handles them gracefully.
Add this test case:
$this->assertArrayNotHasKey( 'description', $category ); $this->assertArrayNotHasKey( 'parent', $category ); } + + // Test invalid field + $response = $this->make_request( [ '_fields' => 'id,invalid_field' ] ); + $data = $response->get_data(); + foreach ( $data as $category ) { + $this->assertArrayHasKey( 'id', $category ); + $this->assertArrayNotHasKey( 'invalid_field', $category ); + } }
235-248
: Optimize category cleanup in tearDownThe current implementation uses nested loops. Consider using
array_merge
to flatten the category IDs and delete them in a single loop.Apply this optimization:
public function tearDown(): void { - // Delete test categories - foreach ( $this->categories as $category_id ) { - if ( is_array( $category_id ) ) { - foreach ( $category_id as $id ) { - wp_delete_term( $id, 'product_cat' ); - } - } else { - wp_delete_term( $category_id, 'product_cat' ); - } - } + // Flatten and delete all category IDs + $category_ids = array_reduce( + $this->categories, + function ( $ids, $category_id ) { + return array_merge( + $ids, + is_array( $category_id ) ? $category_id : [ $category_id ] + ); + }, + [] + ); + foreach ( $category_ids as $id ) { + wp_delete_term( $id, 'product_cat' ); + } parent::tearDown(); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tests/php/src/ProductCategory/ProductCategoryApiTest.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 (2)
tests/php/src/ProductCategory/ProductCategoryApiTest.php (2)
79-88
: LGTM! Well-structured helper method for API requestsThe
make_request
helper method is well-designed, making it easy to test different API scenarios with various parameters.
100-121
: LGTM! Comprehensive authentication test coverageThe authentication test cases effectively verify:
- Endpoint registration
- Unauthorized access handling
- Vendor authorization
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
♻️ Duplicate comments (1)
includes/REST/ProductCategoriesVendorController.php (1)
85-85
:⚠️ Potential issueFix incorrect total categories count for pagination
The total count calculation is using the wrong arguments array, which includes pagination parameters. This will result in incorrect pagination headers.
- $total_categories = wp_count_terms( $args ); + $total_categories = wp_count_terms( $total_args );
🧹 Nitpick comments (3)
includes/REST/ProductCategoriesVendorController.php (3)
14-26
: Consider using WP_REST_Server constants for HTTP methodsReplace the hardcoded 'GET' string with
WP_REST_Server::READABLE
constant for better maintainability and consistency with WordPress coding standards.- 'methods' => 'GET', + 'methods' => WP_REST_Server::READABLE,
51-51
: Improve boolean conversion for hide_empty parameterThe current string comparison could be made more robust using WordPress's built-in function.
- 'hide_empty' => $hide_empty === 'true', + 'hide_empty' => rest_sanitize_boolean( $hide_empty ),
73-79
: Enhance error handling with specific error codesThe error handling could be more specific to help clients better understand and handle different types of failures.
if ( is_wp_error( $categories ) ) { + $error_code = $categories->get_error_code(); + $error_message = $categories->get_error_message(); return new WP_Error( - 'rest_category_error', - __( 'Error retrieving product categories.', 'dokan-lite' ), + 'dokan_rest_' . $error_code, + $error_message ?: __( 'Error retrieving product categories.', 'dokan-lite' ), array( 'status' => 400 ) ); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
includes/REST/ProductCategoriesVendorController.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: api tests (1, 1)
- GitHub Check: e2e tests (1, 3)
'search' => array( | ||
'description' => 'Limit results to those matching a string.', | ||
'type' => 'string', | ||
), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add sanitization callbacks for string parameters
The search, exclude, and include parameters should have sanitization callbacks to prevent potential security issues.
'search' => array(
'description' => 'Limit results to those matching a string.',
'type' => 'string',
+ 'sanitize_callback' => 'sanitize_text_field',
),
'exclude' => array(
'description' => 'Ensure result set excludes specific IDs.',
'type' => 'string',
+ 'sanitize_callback' => 'sanitize_text_field',
+ 'validate_callback' => array( $this, 'validate_id_string' ),
),
'include' => array(
'description' => 'Limit result set to specific IDs.',
'type' => 'string',
+ 'sanitize_callback' => 'sanitize_text_field',
+ 'validate_callback' => array( $this, 'validate_id_string' ),
),
Add this validation method to your class:
/**
* Validate a comma-separated string of IDs
*
* @param string $value The value to validate
* @return bool|WP_Error
*/
public function validate_id_string( $value ) {
if ( ! preg_match( '/^[\d,]+$/', $value ) ) {
return new WP_Error(
'rest_invalid_param',
__( 'String of IDs must contain only numbers and commas.', 'dokan-lite' )
);
}
return true;
}
Also applies to: 166-169, 170-173
'_fields' => array( | ||
'description' => 'Limit response to specific fields.', | ||
'type' => 'string', | ||
), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add validation for _fields parameter
The _fields parameter should validate that only existing fields are requested.
'_fields' => array(
'description' => 'Limit response to specific fields.',
'type' => 'string',
+ 'validate_callback' => array( $this, 'validate_fields' ),
),
Add this validation method to your class:
/**
* Validate requested fields
*
* @param string $value Comma-separated list of fields
* @return bool|WP_Error
*/
protected function validate_fields( $value ) {
$valid_fields = array( 'id', 'name', 'slug', 'parent', 'description', 'count', 'thumbnail', 'link' );
$requested_fields = explode( ',', $value );
$invalid_fields = array_diff( $requested_fields, $valid_fields );
if ( ! empty( $invalid_fields ) ) {
return new WP_Error(
'rest_invalid_fields',
sprintf(
__( 'Invalid field(s): %s. Valid fields are: %s', 'dokan-lite' ),
implode( ', ', $invalid_fields ),
implode( ', ', $valid_fields )
)
);
}
return true;
}
'description' => $category->description, | ||
'count' => (int) $category->count, | ||
'thumbnail' => $thumbnail_url, | ||
'link' => get_term_link( $category ), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error handling for term link generation
The get_term_link()
function can return WP_Error, which should be handled.
- 'link' => get_term_link( $category ),
+ 'link' => is_wp_error( $term_link = get_term_link( $category ) ) ? '' : $term_link,
📝 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.
'link' => get_term_link( $category ), | |
'link' => is_wp_error( $term_link = get_term_link( $category ) ) ? '' : $term_link, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
♻️ Duplicate comments (3)
includes/REST/ProductCategoriesVendorController.php (3)
84-84
:⚠️ Potential issueFix incorrect total categories count for pagination
The total count calculation is using the wrong arguments, which could lead to incorrect pagination.
-$total_categories = wp_count_terms( $args ); +$total_args = $args; +unset( $total_args['number'], $total_args['offset'] ); +$total_categories = wp_count_terms( $total_args );
123-123
:⚠️ Potential issueAdd error handling for term link generation
The get_term_link function can return WP_Error, which should be handled.
- 'link' => get_term_link( $category ), + 'link' => is_wp_error( $term_link = get_term_link( $category ) ) ? '' : $term_link,
167-171
: 🛠️ Refactor suggestionAdd validation for exclude and include parameters
The exclude and include parameters should validate that they contain only comma-separated integers.
'exclude' => array( 'description' => 'Ensure result set excludes specific IDs.', 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', + 'validate_callback' => array( $this, 'validate_id_string' ), ), 'include' => array( 'description' => 'Limit result set to specific IDs.', 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', + 'validate_callback' => array( $this, 'validate_id_string' ), ),Also applies to: 173-176
🧹 Nitpick comments (3)
includes/REST/ProductCategoriesVendorController.php (3)
10-10
: Add class-level PHPDocAdd a descriptive PHPDoc block for the class to document its purpose and responsibilities.
+/** + * REST controller for managing product categories in Dokan. + * + * @since x.x.x + * + * @package WeDevs\Dokan\REST + */ class ProductCategoriesVendorController extends DokanRESTVendorController {
51-51
: Improve boolean conversion for hide_empty parameterThe current boolean conversion is not robust enough and could lead to unexpected behavior.
- 'hide_empty' => $hide_empty === 'true', + 'hide_empty' => in_array( $hide_empty, [ 'true', '1', true, 1 ], true ),
113-113
: Add error handling for thumbnail URL generationThe wp_get_attachment_url function can return false, which should be handled explicitly.
- $thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : ''; + $thumbnail_url = $thumbnail_id ? (wp_get_attachment_url( $thumbnail_id ) ?: '') : '';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
includes/REST/ProductCategoriesVendorController.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: api tests (1, 1)
- GitHub Check: e2e tests (1, 3)
🔇 Additional comments (1)
includes/REST/ProductCategoriesVendorController.php (1)
134-137
: 🛠️ Refactor suggestionAdd validation for requested fields
The method should validate that only existing fields are requested to prevent unexpected behavior.
protected function filter_response_by_fields( $response, $fields ) { + $valid_fields = array_keys( $response ); $fields = explode( ',', $fields ); + $invalid_fields = array_diff( $fields, $valid_fields ); + if ( ! empty( $invalid_fields ) ) { + return $response; + } return array_intersect_key( $response, array_flip( $fields ) ); }Likely invalid or redundant comment.
'parent' => array( | ||
'description' => 'Limit result set to terms assigned to a specific parent.', | ||
'type' => 'integer', | ||
), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add validation for parent parameter
The parent parameter should be validated to ensure it's a positive integer.
'parent' => array(
'description' => 'Limit result set to terms assigned to a specific parent.',
'type' => 'integer',
+ 'minimum' => 0,
+ 'sanitize_callback' => 'absint',
+ 'validate_callback' => 'rest_validate_request_arg',
),
📝 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.
'parent' => array( | |
'description' => 'Limit result set to terms assigned to a specific parent.', | |
'type' => 'integer', | |
), | |
'parent' => array( | |
'description' => 'Limit result set to terms assigned to a specific parent.', | |
'type' => 'integer', | |
'minimum' => 0, | |
'sanitize_callback' => 'absint', | |
'validate_callback' => 'rest_validate_request_arg', | |
), |
$per_page = $request->get_param( 'per_page' ) ? $request->get_param( 'per_page' ) : 10; | ||
$page = $request->get_param( 'page' ) ? $request->get_param( 'page' ) : 1; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Validate maximum value for per_page parameter
The per_page parameter should be capped at 100 as defined in get_collection_params().
- $per_page = $request->get_param( 'per_page' ) ? $request->get_param( 'per_page' ) : 10;
+ $per_page = min( $request->get_param( 'per_page' ) ? (int) $request->get_param( 'per_page' ) : 10, 100 );
📝 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.
$per_page = $request->get_param( 'per_page' ) ? $request->get_param( 'per_page' ) : 10; | |
$page = $request->get_param( 'page' ) ? $request->get_param( 'page' ) : 1; | |
$per_page = min( $request->get_param( 'per_page' ) ? (int) $request->get_param( 'per_page' ) : 10, 100 ); | |
$page = $request->get_param( 'page' ) ? $request->get_param( 'page' ) : 1; |
All Submissions:
Changes proposed in this Pull Request:
Related Pull Request(s)
Closes
How to test the changes in this Pull Request:
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:
FOR PR REVIEWER ONLY:
Summary by CodeRabbit
New Features
Tests