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

🚀 enhance: StoreGrowth listed to the admin setup wizard recommendation plugins #2512

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

devAsadNur
Copy link
Member

@devAsadNur devAsadNur commented Jan 13, 2025

All Submissions:

  • My code follows 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

How to test the changes in this Pull Request:

Changelog entry

enhance: StoreGrowth listed to the admin setup wizard recommendation plugins

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

  • New Features

    • Updated recommended plugin setup process.
    • Enhanced plugin recommendation logic for dynamic retrieval and display of recommended plugins.
    • Introduced a new class for managing recommended plugins.
  • Bug Fixes

    • Improved plugin detection and display mechanisms.

@devAsadNur devAsadNur added Needs: Testing This requires further testing Needs: Dev Review It requires a developer review and approval labels Jan 13, 2025
@devAsadNur devAsadNur self-assigned this Jan 13, 2025
Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

Walkthrough

The pull request introduces significant changes to the Dokan Setup Wizard's handling of recommended plugins. It adds a new RecommendedPlugins class to centralize plugin management and replaces individual plugin checks with a dynamic loop for displaying recommendations. The SetupWizard class is updated to utilize this new structure, enhancing the logic for determining which plugins to install and display, including a focus on the StoreGrowth plugin.

Changes

File Change Summary
includes/Admin/SetupWizard.php - Added private property $recommended_plugins
- Refactored dokan_setup_recommended method to use new plugin management logic
- Updated dokan_setup_recommended_save method to generalize plugin installation checks
- Simplified should_show_recommended_step method
includes/Admin/RecommendedPlugins.php - Added RecommendedPlugins class
- Introduced methods: get(), get_enlisted_plugins(), and is_active()

Assessment against linked issues

Objective Addressed Explanation
Add StoreGrowth to recommended tools The implementation of StoreGrowth is not present in the changes.
Change plugin sequence The sequence modification for recommended plugins is not reflected in the current changes.
Show StoreGrowth title and subtitle Title and subtitle for StoreGrowth are not included in the changes.
Backend plugin installation The logic for installing the StoreGrowth plugin in the backend is not implemented.

Possibly related PRs

Suggested labels

QA approved, :+1: Dev Review Done, Upcoming Release

Poem

🐰 In the wizard's magical space,
StoreGrowth joins the plugin race,
With a hop and a click, it's now in sight,
Recommended tools shining bright!
A rabbit's tale of setup delight 🚀


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. (Beta)
  • @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: 0

🧹 Nitpick comments (2)
includes/Admin/SetupWizard.php (2)

940-940: Update version placeholder in docblock.

Replace DOKAN_SINCE with the actual version number where this feature was introduced.

-     * @since DOKAN_SINCE
+     * @since 3.9.0

937-947: Add safety check for is_plugin_active function.

The is_plugin_active function is not always available in WordPress. Consider adding a safety check.

 protected function is_store_growth_active() {
+    if ( ! function_exists( 'is_plugin_active' ) ) {
+        require_once ABSPATH . 'wp-admin/includes/plugin.php';
+    }
     return is_plugin_active( 'storegrowth-sales-booster/storegrowth-sales-booster.php' );
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00d3c5d and 64e6bf0.

⛔ Files ignored due to path filters (1)
  • assets/images/store-growth-logo.png is excluded by !**/*.png
📒 Files selected for processing (1)
  • includes/Admin/SetupWizard.php (5 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 (4)
includes/Admin/SetupWizard.php (4)

696-703: LGTM! Clean implementation of StoreGrowth plugin recommendation.

The integration follows the same pattern as other recommended plugins and maintains consistency in the codebase.


732-749: LGTM! Appropriate reordering of plugin checks.

The WooCommerce Conversion Tracking check is correctly positioned after the StoreGrowth plugin check.


755-755: LGTM! Improved plugin description clarity.

The updated description better communicates Texty's compatibility with multiple platforms.


789-804: LGTM! Well-structured StoreGrowth plugin installation handling.

The implementation follows the established pattern for plugin installations and includes proper sanitization of user input.

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/Admin/SetupWizard.php (2)

702-716: LGTM! Minor nitpick on the asset path constant.

The StoreGrowth plugin integration is well-structured and follows the established pattern. However, there's a typo in the constant name DOKAN_PLUGIN_ASSEST (should be DOKAN_PLUGIN_ASSET).

Consider fixing the typo in the constant name in a future update:

-                                'img_url'     => DOKAN_PLUGIN_ASSEST . '/images/store-growth-logo.png',
+                                'img_url'     => DOKAN_PLUGIN_ASSET . '/images/store-growth-logo.png',

943-953: Update the @SInCE tag with the correct version.

The @since tag is using a placeholder DOKAN_SINCE. Please replace it with the actual version number.

-     * @since DOKAN_SINCE
+     * @since 3.9.3
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 64e6bf0 and 2478c22.

📒 Files selected for processing (1)
  • includes/Admin/SetupWizard.php (5 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 (4)
includes/Admin/SetupWizard.php (4)

738-754: LGTM! Plugin order change looks good.

The WooCommerce Conversion Tracking plugin has been correctly repositioned after the StoreGrowth plugin while maintaining code structure and readability.


761-761: LGTM! Improved plugin description.

The updated description better communicates Texty's compatibility with Dokan.


795-810: LGTM! StoreGrowth installation handling is well-implemented.

The installation logic follows security best practices with proper sanitization and maintains consistency with other plugin installations.


924-927: LGTM! Visibility logic correctly updated.

The StoreGrowth plugin check has been properly integrated into the recommended step visibility logic.

@devAsadNur devAsadNur requested a review from mrabbani January 13, 2025 07:47
@@ -699,18 +699,18 @@ public function dokan_setup_recommended() {
<ul class="recommended-step">
<?php
if ( $this->user_can_install_plugin() ) {
if ( ! $this->is_wc_conversion_tracking_active() ) {
if ( ! $this->is_store_growth_active() ) {
Copy link
Member

Choose a reason for hiding this comment

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

  • Pls create separate class RecommendedPlugins and the get & is_active( string $plugin_basename ) method will return the recommended plugins.
  • Add new key 'basename' to the plugins and return the the recommended plugins by filtering with is active.
class RecommendedPlugins {
     protected array $plugins = [
          [
                                'type'        => 'wc_conversion_tracking',
                                'title'       => __( 'WooCommerce Conversion Tracking', 'dokan-lite' ),
                                'description' => __( 'Track conversions on your WooCommerce store like a pro!', 'dokan-lite' ),
                                'img_url'     => DOKAN_PLUGIN_ASSEST . '/images/wc-conversion-tracking-logo.png',
                                'img_alt'     => __( 'WooCommerce Conversion Tracking logo', 'dokan-lite' ),
                                'type'        => 'store_growth',
                                'title'       => __( 'StoreGrowth', 'dokan-lite' ),
                                'description' => __( 'Best WooCommerce Marketing Solution!', 'dokan-lite' ),
                                'img_url'     => DOKAN_PLUGIN_ASSEST . '/images/store-growth-logo.png',
                                'img_alt'     => __( 'StoreGrowth logo', 'dokan-lite' ),
                                'plugins'     => [
                                    [
                                        'name' => __( 'WooCommerce Conversion Tracking', 'dokan-lite' ),
                                        'basename' => 'storegrowth-sales-booster/storegrowth-sales-booster.php',
                                        'slug' => 'woocommerce-conversion-tracking',
                                        'name' => __( 'StoreGrowth', 'dokan-lite' ),
                                        'slug' => 'storegrowth-sales-booster',
                                    ],
                                ],
                            ]
     ];
     
    /**
     * Get all enlisted plugins with optional filters.
     */
    protected function get_enlisted_plugins(): array {
        return apply_filters( 'dokan_recommends_plugins', $this->plugins );
    }

    /**
     * Check if a plugin is active.
     */
    protected function is_active( string $basename ): bool {
        return apply_filters( 'dokan_recommended_plugin_is_active', is_plugin_active( $basename ), $basename );
    }

    /**
     * Get the list of recommended plugins that are not active.
     */
    public function get(): array {
        $enlisted_plugins = $this->get_enlisted_plugins();

       $recommended_plugins = array_filter(
            $enlisted_plugins,
            function ( $plugin ) {
                return isset( $plugin['basename'] ) && !$this->is_active( $plugin['basename'] );
            }
        );

        return apply_filters( 'dokan_recommended_plugins', $recommended_plugins );
    }
}

@jamil-mahmud
Copy link

BIG NOTE: DO NOT MERGE - UNLESS PM CLEARANCE

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)
includes/Admin/RecommendedPlugins.php (1)

8-8: Update version placeholder in PHPDoc.

The @since DOKAN_SINCE placeholder needs to be replaced with the actual version number.

includes/Admin/SetupWizard.php (1)

864-864: Update version placeholder in PHPDoc.

The @since DOKAN_SINCE placeholder needs to be replaced with the actual version number.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2478c22 and 7064e07.

📒 Files selected for processing (2)
  • includes/Admin/RecommendedPlugins.php (1 hunks)
  • includes/Admin/SetupWizard.php (3 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 (4)
includes/Admin/RecommendedPlugins.php (1)

25-82: LGTM! Well-structured plugins array with clear organization.

The plugins array is well-organized with consistent structure across all plugins. Each plugin entry includes all required fields: type, title, description, img_url, img_alt, and plugins array with name, slug, and basename.

includes/Admin/SetupWizard.php (3)

702-705: LGTM! Clean integration of RecommendedPlugins class.

The code effectively utilizes the new RecommendedPlugins class to manage and display recommended plugins.


729-743: LGTM! Proper implementation of StoreGrowth plugin installation.

The code correctly handles the StoreGrowth plugin installation when selected by the user.


702-705: Verify all references to recommended plugins are updated.

Let's ensure there are no remaining direct references to recommended plugins that should be using the new RecommendedPlugins class.

✅ Verification successful

Recommended plugins implementation is properly refactored

The new RecommendedPlugins class is correctly integrated and all references to recommended plugins are properly updated. The changes represent a clean refactoring that centralizes plugin definitions while maintaining the original functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct references to recommended plugins that might need updating

# Look for references to recommended plugins
rg -l "store_growth|wc_conversion_tracking|wemail|texty" --type php

# Look for potential plugin installation references
rg -l "install_plugin.*store.*growth" --type php

Length of output: 189


Script:

#!/bin/bash
# Inspect the implementation details of both files
echo "=== SetupWizard.php content ==="
rg -A 5 -B 5 "RecommendedPlugins|store_growth|wc_conversion_tracking|wemail|texty" includes/Admin/SetupWizard.php

echo -e "\n=== RecommendedPlugins.php content ==="
cat includes/Admin/RecommendedPlugins.php

# Look for any other plugin-related patterns
echo -e "\n=== Other plugin references ==="
rg -l "recommended.*plugin|plugin.*recommend" --type php

Length of output: 8863

}
);

error_log( print_r( $recommended_plugins, 1 ) );
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

Remove debug error_log statement.

Production code should not contain debug logging statements.

-        error_log( print_r( $recommended_plugins, 1 ) );

@devAsadNur devAsadNur requested a review from mrabbani January 16, 2025 12:11
@devAsadNur devAsadNur added Needs: Dev Review It requires a developer review and approval and removed Needs: Author Reply labels Jan 16, 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: 0

🧹 Nitpick comments (2)
includes/Admin/SetupWizard.php (2)

874-884: Update the version placeholder in PHPDoc.

The @since DOKAN_SINCE tag contains a placeholder that should be replaced with the actual version number.

-     * @since DOKAN_SINCE
+     * @since 3.9.0

738-753: Add error handling for plugin installation.

The plugin installation logic should handle potential errors that might occur during the installation process.

