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

Avoid loading Stripe script if Stripe gateway is not selected for a payment action. #2081

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

Conversation

AbdiTolesa
Copy link
Contributor

@AbdiTolesa AbdiTolesa commented Nov 4, 2024

Fix https://github.com/Strategy11/formidable-pro/issues/5004

Test steps

  1. Install and activate Authorize.NET add on and configure it as per the documentation: https://formidableforms.com/knowledgebase/authorize-net-aim/
  2. Also, make sure Stripe is configured in Global settings.
  3. Create a form and add a Payment action to your form.
  4. In the Payment action settings, select Authorize.NET as the only payment gateway.
  5. Save and preview your form.
  6. Confirm that Stripe js is not loaded. I would check the page source for frmstrp.js script.
  7. Go back to your form settings and check Stripe payment gateway.
  8. Save and preview your form again.
  9. Confirm the Stripe script is loaded now.

Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Warning

Rate limit exceeded

@AbdiTolesa has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 983f491 and 9d516d6.

Walkthrough

The changes introduce a new static variable and several methods in the FrmStrpLiteActionsController class to manage the loading of the Stripe script conditionally. The new methods determine if the script should be loaded based on form actions and ensure it is only loaded when necessary. The load_scripts method has been updated to incorporate these new methods, leading to a more organized and maintainable code structure.

Changes

File Path Change Summary
stripe/controllers/FrmStrpLiteActionsController.php - Added static variable $has_loaded_stripe_script.
- Added methods: should_load_stripe_script(), should_load_stripe_script_for_form($form_id), maybe_load_stripe_script().
- Modified load_scripts to call maybe_load_stripe_script.
- Removed redundant code in load_scripts.

Possibly related PRs

  • Apply Stripe PR 351 #2076: This PR is related as it involves changes to the payment processing workflow in the FrmStrpLiteAuth class, which may interact with the new methods for managing the Stripe script loading in the FrmStrpLiteActionsController class, particularly in scenarios where payment actions are involved.

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

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 and nitpick comments (1)
stripe/controllers/FrmStrpLiteActionsController.php (1)

464-464: Update @SInCE version tags.

The @SInCE tags show placeholder versions ("x.x"). Please update them with the correct version number.

Also applies to: 491-491

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 75069ff and 95f494b.

📒 Files selected for processing (1)
  • stripe/controllers/FrmStrpLiteActionsController.php (2 hunks)
🔇 Additional comments (3)
stripe/controllers/FrmStrpLiteActionsController.php (3)

13-13: LGTM: Well-structured static variable declaration.

The private static variable is appropriately used to track the Stripe script loading state, preventing duplicate loads.


442-459: LGTM: Well-implemented script loading optimization.

The changes improve performance by:

  1. Conditionally loading the Stripe script
  2. Properly preparing and localizing script variables
  3. Following WordPress script enqueuing best practices

468-486: LGTM: Well-structured helper methods.

The new helper methods are:

  1. Well-organized with clear responsibilities
  2. Include proper validation and error handling
  3. Follow good coding practices

Also applies to: 496-511, 519-522

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

🧹 Outside diff range and nitpick comments (1)
stripe/controllers/FrmStrpLiteActionsController.php (1)

501-508: Enhance form ID validation.

Consider adding explicit type checking and validation for the form ID parameter.

 private static function should_load_stripe_script_for_form( $form_id ) {
+    $form_id = absint( $form_id );
+    if ( ! $form_id ) {
+        return false;
+    }
     $action_status   = array(
         'post_status' => 'publish',
     );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 95f494b and 00f45ee.

📒 Files selected for processing (1)
  • stripe/controllers/FrmStrpLiteActionsController.php (2 hunks)
🔇 Additional comments (4)
stripe/controllers/FrmStrpLiteActionsController.php (4)

13-18: LGTM! Well-documented static variable.

The new static variable is properly scoped and documented with PHPDoc standards.


447-464: LGTM! Secure script loading implementation.

The implementation includes proper security measures with nonce verification and URL escaping. The script parameters are comprehensive and well-structured.


466-491: LGTM! Well-structured conditional loading logic.

The method effectively manages the script loading state and follows single responsibility principle.


510-514: ⚠️ Potential issue

Add type safety checks for gateway access.

The code assumes $action->post_content['gateway'] is always an array, which could lead to runtime errors.

@AbdiTolesa AbdiTolesa changed the title Issue 5004 load stripe script conditionally Avoid loading Stripe script if Stripe gateway is not selected for a payment action. Nov 4, 2024
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

🧹 Outside diff range and nitpick comments (1)
stripe/controllers/FrmStrpLiteActionsController.php (1)

466-491: Consider using early returns for better readability.

While the logic is correct, the method's readability could be improved by restructuring with early returns.

Consider this refactoring:

 private static function should_load_stripe_script() {
     if ( self::$has_loaded_stripe_script ) {
         return false;
     }
     global $frm_vars;
-    $form_ids = $frm_vars['forms_loaded'];
-    if ( ! is_array( $form_ids ) ) {
+    if ( empty( $frm_vars['forms_loaded'] ) || ! is_array( $frm_vars['forms_loaded'] ) ) {
         return false;
     }
-    $form_ids = array_unique( wp_list_pluck( $form_ids, 'id' ) );
+    $form_ids = array_unique( wp_list_pluck( $frm_vars['forms_loaded'], 'id' ) );
     foreach ( $form_ids as $form_id ) {
         if ( self::should_load_stripe_script_for_form( $form_id ) ) {
             self::$has_loaded_stripe_script = true;
             return true;
         }
     }
     return false;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 00f45ee and beda56b.

📒 Files selected for processing (1)
  • stripe/controllers/FrmStrpLiteActionsController.php (2 hunks)
🔇 Additional comments (4)
stripe/controllers/FrmStrpLiteActionsController.php (4)

13-18: LGTM! Well-documented static variable.

The static variable is properly declared and documented with PHPDoc comments.


Line range hint 518-564: LGTM! Well-structured script loading logic.

The method properly handles:

  • Conditional script loading
  • Dependencies management
  • File existence checks
  • Minified/unminified file variants

447-464: LGTM! Good separation of concerns.

The changes improve code organization by:

  • Separating script loading logic into a dedicated method
  • Maintaining proper order of operations (script loading before localization)

493-516: ⚠️ Potential issue

Add type checking for gateway array access.

The array access at line 511 assumes $action->post_content['gateway'] is always an array, which could lead to runtime errors.

Apply the type checking as suggested in the past review:

 foreach ( $payment_actions as $action ) {
-    if ( in_array( 'stripe', $action->post_content['gateway'], true ) ) {
+    if ( isset( $action->post_content['gateway'] ) && 
+         ( ( is_array( $action->post_content['gateway'] ) && in_array( 'stripe', $action->post_content['gateway'], true ) ) ||
+           ( is_string( $action->post_content['gateway'] ) && 'stripe' === $action->post_content['gateway'] ) ) ) {
         return true;
     }
 }

Copy link
Contributor

@lauramekaj1 lauramekaj1 left a comment

Choose a reason for hiding this comment

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

@AbdiTolesa I tested this and it's working fine for me. Thank you!

@Crabcyborg Crabcyborg requested a review from truongwp November 6, 2024 15:07
@AbdiTolesa AbdiTolesa requested a review from truongwp November 7, 2024 06:52
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 and nitpick comments (2)
stripe/controllers/FrmStrpLiteActionsController.php (2)

447-464: Consider optimizing script loading order.

The script variables are being localized even if the Stripe script is not loaded. Consider wrapping the variable preparation and localization within the same conditional check.

- self::maybe_load_stripe_script();
- 
- $action_settings = self::prepare_settings_for_js( $form_id );
- $style_settings  = self::get_style_settings_for_form( $form_id );
- $stripe_vars     = array(
-   'publishable_key' => $publishable,
-   'form_id'         => $form_id,
-   'nonce'           => wp_create_nonce( 'frm_strp_ajax' ),
-   'ajax'            => esc_url_raw( FrmAppHelper::get_ajax_url() ),
-   'settings'        => $action_settings,
-   'locale'          => self::get_locale(),
-   'baseFontSize'    => $style_settings['field_font_size'],
-   'appearanceRules' => self::get_appearance_rules( $style_settings ),
-   'account_id'      => FrmStrpLiteConnectHelper::get_account_id(),
- );
- 
- wp_localize_script( 'formidable-stripe', 'frm_stripe_vars', $stripe_vars );

+ if (self::maybe_load_stripe_script()) {
+   $action_settings = self::prepare_settings_for_js( $form_id );
+   $style_settings  = self::get_style_settings_for_form( $form_id );
+   $stripe_vars     = array(
+     'publishable_key' => $publishable,
+     'form_id'         => $form_id,
+     'nonce'           => wp_create_nonce( 'frm_strp_ajax' ),
+     'ajax'            => esc_url_raw( FrmAppHelper::get_ajax_url() ),
+     'settings'        => $action_settings,
+     'locale'          => self::get_locale(),
+     'baseFontSize'    => $style_settings['field_font_size'],
+     'appearanceRules' => self::get_appearance_rules( $style_settings ),
+     'account_id'      => FrmStrpLiteConnectHelper::get_account_id(),
+   );
+   
+   wp_localize_script( 'formidable-stripe', 'frm_stripe_vars', $stripe_vars );
+ }

524-527: Consider returning boolean from maybe_load_stripe_script.

The method name suggests it might return a boolean indicating whether the script was loaded, which would be useful for the suggested optimization in the script loading order.

- private static function maybe_load_stripe_script() {
+ private static function maybe_load_stripe_script(): bool {
   if ( ! self::should_load_stripe_script() ) {
-    return;
+    return false;
   }
+  return true;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between beda56b and 983f491.

📒 Files selected for processing (1)
  • stripe/controllers/FrmStrpLiteActionsController.php (2 hunks)
🔇 Additional comments (2)
stripe/controllers/FrmStrpLiteActionsController.php (2)

13-18: LGTM! Well-documented static variable.

The new static variable is properly declared with clear PHPDoc documentation.


510-514: ⚠️ Potential issue

Add type check before accessing array index.

As noted in the previous review, the code assumes $action->post_content['gateway'] is always an array. Add a type check to prevent potential errors.

- if ( in_array( 'stripe', $action->post_content['gateway'], true ) ) {
+ if ( isset( $action->post_content['gateway'] ) && 
+      ( ( is_array( $action->post_content['gateway'] ) && in_array( 'stripe', $action->post_content['gateway'], true ) ) ||
+        ( is_string( $action->post_content['gateway'] ) && 'stripe' === $action->post_content['gateway'] ) ) ) {

Comment on lines +473 to +491
private static function should_load_stripe_script() {
if ( self::$has_loaded_stripe_script ) {
return false;
}
global $frm_vars;
$form_ids = $frm_vars['forms_loaded'];
if ( empty( $form_ids ) || ! is_array( $form_ids ) ) {
return false;
}
$form_ids = array_unique( wp_list_pluck( $form_ids, 'id' ) );
foreach ( $form_ids as $form_id ) {
if ( self::should_load_stripe_script_for_form( $form_id ) ) {
self::$has_loaded_stripe_script = true;
return true;
}
}

return false;
}
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 early return and empty check for forms_loaded.

The function could be simplified with early returns, and the empty check for $frm_vars['forms_loaded'] should be moved before accessing it.

 private static function should_load_stripe_script() {
   if ( self::$has_loaded_stripe_script ) {
     return false;
   }
   global $frm_vars;
-  $form_ids = $frm_vars['forms_loaded'];
-  if ( empty( $form_ids ) || ! is_array( $form_ids ) ) {
+  if ( empty( $frm_vars['forms_loaded'] ) || ! is_array( $frm_vars['forms_loaded'] ) ) {
     return false;
   }
+  $form_ids = $frm_vars['forms_loaded'];
   $form_ids = array_unique( wp_list_pluck( $form_ids, 'id' ) );
📝 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
private static function should_load_stripe_script() {
if ( self::$has_loaded_stripe_script ) {
return false;
}
global $frm_vars;
$form_ids = $frm_vars['forms_loaded'];
if ( empty( $form_ids ) || ! is_array( $form_ids ) ) {
return false;
}
$form_ids = array_unique( wp_list_pluck( $form_ids, 'id' ) );
foreach ( $form_ids as $form_id ) {
if ( self::should_load_stripe_script_for_form( $form_id ) ) {
self::$has_loaded_stripe_script = true;
return true;
}
}
return false;
}
private static function should_load_stripe_script() {
if ( self::$has_loaded_stripe_script ) {
return false;
}
global $frm_vars;
if ( empty( $frm_vars['forms_loaded'] ) || ! is_array( $frm_vars['forms_loaded'] ) ) {
return false;
}
$form_ids = $frm_vars['forms_loaded'];
$form_ids = array_unique( wp_list_pluck( $form_ids, 'id' ) );
foreach ( $form_ids as $form_id ) {
if ( self::should_load_stripe_script_for_form( $form_id ) ) {
self::$has_loaded_stripe_script = true;
return true;
}
}
return false;
}

@AbdiTolesa AbdiTolesa requested a review from truongwp November 11, 2024 11:33
Copy link
Contributor

@truongwp truongwp left a comment

Choose a reason for hiding this comment

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

This looks good now. Thanks @AbdiTolesa!

@truongwp truongwp requested a review from Crabcyborg November 12, 2024 17:09
@Crabcyborg Crabcyborg added this to the 6.16.2 milestone Nov 12, 2024
@Crabcyborg Crabcyborg modified the milestones: 6.16.2, 6.16.3 Nov 20, 2024
@Crabcyborg Crabcyborg modified the milestones: 6.16.3, 6.17 Dec 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants