Skip to content

Guard WP_Router::$request before use#589

Open
arifulhoque7 wants to merge 1 commit intoweDevsOfficial:developfrom
arifulhoque7:feature/invoice-module-improvements
Open

Guard WP_Router::$request before use#589
arifulhoque7 wants to merge 1 commit intoweDevsOfficial:developfrom
arifulhoque7:feature/invoice-module-improvements

Conversation

@arifulhoque7
Copy link
Copy Markdown
Contributor

@arifulhoque7 arifulhoque7 commented Mar 31, 2026

PR Description Close 304

Related PRO PR

Summary

This PR improves the invoice module functionality across the PM Pro plugin by enhancing data transformation, shortcode handling, and frontend script management.

Changes Made

1. Invoice.php (Main Module)

  • Updated script enqueuing and localization for better compatibility
  • Improved frontend script loading and data passing to the invoice component
  • Added better support for project data in frontend invoice rendering
  • Enhanced localization data handling for consistency across requests

2. Invoice Shortcode (includes/shortcodes/Invoice.php)

  • Improved shortcode output handling
  • Added better authentication checks for logged-in users
  • Enhanced frontend script initialization for the invoice component
  • Simplified and optimized the shortcode wrapper logic

3. Invoice Transformer (Src/Transformers/Invoice_Transformer.php)

  • Optimized data transformation pipeline for invoice objects
  • Improved payment and amount calculation methods
  • Enhanced filtering logic for invoice items (tasks/names)
  • Better handling of client address and invoice metadata

4. Vue Component Mixin (views/assets/src/helpers/mixin/mixin.js)

  • Added methods for PDF generation and email functionality
  • Improved helper methods for data retrieval and manipulation
  • Enhanced request handling for payment and invoice operations
  • Better country/currency code lookups

5. Transformer Manager Trait (Transformer_Manager.php)

  • Refined response formatting and serialization
  • Improved JSON response generation
  • Better handling of query parameters for resource includes
  • Enhanced security with sanitization

6. Compiled Assets (invoice.js)

  • Rebuilt and optimized compiled JavaScript bundle
  • Reflects all Vue component improvements

Impact

  • ✅ Improved invoice data consistency and accuracy
  • ✅ Better frontend user experience with optimized scripts
  • ✅ Enhanced API response handling
  • ✅ Improved code maintainability and consistency
  • ✅ Better support for related data includes

Files Modified

  • wp-content/plugins/pm-pro/modules/Invoice/Invoice.php
  • wp-content/plugins/pm-pro/modules/Invoice/includes/shortcodes/Invoice.php
  • wp-content/plugins/pm-pro/modules/Invoice/Src/Transformers/Invoice_Transformer.php
  • wp-content/plugins/pm-pro/modules/Invoice/views/assets/src/helpers/mixin/mixin.js
  • wp-content/plugins/pm-pro/modules/Invoice/views/assets/js/invoice.js
  • wp-content/plugins/wedevs-project-manager/src/Common/Traits/Transformer_Manager.php

Testing

  • Verify invoice display on frontend
  • Test PDF generation functionality
  • Confirm email sending works correctly
  • Validate API responses with data includes
  • Check backward compatibility with existing invoices

Related Issues

  • Resolves invoice module data handling inconsistencies
  • Improves transformer object serialization

Summary by CodeRabbit

  • Bug Fixes
    • Improved request parameter handling to prevent errors in edge cases, ensuring more stable application behavior when processing query parameters.

Add a check that WP_Router::$request is truthy before calling get_query_params() and accessing the 'with' query param. This prevents fatal errors when the static request property is not initialized; the same guard is applied in both locations where parseIncludes is called.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 31, 2026

Walkthrough

Two methods in the Transformer Manager trait now include defensive null checks before accessing the request query parameters. The update guards against potential null reference errors when WP_Router::$request is unset, while preserving all existing parsing and response-building logic.

Changes

Cohort / File(s) Summary
Null Safety Guard
src/Common/Traits/Transformer_Manager.php
Added existence checks for WP_Router::$request in get_response() and get_json_response() methods before accessing query parameters with the with key, preventing undefined reference errors.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

A rabbit hops through defensive code,
Where null checks guard the safest road, 🐰
Two methods now stand strong and true,
With request checks before they flew!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Guard WP_Router::$request before use' directly and clearly summarizes the main change: adding a guard check for WP_Router::$request before accessing it to prevent errors.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@arifulhoque7 arifulhoque7 self-assigned this Mar 31, 2026
@arifulhoque7 arifulhoque7 added Needs Dev Review This PR needs review by a developer Needs Testing This issue/PR needs further testing labels Mar 31, 2026
Copy link
Copy Markdown

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

🧹 Nitpick comments (1)
src/Common/Traits/Transformer_Manager.php (1)

13-46: Consider extracting duplicate manager setup logic.

Both get_response() and get_json_response() share identical manager initialization and include-parsing logic. Extracting this to a private helper method would reduce duplication and ensure the guard is maintained in one place.

♻️ Optional refactor to reduce duplication
+    private function create_manager() {
+        $manager = new Manager();
+        $manager->setSerializer( new DataArraySerializer() );
+
+        if (WP_Router::$request && isset(WP_Router::$request->get_query_params()['with'])) {
+            $manager->parseIncludes(sanitize_text_field(wp_unslash(WP_Router::$request->get_query_params()['with'])));
+        }
+
+        return $manager;
+    }
+
     public function get_response( $resource, $extra = [] ) {
-        $manager = new Manager();
-        $manager->setSerializer( new DataArraySerializer() );
-
-        if (WP_Router::$request && isset(WP_Router::$request->get_query_params()['with'])) {
-            $manager->parseIncludes(sanitize_text_field(wp_unslash(WP_Router::$request->get_query_params()['with'])));
-        }
+        $manager = $this->create_manager();

         if ($resource) {
             $response = $manager->createData( $resource )->toArray();
-
         } else {
             $response = [];
         }
        
         return array_merge( $extra, $response );
     }

     public function get_json_response( $resource, $extra = [] ) {
-        $manager = new Manager();
-        $manager->setSerializer( new DataArraySerializer() );
-
-
-        if (WP_Router::$request && isset(WP_Router::$request->get_query_params()['with'])) {
-            $manager->parseIncludes(sanitize_text_field(wp_unslash(WP_Router::$request->get_query_params()['with'])));
-        }
+        $manager = $this->create_manager();

         if ($resource) {
             $response = $manager->createData( $resource )->toArray();
         } else {
             $response = [];
         }

         return json_encode( array_merge( $extra, $response ) );
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Common/Traits/Transformer_Manager.php` around lines 13 - 46, Extract the
duplicated Manager initialization and include-parsing into a private helper
(e.g., init_manager_with_includes()) used by both get_response() and
get_json_response(): move creation of new Manager(), setSerializer(new
DataArraySerializer()), and the WP_Router::$request guard +
parseIncludes(sanitize_text_field(wp_unslash(...))) into that helper and return
the configured Manager instance; then call that helper from get_response() and
get_json_response() before calling createData($resource)->toArray() so the
include-guard logic lives in one place.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/Common/Traits/Transformer_Manager.php`:
- Around line 13-46: Extract the duplicated Manager initialization and
include-parsing into a private helper (e.g., init_manager_with_includes()) used
by both get_response() and get_json_response(): move creation of new Manager(),
setSerializer(new DataArraySerializer()), and the WP_Router::$request guard +
parseIncludes(sanitize_text_field(wp_unslash(...))) into that helper and return
the configured Manager instance; then call that helper from get_response() and
get_json_response() before calling createData($resource)->toArray() so the
include-guard logic lives in one place.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e4cf2c36-0f18-4240-8cb0-4ca210f57711

📥 Commits

Reviewing files that changed from the base of the PR and between 61f8f1f and 6133d6e.

📒 Files selected for processing (1)
  • src/Common/Traits/Transformer_Manager.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Needs Dev Review This PR needs review by a developer Needs Testing This issue/PR needs further testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant