diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..7b68c1c4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +# This file is for unifying the coding style for different editors and IDEs +# editorconfig.org + +# WordPress Coding Standards +# https://make.wordpress.org/core/handbook/coding-standards/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +tab_width = 4 +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true + +[*.txt] +trim_trailing_whitespace = false + +[*.{md,json,yml}] +trim_trailing_whitespace = false +indent_style = space +indent_size = 2 + +[*.json] +indent_style = tab diff --git a/.github/workflows/aqua.yml b/.github/workflows/aqua.yml index 633e7bc4..4811d9f7 100644 --- a/.github/workflows/aqua.yml +++ b/.github/workflows/aqua.yml @@ -1,4 +1,5 @@ name: Aqua + on: pull_request: branches: @@ -7,25 +8,43 @@ on: jobs: aqua: - name: Aqua scanner - runs-on: ubuntu-22.04 + name: Code scanning + runs-on: ubuntu-24.04 + + permissions: + contents: read + id-token: write + steps: - name: Checkout code uses: actions/checkout@v4 + with: + show-progress: false + + - name: Authenticate to Google Cloud + id: gcloud-auth + uses: google-github-actions/auth@v2 + with: + token_format: access_token + workload_identity_provider: projects/699052769907/locations/global/workloadIdentityPools/github-identity-pool-shared/providers/github-identity-provider-shared # yamllint disable-line + service_account: github-gar-alma-woocommerce-ga@lyrical-carver-335213.iam.gserviceaccount.com + + - name: Authenticate to Artifact Registry + uses: docker/login-action@v3 + with: + registry: europe-docker.pkg.dev + username: oauth2accesstoken + password: ${{ steps.gcloud-auth.outputs.access_token }} - name: Run Aqua scanner uses: docker://aquasec/aqua-scanner - with: - args: trivy fs --sast --reachability --scanners misconfig,vuln,secret . - # To customize which severities add the following flag: --severity UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL - # To enable SAST scanning, add: --sast - # To enable reachability scanning, add: --reachability - # To enable npm/dotnet non-lock file scanning, add: --package-json / --dotnet-proj env: AQUA_KEY: ${{ secrets.AQUA_KEY }} AQUA_SECRET: ${{ secrets.AQUA_SECRET }} GITHUB_TOKEN: ${{ github.token }} AQUA_URL: https://api.eu-1.supply-chain.cloud.aquasec.com CSPM_URL: https://eu-1.api.cloudsploit.com - TRIVY_RUN_AS_PLUGIN: "aqua" - # For http/https proxy configuration add env vars: HTTP_PROXY/HTTPS_PROXY, CA-CRET (path to CA certificate) + TRIVY_RUN_AS_PLUGIN: aqua + TRIVY_DB_REPOSITORY: europe-docker.pkg.dev/lyrical-carver-335213/aquasec/trivy-db:2 + with: + args: trivy fs --sast --reachability --scanners misconfig,vuln,secret . diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d772321..f0cec999 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,18 @@ on: workflow_dispatch: ~ jobs: - + sonarcloud: + name: SonarQube Cloud + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: SonarQube Cloud Scan + uses: SonarSource/sonarcloud-github-action@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} lint: name: Lint code runs-on: ubuntu-22.04 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8d39610c..86d1f50d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -23,13 +23,13 @@ repos: name: PHP and WordPress coding standards Fixer test language: system entry: ./bin/coding-standard-fixer.sh - stages: [commit] + stages: [pre-commit] - id: coding-standard name: Check the PHP and WordPress coding standards language: system entry: ./bin/coding-standard.sh - stages: [commit] + stages: [pre-commit] # - repo: https://github.com/returntocorp/semgrep # rev: v1.75.0 diff --git a/Dockerfile b/Dockerfile index dddbadeb..7d0fa020 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -ARG PHP_VERSION +ARG PHP_VERSION=latest FROM composer:2 AS composer FROM php:${PHP_VERSION} diff --git a/Dockerfile.legacy b/Dockerfile.legacy index 2f38ff93..2d5e296e 100644 --- a/Dockerfile.legacy +++ b/Dockerfile.legacy @@ -12,15 +12,15 @@ ENV DEBIAN_FRONTEND=noninteractive sed -i s/stretch-updates/stretch/g /etc/apt/sources.list # Install dependencies -RUN apt update && \ - apt install -y --no-install-recommends \ +RUN apt update \ + && apt install -y --no-install-recommends \ git \ - zip \ - unzip \ rsync \ + unzip \ + zip \ && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* + apt-get clean \ + && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* # Create non-root user RUN useradd -u ${UID} -ms /bin/bash phpuser diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 00000000..1744790a --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,15 @@ +# General setup +sonar.projectKey=alma_alma-woocommerce-gateway +sonar.organization=almapay +# This is the name and version displayed in the SonarCloud UI. +sonar.projectName=alma-woocommerce-gateway +# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. +sonar.sources=src/ +sonar.exclusions=src/.composer/**,src/.subversion/**,src/assets/widget/**,src/bin/**,src/build/**,src/languages/**,src/vendor/**,src/.phpcs.xml.dist,src/.phpunit.result.cache,src/phpcs.xml,src/phpunit.xml.dist,src/phpcs.xml +# Test folders +sonar.tests=src/tests/ +sonar.test.inclusions=src/tests/**/* +# Encoding of the source code. Default is default system encoding +sonar.sourceEncoding=UTF-8 +# Exclude files from coverage +sonar.coverage.exclusions=src/tests/**/* diff --git a/src/includes/AlmaSettings.php b/src/includes/AlmaSettings.php index 28eddf29..218589b8 100644 --- a/src/includes/AlmaSettings.php +++ b/src/includes/AlmaSettings.php @@ -42,6 +42,9 @@ use Alma\Woocommerce\Helpers\FeePlanHelper; use Alma\Woocommerce\Helpers\InternationalizationHelper; use Alma\Woocommerce\Helpers\SettingsHelper; +use Exception; +use WC_Order; +use WP_User; /** * Handles settings retrieval from the settings API. @@ -56,7 +59,7 @@ * @property string display_product_eligibility Wp-bool-eq (yes or no) * @property string display_cart_eligibility Wp-bool-eq (yes or no) * @property string environment Live or test - * @property bool keys_validity Flag to indicate id the current keys are working + * @property bool keys_validity Flag to indicate id the current keys are working * @property string selected_fee_plan Admin dashboard fee_plan in edition mode. * @property string test_merchant_id Alma TEST merchant ID * @property string test_merchant_name Alma TEST merchant name @@ -65,12 +68,12 @@ * @property string variable_product_price_query_selector Css query selector * @property string variable_product_sale_price_query_selector Css query selector for variable discounted products * @property string variable_product_check_variations_event JS event for product variation change - * @property array excluded_products_list Wp Categories excluded slug's list + * @property array excluded_products_list Wp Categories excluded slug's list * @property string share_of_checkout_enabled Bool for share of checkout acceptance (yes or no) * @property string share_of_checkout_enabled_date String Date when the merchant did accept the share of checkout * @property string share_of_checkout_last_sharing_date String Date when we sent the data to Alma - * @property bool display_in_page Bool if In Page is activated - * @property bool use_blocks_template Bool if we want to use a blocks template + * @property bool display_in_page Bool if In Page is activated + * @property bool use_blocks_template Bool if we want to use a blocks template */ class AlmaSettings { @@ -182,15 +185,6 @@ public function load_settings() { } } - /** - * Is blocks template enabled. - * - * @return bool - */ - public function is_blocks_template_enabled() { - return 'yes' === $this->use_blocks_template; - } - /** * Retrieve the db settings. * @@ -206,6 +200,15 @@ public function get_settings() { return array_merge( $this->settings_helper->default_settings(), $settings ); } + /** + * Is blocks template enabled. + * + * @return bool + */ + public function is_blocks_template_enabled() { + return 'yes' === $this->use_blocks_template; + } + /** * __isset. * @@ -232,36 +235,6 @@ public function has_pay_later() { return false; } - /** - * Is the plan a pnx plus 4 ? - * - * @param FeePlan $fee_plan The fee plan. - * @return bool - */ - public function is_pnx_plus_4( $fee_plan ) { - if ( $fee_plan->getInstallmentsCount() > 4 ) { - return true; - } - - return false; - } - - /** - * Tells if the merchant has pay now payment method enabled in the WC back-office. - * - * @return bool - */ - public function has_pay_now() { - foreach ( $this->get_enabled_plans_definitions() as $plan_definition ) { - if ( 1 === $plan_definition['installments_count'] ) { - return true; - } - } - - return false; - } - - /** * Gets enabled plans and configuration summary stored in settings for each enabled plan. * @@ -389,28 +362,42 @@ public function get_deferred_months( $key ) { } /** - * Is plugin enabled. + * Is the plan a pnx plus 4 ? + * + * @param FeePlan $fee_plan The fee plan. * * @return bool */ - public function is_enabled() { - return 'yes' === $this->enabled; + public function is_pnx_plus_4( $fee_plan ) { + if ( $fee_plan->getInstallmentsCount() > 4 ) { + return true; + } + + return false; } /** - * Gets title for a payment method. - * - * @param string $payment_method The payment method. - * @param string $is_blocks Are we in blocks. + * Tells if the merchant has pay now payment method enabled in the WC back-office. * - * @return string + * @return bool */ - public function get_title( $payment_method, $is_blocks = false ) { - if ( $is_blocks ) { - return $this->get_i18n( 'title_blocks_' . $payment_method ); + public function has_pay_now() { + foreach ( $this->get_enabled_plans_definitions() as $plan_definition ) { + if ( 1 === $plan_definition['installments_count'] ) { + return true; + } } - return $this->get_i18n( 'title_' . $payment_method ); + return false; + } + + /** + * Is plugin enabled. + * + * @return bool + */ + public function is_enabled() { + return 'yes' === $this->enabled; } /** @@ -421,12 +408,12 @@ public function get_title( $payment_method, $is_blocks = false ) { * * @return string */ - public function get_description( $payment_method, $is_blocks = false ) { + public function get_title( $payment_method, $is_blocks = false ) { if ( $is_blocks ) { - return $this->get_i18n( 'description_blocks_' . $payment_method ); + return $this->get_i18n( 'title_blocks_' . $payment_method ); } - return $this->get_i18n( 'description_' . $payment_method ); + return $this->get_i18n( 'title_' . $payment_method ); } /** @@ -441,6 +428,7 @@ public function get_i18n( $key ) { if ( $this->{$key . '_' . get_locale()} ) { return $this->{$key . '_' . get_locale()}; } + return $this->internationalization_helper->get_translated_text( $this->settings_helper->default_settings()[ $key ], get_locale() @@ -451,21 +439,19 @@ public function get_i18n( $key ) { } /** - * Gets API string for the current environment. + * Gets title for a payment method. + * + * @param string $payment_method The payment method. + * @param string $is_blocks Are we in blocks. * * @return string */ - public function get_active_api_key() { - return $this->is_live() ? $this->get_live_api_key() : $this->get_test_api_key(); - } + public function get_description( $payment_method, $is_blocks = false ) { + if ( $is_blocks ) { + return $this->get_i18n( 'description_blocks_' . $payment_method ); + } - /** - * Is using live API. - * - * @return bool - */ - public function is_live() { - return $this->get_environment() === 'live'; + return $this->get_i18n( 'description_' . $payment_method ); } /** @@ -477,7 +463,6 @@ public function is_test() { return $this->get_environment() === 'test'; } - /** * Gets active environment from setting. * @@ -487,6 +472,36 @@ public function get_environment() { return 'live' === $this->environment ? 'live' : 'test'; } + /** + * Check if we have keys for the active environment. + * + * @return bool + */ + public function has_keys() { + if ( empty( $this->get_active_api_key() ) ) { + return false; + } + + return true; + } + + /** + * Gets API string for the current environment. + * + * @return string + */ + public function get_active_api_key() { + return $this->is_live() ? $this->get_live_api_key() : $this->get_test_api_key(); + } + + /** + * Is using live API. + * + * @return bool + */ + public function is_live() { + return $this->get_environment() === 'live'; + } /** * Gets API key for live environment. @@ -507,25 +522,24 @@ public function get_test_api_key() { } /** - * Check if we have keys for the active environment. + * Fetch the payment. * - * @return bool + * @param string $payment_id The payment id. + * + * @return Payment + * + * @throws ApiFetchPaymentsException Fetch payment exception. */ - public function has_keys() { - if ( empty( $this->get_active_api_key() ) ) { - return false; - } + public function fetch_payment( $payment_id ) { + try { + $this->get_alma_client(); - return true; - } + return $this->alma_client->payments->fetch( $payment_id ); - /** - * Saves settings. - * - * @return void - */ - public function save() { - update_option( self::OPTIONS_KEY, $this->settings ); + } catch ( Exception $e ) { + $this->logger->error( sprintf( 'Api fetch_payment, payment id "%s" , Api message "%s"', $payment_id, $e->getMessage() ) ); + throw new ApiFetchPaymentsException( $payment_id ); + } } /** @@ -560,34 +574,12 @@ public function get_alma_client() { ); } - /** - * Fetch the payment. - * - * @param string $payment_id The payment id. - * - * @return Payment - * - * @throws ApiFetchPaymentsException Fetch payment exception. - */ - public function fetch_payment( $payment_id ) { - try { - $this->get_alma_client(); - - return $this->alma_client->payments->fetch( $payment_id ); - - } catch ( \Exception $e ) { - $this->logger->error( sprintf( 'Api fetch_payment, payment id "%s" , Api message "%s"', $payment_id, $e->getMessage() ) ); - throw new ApiFetchPaymentsException( $payment_id ); - } - } - - /** * Create the payment. * - * @param array $payload The payload. - * @param \WC_Order $wc_order The order id. - * @param FeePlan $fee_plan The fee plan. + * @param array $payload The payload. + * @param WC_Order $wc_order The order id. + * @param FeePlan $fee_plan The fee plan. * * @return Payment * @@ -599,7 +591,7 @@ public function create_payment( $payload, $wc_order, $fee_plan ) { return $this->alma_client->payments->create( $payload ); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api create_payments, order id "%s" , Api message "%s", Payload "%s", Trace "%s"', @@ -616,7 +608,7 @@ public function create_payment( $payload, $wc_order, $fee_plan ) { /** * Share the data for soc. * - * @param array $data The payload. + * @param array $data The payload. * * @throws ApiShareOfCheckoutException ApiShareOfCheckoutException exception. */ @@ -626,7 +618,7 @@ public function send_soc_data( $data ) { $this->alma_client->shareOfCheckout->share( $data ); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api : shareOfCheckout, data : "%s", Api message "%s"', wp_json_encode( $data ), $e->getMessage() ) ); throw new ApiShareOfCheckoutException( $data ); } @@ -644,13 +636,12 @@ public function get_soc_last_updated_date() { $this->get_alma_client(); return $this->alma_client->shareOfCheckout->getLastUpdateDates(); // phpcs:ignore - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api : getLastUpdateDates shareOfCheckout, Api message "%s"', $e->getMessage() ) ); throw new ApiSocLastUpdateDatesException(); } } - /** * Sent the accept for the soc consent * @@ -662,7 +653,7 @@ public function accept_soc_consent() { $this->alma_client->shareOfCheckout->addConsent(); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api : accept share of shareOfCheckout, Api message "%s"', $e->getMessage() ) ); throw new ApiShareOfCheckoutAcceptException(); } @@ -679,13 +670,12 @@ public function deny_soc_consent() { $this->alma_client->shareOfCheckout->removeConsent(); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api : deny share of shareOfCheckout, Api message "%s"', $e->getMessage() ) ); throw new ApiShareOfCheckoutDenyException(); } } - /** * Trigger the transaction. * @@ -701,7 +691,7 @@ public function trigger_payment( $transaction_id ) { return $this->alma_client->payments->trigger( $transaction_id ); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api trigger_payment, transaction id "%s" , Api message "%s"', $transaction_id, $e->getMessage() ) ); throw new ApiTriggerPaymentsException( $transaction_id ); } @@ -722,7 +712,7 @@ public function full_refund( $transaction_id, $merchant_reference, $comment ) { $this->get_alma_client(); $this->alma_client->payments->fullRefund( $transaction_id, $merchant_reference, $comment ); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api full_refund, transaction id "%s" , Api message "%s"', $transaction_id, $e->getMessage() ) ); throw new ApiFullRefundException( $transaction_id, $merchant_reference ); } @@ -744,7 +734,7 @@ public function partial_refund( $transaction_id, $amount, $merchant_reference, $ $this->get_alma_client(); $this->alma_client->payments->partialRefund( $transaction_id, $amount, $merchant_reference, $comment ); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( sprintf( 'Api partialRefund, transaction id "%s" , Api message "%s"', $transaction_id, $e->getMessage() ) ); throw new ApiPartialRefundException( $transaction_id, $merchant_reference, $amount ); } @@ -801,7 +791,7 @@ public function get_alma_merchant_id() { $merchant = $this->alma_client->merchants->me(); $this->{$this->environment . '_merchant_id'} = $merchant->id; $this->{$this->environment . '_merchant_name'} = $merchant->name; - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->__set( 'keys_validity', 'no' ); $this->save(); @@ -811,7 +801,7 @@ public function get_alma_merchant_id() { } throw new ApiMerchantsException( - // translators: %s: Error message. + // translators: %s: Error message. __( 'Alma encountered an error when fetching merchant status, please check your api keys or retry later.', 'alma-gateway-for-woocommerce' ), $e->getCode(), $e @@ -832,6 +822,15 @@ public function get_alma_merchant_id() { } } + /** + * Saves settings. + * + * @return void + */ + public function save() { + update_option( self::OPTIONS_KEY, $this->settings ); + } + /** * Get and manage the fee plans. * @@ -890,7 +889,7 @@ function ( $fee_plan ) { public function get_alma_fee_plans() { try { return $this->alma_client->merchants->feePlans( FeePlan::KIND_GENERAL, 'all', true ); - } catch ( \Exception $e ) { + } catch ( Exception $e ) { $this->logger->error( $e->getMessage(), $e->getTrace() ); } @@ -922,11 +921,11 @@ protected function is_allowed_fee_plan( FeePlan $fee_plan ) { /** * Is Alma available for this user ? * - * @param \WP_User $user The user roles which to test. + * @param WP_User $user The user roles which to test. * * @return bool */ - public function is_allowed_to_see_alma( \WP_User $user ) { + public function is_allowed_to_see_alma( WP_User $user ) { return in_array( 'administrator', $user->roles, true ) || 'live' === $this->get_environment(); } @@ -1003,7 +1002,7 @@ public function should_display_plan( $plan_key, $gateway_id ) { switch ( $gateway_id ) { case ConstantsHelper::GATEWAY_ID: case ConstantsHelper::GATEWAY_ID_IN_PAGE: - return in_array( + $display_plan = in_array( $this->get_installments_count( $plan_key ), array( 2, @@ -1012,24 +1011,26 @@ public function should_display_plan( $plan_key, $gateway_id ) { ), true ); + break; case ConstantsHelper::GATEWAY_ID_PAY_NOW: case ConstantsHelper::GATEWAY_ID_IN_PAGE_PAY_NOW: - return ( - $this->get_installments_count( $plan_key ) === 1 - && ( $this->get_deferred_days( $plan_key ) === 0 && $this->get_deferred_months( $plan_key ) === 0 ) - ); + $display_plan = $this->get_installments_count( $plan_key ) === 1 + && ( $this->get_deferred_days( $plan_key ) === 0 && $this->get_deferred_months( $plan_key ) === 0 ); + break; case ConstantsHelper::GATEWAY_ID_PAY_LATER: case ConstantsHelper::GATEWAY_ID_IN_PAGE_PAY_LATER: - return ( - $this->get_installments_count( $plan_key ) === 1 - && ( $this->get_deferred_days( $plan_key ) !== 0 || $this->get_deferred_months( $plan_key ) !== 0 ) - ); + $display_plan = $this->get_installments_count( $plan_key ) === 1 + && ( $this->get_deferred_days( $plan_key ) !== 0 || $this->get_deferred_months( $plan_key ) !== 0 ); + break; case ConstantsHelper::GATEWAY_ID_IN_PAGE_MORE_THAN_FOUR: case ConstantsHelper::GATEWAY_ID_MORE_THAN_FOUR: - return ( $this->get_installments_count( $plan_key ) > 4 ); + $display_plan = $this->get_installments_count( $plan_key ) > 4; + break; default: - return false; + $display_plan = false; } + + return $display_plan; } /** @@ -1058,7 +1059,7 @@ public function get_display_text() { } /** - /** + * /** * Populate fee plan * * @param string $plan_key The plan key. @@ -1080,15 +1081,13 @@ public function build_fee_plan( $plan_key ) { throw new PlansDefinitionException( "deferred_months_$plan_key not set" ); } - $fee_plan = new FeePlan( + return new FeePlan( array( 'installments_count' => $this->settings[ "installments_count_$plan_key" ], 'deferred_days' => $this->settings[ "deferred_days_$plan_key" ], 'deferred_months' => $this->settings[ "deferred_months_$plan_key" ], ) ); - - return $fee_plan; } diff --git a/src/includes/Helpers/CartHelper.php b/src/includes/Helpers/CartHelper.php index 359d6c01..d6ac8dc6 100644 --- a/src/includes/Helpers/CartHelper.php +++ b/src/includes/Helpers/CartHelper.php @@ -14,10 +14,10 @@ use Alma\API\Endpoints\Results\Eligibility; use Alma\Woocommerce\AlmaLogger; use Alma\Woocommerce\AlmaSettings; -use Alma\Woocommerce\Exceptions\AlmaException; use Alma\Woocommerce\Factories\CartFactory; use Alma\Woocommerce\Factories\SessionFactory; use Alma\Woocommerce\Factories\VersionFactory; +use Exception; if ( ! defined( 'ABSPATH' ) ) { die( 'Not allowed' ); // Exit if accessed directly. @@ -27,7 +27,6 @@ * Class CartHelper. */ class CartHelper { - /** * Helper global. * @@ -109,48 +108,27 @@ public function __construct( $tools_helper, $session_factory, $version_factory, } /** - * Get cart total in cents. + * Get eligible plans keys for current cart. * - * @return integer - * @see alma_price_to_cents() - * @see get_total_from_cart - */ - public function get_total_in_cents() { - return $this->tools_helper->alma_price_to_cents( $this->get_total_from_cart() ); - } - - /** - * Gets total from wc cart depending on which wc version is running. + * @param array|Eligibility[] $cart_eligibilities The eligibilities. * - * @return float + * @return array */ - public function get_total_from_cart() { - $cart = $this->cart_factory->get_cart(); - - if ( ! $cart ) { - return 0; - } - - if ( version_compare( $this->version_factory->get_version(), '3.2.0', '<' ) ) { - return $cart->total; + public function get_eligible_plans_keys_for_cart( $cart_eligibilities = array() ) { + if ( empty( $cart_eligibilities ) ) { + $cart_eligibilities = $this->get_cart_eligibilities(); } - $total = $cart->get_total( null ); - - $session = $this->session_factory->get_session(); - $session_total = $session->get( 'cart_totals', null ); - - if ( - ( - 0 === $total - || '0' === $total - ) - && ! empty( $session_total['total'] ) - ) { - $total = $session_total['total']; - } + return array_filter( + $this->alma_settings->get_eligible_plans_keys( $this->get_total_in_cents() ), + function ( $key ) use ( $cart_eligibilities ) { + if ( is_array( $cart_eligibilities ) ) { + return array_key_exists( $key, $cart_eligibilities ); + } - return $total; + return property_exists( $cart_eligibilities, $key ); + } + ); } /** @@ -172,7 +150,7 @@ public function get_cart_eligibilities() { $this->alma_settings->get_alma_client(); $payload = $this->get_eligibility_payload_from_cart(); $this->eligibilities = $this->alma_settings->alma_client->payments->eligibility( $payload ); - } catch ( \Exception $error ) { + } catch ( Exception $error ) { $this->alma_logger->error( $error->getMessage(), $error->getTrace() ); return array(); @@ -189,55 +167,48 @@ public function get_cart_eligibilities() { } /** - * Get eligible plans keys for current cart. + * Get cart total in cents. * - * @param array|Eligibility[] $cart_eligibilities The eligibilities. - * @return array + * @return integer + * @see alma_price_to_cents() + * @see get_total_from_cart */ - public function get_eligible_plans_keys_for_cart( $cart_eligibilities = array() ) { - if ( empty( $cart_eligibilities ) ) { - $cart_eligibilities = $this->get_cart_eligibilities(); - } - - $eligibilities = array_filter( - $this->alma_settings->get_eligible_plans_keys( $this->get_total_in_cents() ), - function ( $key ) use ( $cart_eligibilities ) { - if ( is_array( $cart_eligibilities ) ) { - return array_key_exists( $key, $cart_eligibilities ); - } - - return property_exists( $cart_eligibilities, $key ); - } - ); - - return $eligibilities; + public function get_total_in_cents() { + return $this->tools_helper->alma_price_to_cents( $this->get_total_from_cart() ); } /** - * Get Eligibility / Payment formatted eligible plans definitions for current cart. + * Gets total from wc cart depending on which wc version is running. * - * @return array + * @return float */ - public function get_eligible_plans_for_cart() { - $amount = $this->get_total_in_cents(); + public function get_total_from_cart() { + $cart = $this->cart_factory->get_cart(); - return array_values( - array_map( - function ( $plan ) use ( $amount ) { - unset( $plan['max_amount'] ); - unset( $plan['min_amount'] ); - if ( isset( $plan['deferred_months'] ) && 0 === $plan['deferred_months'] ) { - unset( $plan['deferred_months'] ); - } - if ( isset( $plan['deferred_days'] ) && 0 === $plan['deferred_days'] ) { - unset( $plan['deferred_days'] ); - } + if ( ! $cart ) { + return 0; + } - return $plan; - }, - $this->alma_settings->get_eligible_plans_definitions( $amount ) + if ( version_compare( $this->version_factory->get_version(), '3.2.0', '<' ) ) { + return $cart->total; + } + + $total = $cart->get_total( null ); + + $session = $this->session_factory->get_session(); + $session_total = $session->get( 'cart_totals', null ); + + if ( + ( + 0 === $total + || '0' === $total ) - ); + && ! empty( $session_total['total'] ) + ) { + $total = $session_total['total']; + } + + return $total; } /** @@ -265,4 +236,31 @@ public function get_eligibility_payload_from_cart() { return $data; } + + /** + * Get Eligibility / Payment formatted eligible plans definitions for current cart. + * + * @return array + */ + public function get_eligible_plans_for_cart() { + $amount = $this->get_total_in_cents(); + + return array_values( + array_map( + function ( $plan ) { + unset( $plan['max_amount'] ); + unset( $plan['min_amount'] ); + if ( isset( $plan['deferred_months'] ) && 0 === $plan['deferred_months'] ) { + unset( $plan['deferred_months'] ); + } + if ( isset( $plan['deferred_days'] ) && 0 === $plan['deferred_days'] ) { + unset( $plan['deferred_days'] ); + } + + return $plan; + }, + $this->alma_settings->get_eligible_plans_definitions( $amount ) + ) + ); + } }