Consider adding error handling:

 if ( $setup_store_growth && ! $this->is_store_growth_active() ) {
+    try {
         $this->install_plugin(
             'storegrowth-sales-booster',
             [
                 'name'      => __( 'StoreGrowth', 'dokan-lite' ),
                 'repo-slug' => 'storegrowth-sales-booster',
                 'file'      => 'storegrowth-sales-booster.php',
             ]
         );
+    } catch ( Exception $e ) {
+        dokan_log( sprintf( 'StoreGrowth plugin installation failed: %s', $e->getMessage() ) );
+        // Optionally, add admin notice about the failure
+        add_action( 'admin_notices', function() {
+            echo '<div class="notice notice-error"><p>' . esc_html__( 'Failed to install StoreGrowth plugin. Please try installing it manually.', 'dokan-lite' ) . '</p></div>';
+        } );
+    }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 705eb76 and 3ae552a.

📒 Files selected for processing (1)
  • includes/Admin/SetupWizard.php (5 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)
includes/Admin/SetupWizard.php (2)

29-36: LGTM! Well-structured property declaration and initialization.

The new RecommendedPlugins property is properly typed, well-documented, and correctly initialized in the constructor.

Also applies to: 47-47


713-714: Implementation aligns with previous review suggestions.

The code now properly utilizes the RecommendedPlugins class for managing plugin recommendations, as suggested in the previous review.

Also applies to: 867-867

Comment on lines 738 to 743
$setup_store_growth = isset( $_POST['setup_store_growth'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_store_growth'] ) );
$setup_wc_conversion_tracking = isset( $_POST['setup_wc_conversion_tracking'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_wc_conversion_tracking'] ) );
$setup_wemail = isset( $_POST['setup_wemail'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_wemail'] ) );
$setup_texty = isset( $_POST['setup_texty'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_texty'] ) );

if ( $setup_store_growth && ! $this->is_store_growth_active() ) {
Copy link
Member

Choose a reason for hiding this comment

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

  • Pls also refactor this section so that we can handle it dynamically.
  • Check the current_user_can( 'manage_woocommerce' ) before the install.

@mrabbani mrabbani added Needs: Author Reply and removed Needs: Dev Review It requires a developer review and approval labels Jan 17, 2025
@devAsadNur devAsadNur added Needs: Dev Review It requires a developer review and approval and removed Needs: Author Reply labels Jan 17, 2025
@devAsadNur devAsadNur requested a review from mrabbani January 17, 2025 13:26
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: 2

🧹 Nitpick comments (1)
includes/Admin/SetupWizard.php (1)

940-942: Enhance error handling for unauthorized access.

Consider adding proper error handling when the user lacks required capabilities.

Apply this diff to improve the code:

 if ( ! current_user_can( 'manage_woocommerce' ) ) {
+    wp_die(
+        esc_html__( 'You do not have sufficient permissions to install plugins.', 'dokan-lite' ),
+        esc_html__( 'Permission Error', 'dokan-lite' ),
+        [ 'response' => 403 ]
+    );
     return;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ae552a and 8605cc3.

📒 Files selected for processing (1)
  • includes/Admin/SetupWizard.php (7 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 (3)
includes/Admin/SetupWizard.php (3)

29-36: LGTM! Well-documented property declaration.

The property is well-documented with proper PHPDoc and appropriate visibility modifier.


47-47: LGTM! Proper initialization with capability check.

The RecommendedPlugins instance is correctly initialized after verifying user capabilities.


713-714: LGTM! Improved plugin recommendation handling.

The code now uses a centralized approach for managing recommended plugins, making it more maintainable.

Comment on lines +775 to +794
/**
* Determines if a plugin should be installed based on POST data.
*
* @since DOKAN_SINCE
*
* @param array $plugin Plugin configuration array
*
* @return bool
*/
private function should_install_plugin( array $plugin ): bool {
check_admin_referer( 'dokan-setup' );

$setup_key = 'setup_' . $plugin['type'];

if ( ! isset( $_POST[ $setup_key ] ) ) {
return false;
}

return 'yes' === sanitize_text_field( wp_unslash( $_POST[ $setup_key ] ) );
}
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

Improve security and validation in should_install_plugin method.

Consider these improvements:

  1. Move nonce verification to the caller (dokan_setup_recommended_save)
  2. Add validation for the plugin array structure

Apply this diff to improve the code:

 private function should_install_plugin( array $plugin ): bool {
-    check_admin_referer( 'dokan-setup' );
+    if ( ! isset( $plugin['type'] ) || empty( $plugin['type'] ) ) {
+        return false;
+    }

     $setup_key = 'setup_' . $plugin['type'];

     if ( ! isset( $_POST[ $setup_key ] ) ) {
         return false;
     }

     return 'yes' === sanitize_text_field( wp_unslash( $_POST[ $setup_key ] ) );
 }

And in dokan_setup_recommended_save method:

 public function dokan_setup_recommended_save() {
+    check_admin_referer( 'dokan-setup' );
+
     foreach ( $this->recommended_plugins->get() as $plugin ) {

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +736 to +754
foreach ( $this->recommended_plugins->get() as $plugin ) {
if ( ! $this->should_install_plugin( $plugin ) ) {
continue;
}

$setup_wc_conversion_tracking = isset( $_POST['setup_wc_conversion_tracking'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_wc_conversion_tracking'] ) );
$setup_wemail = isset( $_POST['setup_wemail'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_wemail'] ) );
$setup_texty = isset( $_POST['setup_texty'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_texty'] ) );
$plugin_details = $plugin['plugins'][0] ?? null;

if ( $setup_wc_conversion_tracking && ! $this->is_wc_conversion_tracking_active() ) {
$this->install_plugin(
'woocommerce-conversion-tracking',
[
'name' => __( 'WooCommerce Conversion Tracking', 'dokan-lite' ),
'repo-slug' => 'woocommerce-conversion-tracking',
'file' => 'conversion-tracking.php',
]
);
}
if ( ! $plugin_details ) {
continue;
}

if ( $setup_wemail && ! $this->is_wemail_active() ) {
$this->install_plugin(
'wemail',
[
'name' => __( 'weMail', 'dokan-lite' ),
'repo-slug' => 'wemail',
'file' => 'wemail.php',
]
);
}
$plugin_details_arr = explode( '/', $plugin_details['basename'] ?? '' );

if ( $setup_texty && ! $this->is_texty_active() ) {
$this->install_plugin(
'texty',
$plugin_details['slug'],
[
'name' => __( 'Texty', 'dokan-lite' ),
'repo-slug' => 'texty',
'file' => 'texty.php',
'name' => $plugin_details['name'] ?? '',
'repo-slug' => $plugin_details_arr[0] ?? '',
'file' => $plugin_details_arr[1] ?? '',
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

Enhance array access safety and consistency.

Consider these improvements for safer array handling:

  1. Use null coalescing operator consistently
  2. Add validation for plugin details array structure
  3. Use array_key_exists for safer checks

Apply this diff to improve the code:

 foreach ( $this->recommended_plugins->get() as $plugin ) {
     if ( ! $this->should_install_plugin( $plugin ) ) {
         continue;
     }

-    $plugin_details = $plugin['plugins'][0] ?? null;
+    if ( ! isset( $plugin['plugins'] ) || ! is_array( $plugin['plugins'] ) || empty( $plugin['plugins'] ) ) {
+        continue;
+    }
+
+    $plugin_details = $plugin['plugins'][0];

     if ( ! $plugin_details ) {
         continue;
     }

-    $plugin_details_arr = explode( '/', $plugin_details['basename'] ?? '' );
+    $basename = $plugin_details['basename'] ?? '';
+    if ( empty( $basename ) ) {
+        continue;
+    }
+
+    $plugin_details_arr = explode( '/', $basename );

     $this->install_plugin(
         $plugin_details['slug'],
         [
-            'name'      => $plugin_details['name'] ?? '',
-            'repo-slug' => $plugin_details_arr[0] ?? '',
-            'file'      => $plugin_details_arr[1] ?? '',
+            'name'      => $plugin_details['name'] ?? 'Unknown Plugin',
+            'repo-slug' => $plugin_details_arr[0] ?? $plugin_details['slug'],
+            'file'      => $plugin_details_arr[1] ?? $plugin_details['slug'] . '.php',
         ]
     );
 }
📝 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
foreach ( $this->recommended_plugins->get() as $plugin ) {
if ( ! $this->should_install_plugin( $plugin ) ) {
continue;
}
$setup_wc_conversion_tracking = isset( $_POST['setup_wc_conversion_tracking'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_wc_conversion_tracking'] ) );
$setup_wemail = isset( $_POST['setup_wemail'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_wemail'] ) );
$setup_texty = isset( $_POST['setup_texty'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['setup_texty'] ) );
$plugin_details = $plugin['plugins'][0] ?? null;
if ( $setup_wc_conversion_tracking && ! $this->is_wc_conversion_tracking_active() ) {
$this->install_plugin(
'woocommerce-conversion-tracking',
[
'name' => __( 'WooCommerce Conversion Tracking', 'dokan-lite' ),
'repo-slug' => 'woocommerce-conversion-tracking',
'file' => 'conversion-tracking.php',
]
);
}
if ( ! $plugin_details ) {
continue;
}
if ( $setup_wemail && ! $this->is_wemail_active() ) {
$this->install_plugin(
'wemail',
[
'name' => __( 'weMail', 'dokan-lite' ),
'repo-slug' => 'wemail',
'file' => 'wemail.php',
]
);
}
$plugin_details_arr = explode( '/', $plugin_details['basename'] ?? '' );
if ( $setup_texty && ! $this->is_texty_active() ) {
$this->install_plugin(
'texty',
$plugin_details['slug'],
[
'name' => __( 'Texty', 'dokan-lite' ),
'repo-slug' => 'texty',
'file' => 'texty.php',
'name' => $plugin_details['name'] ?? '',
'repo-slug' => $plugin_details_arr[0] ?? '',
'file' => $plugin_details_arr[1] ?? '',
foreach ( $this->recommended_plugins->get() as $plugin ) {
if ( ! $this->should_install_plugin( $plugin ) ) {
continue;
}
if ( ! isset( $plugin['plugins'] ) || ! is_array( $plugin['plugins'] ) || empty( $plugin['plugins'] ) ) {
continue;
}
$plugin_details = $plugin['plugins'][0];
if ( ! $plugin_details ) {
continue;
}
$basename = $plugin_details['basename'] ?? '';
if ( empty( $basename ) ) {
continue;
}
$plugin_details_arr = explode( '/', $basename );
$this->install_plugin(
$plugin_details['slug'],
[
'name' => $plugin_details['name'] ?? 'Unknown Plugin',
'repo-slug' => $plugin_details_arr[0] ?? $plugin_details['slug'],
'file' => $plugin_details_arr[1] ?? $plugin_details['slug'] . '.php',
]
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs: Dev Review It requires a developer review and approval Needs: Testing This requires further testing PM Dependency
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants