diff --git a/.circleci/phpstan/mocks/unirgy_giftcert_helper_data.mock b/.circleci/phpstan/mocks/unirgy_giftcert_helper_data.mock new file mode 100644 index 000000000..1e32f590d --- /dev/null +++ b/.circleci/phpstan/mocks/unirgy_giftcert_helper_data.mock @@ -0,0 +1,4 @@ +getMessage())); + throw new LocalizedException(__('Gateway error: %1', $e->getMessage())); /** @phpstan-ignore-line */ } if ($request->getStatusOnly() && $response) { @@ -252,7 +252,7 @@ public function sendRequest($request) $resultFromJSON = ApiUtils::getJSONFromResponseBody($responseBody); $result->setResponse($resultFromJSON); } else { - throw new LocalizedException(__('Something went wrong in the payment gateway.')); + throw new LocalizedException(__('Something went wrong in the payment gateway.')); /** @phpstan-ignore-line */ } return $result; } @@ -260,7 +260,7 @@ public function sendRequest($request) /** * Build request * - * @param DataObject $requestData + * @param DataObject|mixed $requestData * * @return Request */ diff --git a/Helper/AutomatedTesting.php b/Helper/AutomatedTesting.php index 440c1694f..d2132571c 100644 --- a/Helper/AutomatedTesting.php +++ b/Helper/AutomatedTesting.php @@ -341,6 +341,7 @@ protected function getProduct($type) $searchCriteria = $searchCriteriaBuilder->create(); $products = $this->productRepository->getList($searchCriteria)->getItems(); + /** @var Product $product */ foreach ($products as $product) { if ($this->stockRegistry->getStockItem($product->getId())->getIsInStock() && ( $type !== 'sale' || diff --git a/Helper/Bugsnag.php b/Helper/Bugsnag.php index ad0113966..f6a4cd7b0 100644 --- a/Helper/Bugsnag.php +++ b/Helper/Bugsnag.php @@ -20,7 +20,6 @@ use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Bolt\Boltpay\Helper\Config as ConfigHelper; -use Magento\Framework\Filesystem\DirectoryList; use Magento\Store\Model\StoreManagerInterface; use Bolt\Boltpay\Helper\Log as BoltLogger; @@ -38,7 +37,7 @@ class Bugsnag extends AbstractHelper const STAGE_TEST = 'test'; /** - * @var BugsnagClient + * @var \Bugsnag\Client */ private $bugsnag; @@ -59,14 +58,12 @@ class Bugsnag extends AbstractHelper * Bugsnag constructor. * @param Context $context * @param Config $configHelper - * @param DirectoryList $directoryList * @param StoreManagerInterface $storeManager * @param BoltLogger $boltLogger */ public function __construct( Context $context, ConfigHelper $configHelper, - DirectoryList $directoryList, StoreManagerInterface $storeManager, BoltLogger $boltLogger ) { @@ -99,7 +96,7 @@ public function __construct( /** * Notify Bugsnag of a non-fatal/handled throwable. * - * @param \Throwable $throwable the throwable to notify Bugsnag about + * @param mixed $throwable the throwable to notify Bugsnag about * @param callable|null $callback the customization callback * * @return void diff --git a/Helper/Cart.php b/Helper/Cart.php index bff9e1f94..55fb67a35 100644 --- a/Helper/Cart.php +++ b/Helper/Cart.php @@ -31,6 +31,8 @@ use Bolt\Boltpay\Model\Response; use Magento\Catalog\Helper\ImageFactory; use Magento\Catalog\Model\Config\Source\Product\Thumbnail as ThumbnailSource; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Configuration\Item\Option\OptionInterface; use Magento\Catalog\Model\ProductRepository; use Magento\Checkout\Helper\Data as CheckoutHelper; use Magento\Customer\Api\CustomerRepositoryInterface as CustomerRepository; @@ -97,7 +99,7 @@ class Cart extends AbstractHelper /** @var CartInterface */ private $lastImmutableQuote = null; - /** @var CheckoutSession */ + /** @var CheckoutSession|mixed */ private $checkoutSession; /** @var CustomerSession */ @@ -129,7 +131,7 @@ class Cart extends AbstractHelper private $bugsnag; /** - * @var DataObjectFactory + * @var DataObjectFactory|mixed */ private $dataObjectFactory; @@ -287,7 +289,7 @@ class Cart extends AbstractHelper private $quoteIdMaskResourceModel; /** - * @var QuoteIdMaskFactory + * @var QuoteIdMaskFactory|mixed */ private $quoteIdMaskFactory; @@ -417,7 +419,7 @@ public function isCheckoutAllowed() /** * Load Quote by id * @param $quoteId - * @return \Magento\Quote\Model\Quote|false + * @return \Magento\Quote\Model\Quote|false|mixed */ public function getQuoteById($quoteId) { @@ -458,7 +460,7 @@ public function getActiveQuoteById($quoteId) * @param string $incrementId * @param bool $forceLoad - use it if needed to load data without cache. * - * @return OrderInterface|false + * @return OrderInterface|mixed */ public function getOrderByIncrementId($incrementId, $forceLoad = false) { @@ -687,7 +689,7 @@ protected function getCartCacheIdentifier($cart) } /** - * @param Quote $immutableQuote + * @param Quote|mixed $immutableQuote * @return string */ protected function convertExternalFieldsToCacheIdentifier($immutableQuote) @@ -804,7 +806,7 @@ public function getImmutableQuoteIdFromBoltOrder($response) * Get the id of the quote Bolt order was created for * The same as getImmutableQuoteIdFromBoltOrder but cart is in array format * - * @param Response $boltOrder + * @param Response $boltCart * @return mixed */ public function getImmutableQuoteIdFromBoltCartArray($boltCart) @@ -898,7 +900,7 @@ public function getBoltpayOrder($paymentOnly, $placeOrderPayload = null, $storeI if ($this->doesOrderExist($cart, $quote)) { $this->deactivateSessionQuote($quote); throw new LocalizedException( - __('Order was created. Please reload the page and try again') + __('Order was created. Please reload the page and try again') /** @phpstan-ignore-line */ ); } @@ -918,6 +920,7 @@ public function getBoltpayOrder($paymentOnly, $placeOrderPayload = null, $storeI if ($boltOrderData = $this->loadFromCache($cacheIdentifier)) { // re-create response object from the cached response + /** @var Response|mixed $boltOrder */ $boltOrder = new Response( [ 'store_id' => $boltOrderData['store_id'], @@ -1035,7 +1038,6 @@ private function getSignResponse($signRequest, $storeId = null) */ public function getHints($cartReference = null, $checkoutType = 'admin') { - /** @var Quote */ if ($checkoutType != 'product') { $quote = $cartReference ? $this->getQuoteById($cartReference) : @@ -1097,6 +1099,7 @@ public function getHints($cartReference = null, $checkoutType = 'admin') $signRequest = [ 'merchant_user_id' => $customer->getId(), ]; + /** @var Response|mixed $signResponse */ $signResponse = $this->getSignResponse( $signRequest, $quote ? $quote->getStoreId() : null @@ -1226,6 +1229,7 @@ public function replicateQuoteData($source, $destination) $destination->removeAllItems(); foreach ($source->getAllVisibleItems() as $item) { + /** @var \Magento\Quote\Model\Quote\Item|mixed $item */ $newItem = clone $item; $destination->addItem($newItem); if ($item->getHasChildren()) { @@ -1236,11 +1240,14 @@ public function replicateQuoteData($source, $destination) } } } + /** @var \Magento\Quote\Model\Quote\Address|mixed $destinationBillingAddress */ + $destinationBillingAddress = $destination->getBillingAddress(); + $destinationBillingAddress->setShouldIgnoreValidation(true); + $this->transferData($source->getBillingAddress(), $destinationBillingAddress); - $destination->getBillingAddress()->setShouldIgnoreValidation(true); - $this->transferData($source->getBillingAddress(), $destination->getBillingAddress()); - - $destination->getShippingAddress()->setShouldIgnoreValidation(true); + /** @var \Magento\Quote\Model\Quote\Address|mixed $destinationShippingAddress */ + $destinationShippingAddress = $destination->getShippingAddress(); + $destinationShippingAddress->setShouldIgnoreValidation(true); $this->transferData($source->getShippingAddress(), $destination->getShippingAddress()); $this->transferData($source, $destination, false); @@ -1263,8 +1270,8 @@ public function replicateQuoteData($source, $destination) * Reason: Some 3rd party plugins read this value and if set * consider the quote to be a complete order. * - * @param Quote $immutableQuote - * @param Quote $quote + * @param Quote|mixed $immutableQuote + * @param Quote|mixed $quote * @throws \Magento\Framework\Exception\AlreadyExistsException */ protected function reserveOrderId($immutableQuote, $quote) @@ -1286,7 +1293,7 @@ protected function reserveOrderId($immutableQuote, $quote) * Set the BoltParentQuoteId to the parent quote, if not set already, * so it can be replicated to immutable quote in replicateQuoteData. * - * @param Quote $quote + * @param Quote|mixed $quote * @return Quote * @throws \Magento\Framework\Exception\AlreadyExistsException */ @@ -1366,6 +1373,7 @@ private function getAdditionalAttributes($sku, $storeId, $additionalAttributes) return []; } try { + /** @var Product $product */ $product = $this->productRepository->get($sku, false, $storeId); } catch (NoSuchEntityException $e) { $this->bugsnag->notifyException($e); @@ -1691,7 +1699,7 @@ function ($item) use ($imageHelper, &$totalAmount, &$diff, $isOrder, $storeId, $ /** * Return the selected customizable options of quote item. * - * @param Quote/Item $item + * @param Quote\Item $item * * @return array */ @@ -1705,8 +1713,10 @@ public function getProductCustomizableOptions($item) $customizableOptions = []; $product = $item->getProduct(); foreach (explode(',', ($optionIds->getValue() ?: '')) as $optionId) { + /** @var Product\Option|mixed $option */ $option = $product->getOptionById($optionId); if ($option) { + /** @var OptionInterface|mixed $confItemOption */ $confItemOption = $product->getCustomOption(\Magento\Catalog\Model\Product\Type\AbstractType::OPTION_PREFIX . $optionId); $itemOption = $item->getOptionByCode(\Magento\Catalog\Model\Product\Type\AbstractType::OPTION_PREFIX . $option->getId()); $group = $option->groupFactory($option->getType()) @@ -1779,6 +1789,7 @@ private function getProductToGetImageForConfigurableItem($item) $parentProduct = $item->getProduct(); /** @var \Magento\Quote\Model\Quote\Item\Option $option */ $option = $item->getOptionByCode('simple_product'); + /** @var Product|mixed $childProduct */ $childProduct = $option ? $option->getProduct() : $parentProduct; $configValue = $this->configHelper->getScopeConfig()->getValue( 'checkout/cart/configurable_product_image', @@ -1863,7 +1874,7 @@ protected function getCalculationAddress($quote) * @param bool $paymentOnly flag that represents the type of checkout * @param string|null $placeOrderPayload additional data collected from the (one page checkout) page, * i.e. billing address to be saved with the order - * @param Quote|null $immutableQuote If passed do not create new clone, get data existing one data. + * @param Quote|mixed $immutableQuote If passed do not create new clone, get data existing one data. * discount validation, bugsnag report * * @return array @@ -1874,7 +1885,7 @@ public function getCartData($paymentOnly, $placeOrderPayload = null, $immutableQ // If the immutable quote is passed (i.e. discount code validation, bugsnag report generation) // load the parent quote, otherwise load the session quote - /** @var Quote $quote */ + /** @var Quote|mixed $quote */ $quote = ($immutableQuote && $immutableQuote->getBoltParentQuoteId() != $immutableQuote->getId()) ? $this->getQuoteById($immutableQuote->getBoltParentQuoteId()) : $this->checkoutSession->getQuote(); @@ -2114,7 +2125,7 @@ public function buildCartFromQuote($parentQuote, $immutableQuote, $items, $place ); throw new LocalizedException( - __('Billing address is missing. Please input all required fields in billing address form and try again') + __('Billing address is missing. Please input all required fields in billing address form and try again') /** @phpstan-ignore-line */ ); } } else { @@ -2130,7 +2141,7 @@ public function buildCartFromQuote($parentQuote, $immutableQuote, $items, $place ); throw new LocalizedException( - __('Shipping method is missing. Please select shipping method and try again') + __('Shipping method is missing. Please select shipping method and try again') /** @phpstan-ignore-line */ ); } @@ -2152,7 +2163,7 @@ public function buildCartFromQuote($parentQuote, $immutableQuote, $items, $place ); throw new LocalizedException( - __('Billing address is missing. Please input all required fields in billing address form and try again') + __('Billing address is missing. Please input all required fields in billing address form and try again') /** @phpstan-ignore-line */ ); } @@ -2205,7 +2216,7 @@ public function buildCartFromQuote($parentQuote, $immutableQuote, $items, $place ); throw new LocalizedException( - __('Shipping address is missing. Please input all required fields in shipping address form and try again') + __('Shipping address is missing. Please input all required fields in shipping address form and try again') /** @phpstan-ignore-line */ ); } } @@ -2266,11 +2277,8 @@ public function buildCartFromQuote($parentQuote, $immutableQuote, $items, $place } /** - * Email validator - * - * @param string $email + * @param $email * @return bool - * @throws \Magento\Framework\Validator\ValidateException */ public function validateEmail($email) { @@ -2302,8 +2310,8 @@ protected function getWebsiteId() * * @param int $totalAmount * @param float $diff - * @param AddressTotal[] $totals * @param bool $paymentOnly + * @param Quote|mixed $quote * @return array * @throws NoSuchEntityException */ @@ -2360,7 +2368,7 @@ public function collectDiscounts( } $discounts[] = [ 'rule_id' => $rule->getRuleId(), - 'description' => trim(__('Discount ') . $description), + 'description' => trim(__('Discount ') . $description), /** @phpstan-ignore-line */ 'amount' => $roundedAmount, 'discount_category' => Discount::BOLT_DISCOUNT_CATEGORY_AUTO_PROMO, 'discount_type' => $discountType, // For v1/discounts.code.apply and v2/cart.update @@ -2485,6 +2493,7 @@ public function collectDiscounts( // Process other discounts, stored in totals array ///////////////////////////////////////////////////////////////////////////////// foreach ($this->discountTypes as $discount => $description) { + /** @var mixed $totalDiscount */ $totalDiscount = $totals[$discount] ?? null; if ($totalDiscount && $amount = $totalDiscount->getValue()) { $roundedDiscountAmount = 0; @@ -2580,7 +2589,6 @@ private function handlePuertoRico($addressData) * Properties are checked with getters specified in configuration. * * @param Quote|null $quote - * @param null|int $storeId * * @return bool * @throws NoSuchEntityException @@ -2607,8 +2615,8 @@ public function hasProductRestrictions($quote = null) return false; } + /** @var \Magento\Quote\Model\Quote\Item $item */ foreach ($quote->getAllVisibleItems() as $item) { - /** @var \Magento\Quote\Model\Quote\Item $item */ // call every method on item, if returns true, do restrict foreach ($itemRestrictionMethods as $method) { if ($item->$method()) { @@ -2688,8 +2696,8 @@ public function createCartByRequest($request) public function createCart($items, $metadata = null, $storeId = null) { $quoteId = $this->quoteManagement->createEmptyCart(); + /** @var Quote|mixed $quote */ $quote = $this->quoteFactory->create()->load($quoteId); - $quote->setBoltParentQuoteId($quoteId); $quote->setBoltCheckoutType(self::BOLT_CHECKOUT_TYPE_PPC); @@ -2723,13 +2731,13 @@ public function createCart($items, $metadata = null, $storeId = null) $error_message = $e->getMessage(); if ($error_message == 'Product that you are trying to add is not available.') { throw new BoltException( - __($error_message), + __($error_message), /** @phpstan-ignore-line */ null, BoltErrorResponse::ERR_PPC_OUT_OF_STOCK ); } else { throw new BoltException( - __('The requested qty is not available'), + __('The requested qty is not available'), /** @phpstan-ignore-line */ null, BoltErrorResponse::ERR_PPC_INVALID_QUANTITY ); @@ -2762,7 +2770,7 @@ private function assignQuoteCustomerByEncryptedUserId($quote, $encrypted_user_id { $metadata = json_decode((string)$encrypted_user_id); if (! $metadata || ! isset($metadata->user_id) || ! isset($metadata->timestamp) || ! isset($metadata->signature)) { - throw new WebapiException(__('Incorrect encrypted_user_id'), 6306, 422); + throw new WebapiException(__('Incorrect encrypted_user_id'), 6306, 422); /** @phpstan-ignore-line */ } $payload = [ @@ -2771,17 +2779,17 @@ private function assignQuoteCustomerByEncryptedUserId($quote, $encrypted_user_id ]; if (!$this->hookHelper->verifySignature(json_encode($payload), $metadata->signature)) { - throw new WebapiException(__('Incorrect signature'), 6306, 422); + throw new WebapiException(__('Incorrect signature'), 6306, 422); /** @phpstan-ignore-line */ } if (time() - $metadata->timestamp > 3600) { - throw new WebapiException(__('Outdated encrypted_user_id'), 6306, 422); + throw new WebapiException(__('Outdated encrypted_user_id'), 6306, 422); /** @phpstan-ignore-line */ } try { $customer = $this->customerRepository->getById($metadata->user_id); } catch (\Exception $e) { - throw new WebapiException(__('Incorrect user_id'), 6306, 422); + throw new WebapiException(__('Incorrect user_id'), 6306, 422); /** @phpstan-ignore-line */ } $quote->assignCustomer($customer); // Assign quote to Customer } @@ -2793,13 +2801,14 @@ public function calculateCartAndHints($paymentOnly = false, $placeOrderPayload = try { if ($this->hasProductRestrictions()) { - throw new BoltException(__('The cart has products not allowed for Bolt checkout')); + throw new BoltException(__('The cart has products not allowed for Bolt checkout')); /** @phpstan-ignore-line */ } if (! $this->isCheckoutAllowed()) { - throw new BoltException(__('Guest checkout is not allowed.')); + throw new BoltException(__('Guest checkout is not allowed.')); /** @phpstan-ignore-line */ } + /** @var Response|mixed $boltpayOrder */ // call the Bolt API $boltpayOrder = $this->getBoltpayOrder($paymentOnly, $placeOrderPayload); @@ -2915,7 +2924,7 @@ public function getCustomerByEmail($email, $websiteId = null) /** * Collect address total. * - * @param \Magento\Quote\Model\Quote $quote + * @param \Magento\Quote\Model\Quote|mixed $quote * @param \Magento\Quote\Model\Quote\Address $address * */ @@ -3029,10 +3038,15 @@ public function getSaleRuleDiscounts($quote) $saleRuleDiscountsDetails = []; // If the Magento version < 2.3.4, we still collect discounts details via plugin methods. if ($this->isCollectDiscountsByPlugin($quote)) { - $saleRuleDiscountsDetails = $this->sessionHelper->getCheckoutSession()->getBoltCollectSaleRuleDiscounts([]); + /** @var CheckoutSession|mixed $checkoutSession */ + $checkoutSession = $this->sessionHelper->getCheckoutSession(); + $saleRuleDiscountsDetails = $checkoutSession->getBoltCollectSaleRuleDiscounts([]); } else { - /* @var \Magento\SalesRule\Api\Data\RuleDiscountInterface $ruleDiscounts */ - $extensionSaleRuleDiscounts = $address->getExtensionAttributes()->getDiscounts(); + /** @var \Magento\Quote\Api\Data\AddressExtensionInterface|mixed $addressExtensionAttribute */ + $addressExtensionAttribute = $address->getExtensionAttributes(); + /* @var \Magento\SalesRule\Api\Data\RuleDiscountInterface $extensionSaleRuleDiscounts */ + $extensionSaleRuleDiscounts = $addressExtensionAttribute->getDiscounts(); + /** @var mixed $cartFixedRules */ $cartFixedRules = $address->getCartFixedRules(); if ($extensionSaleRuleDiscounts && is_array($extensionSaleRuleDiscounts)) { foreach ($extensionSaleRuleDiscounts as $value) { diff --git a/Helper/CheckboxesHandler.php b/Helper/CheckboxesHandler.php index 54c23adac..43975917a 100644 --- a/Helper/CheckboxesHandler.php +++ b/Helper/CheckboxesHandler.php @@ -45,8 +45,8 @@ class CheckboxesHandler extends AbstractHelper /** * @param Context $context - * @param OrderHelper $orderHelper * @param Bugsnag $bugsnag + * @param SubscriberFactory $subscriberFactory */ public function __construct( Context $context, @@ -61,7 +61,7 @@ public function __construct( /** * Handle checkboxes * - * @param OrderModel $order + * @param \Magento\Sales\Model\Order $order * @param array $checkboxes */ public function handle($order, $checkboxes) @@ -95,7 +95,7 @@ public function handle($order, $checkboxes) * - If order for logged in user subscribe by userId * - If order for guest user subscribe by email * - * @param OrderModel $order + * @param \Magento\Sales\Model\Order $order */ public function subscribeToNewsletter($order) { diff --git a/Helper/Config.php b/Helper/Config.php index 326416aa6..f9b96f65a 100644 --- a/Helper/Config.php +++ b/Helper/Config.php @@ -1586,7 +1586,9 @@ public function getClientIp() 'HTTP_FORWARDED', 'REMOTE_ADDR' ] as $key) { - if ($ips = $this->_request->getServer($key, false)) { + /** @var \Magento\Framework\App\Request\Http $request */ + $request = $this->_request; + if ($ips = $request->getServer($key, false)) { foreach (explode(',', $ips) as $ip) { $ip = trim($ip); // just to be safe if (filter_var( @@ -1858,7 +1860,7 @@ public function isGuestCheckoutForDownloadableProductDisabled() /** * Get all bolt configuration settings * - * @return BoltConfigSetting[] + * @return BoltConfigSettingFactory[] */ public function getAllConfigSettings() { @@ -2059,7 +2061,7 @@ public function getAllConfigSettings() // instant button variant field $boltSettings[] = $this->boltConfigSettingFactory->create() ->setName('instant_button_variant') - ->setValue($this->getInstantButtonVariant(), true); + ->setValue($this->getInstantButtonVariant()); // instant button variant field ppc $boltSettings[] = $this->boltConfigSettingFactory->create() ->setName('instant_button_variant_ppc') diff --git a/Helper/CustomFieldsHandler.php b/Helper/CustomFieldsHandler.php index c5fde1485..f1f7b676f 100644 --- a/Helper/CustomFieldsHandler.php +++ b/Helper/CustomFieldsHandler.php @@ -46,8 +46,8 @@ class CustomFieldsHandler extends AbstractHelper /** * @param Context $context - * @param OrderHelper $orderHelper * @param Bugsnag $bugsnag + * @param SubscriberFactory $subscriberFactory */ public function __construct( Context $context, @@ -62,7 +62,7 @@ public function __construct( /** * Handle custom fields * - * @param OrderModel $order + * @param \Magento\Sales\Model\Order $order * @param array $customFields */ public function handle($order, $customFields) @@ -94,7 +94,7 @@ public function handle($order, $customFields) * - If order for logged in user subscribe by userId * - If order for guest user subscribe by email * - * @param OrderModel $order + * @param \Magento\Sales\Model\Order $order */ public function subscribeToNewsletter($order) { diff --git a/Helper/Discount.php b/Helper/Discount.php index eb5a2977c..57f07df39 100644 --- a/Helper/Discount.php +++ b/Helper/Discount.php @@ -173,9 +173,9 @@ public function __construct( /** * Collect and update quote totals. - * @param Quote $quote + * @param Quote|mixed $quote */ - public function updateTotals(Quote $quote) + public function updateTotals($quote) { $quote->getShippingAddress()->setCollectShippingRates(true); $quote->setTotalsCollectedFlag(false); @@ -274,7 +274,7 @@ public function getUnirgyGiftCertBalanceByCode($giftcertCode) { $result = 0; - /** @var \Unirgy\Giftcert\Model\Cert $giftCert */ + /** @var \Unirgy\Giftcert\Model\Cert $unirgyInstance */ $unirgyInstance = $this->unirgyCertRepository->getInstance(); if ($unirgyInstance) { @@ -304,13 +304,11 @@ public function applyExternalDiscountData($quote) { $this->eventsForThirdPartyModules->dispatchEvent("applyExternalDiscountData", $quote); } - + /** - * Load the coupon data by code - * + * Load the coupon data by cod * @param $couponCode - * - * @return Coupon + * @return \Magento\SalesRule\Model\Coupon|mixed */ public function loadCouponCodeData($couponCode) { @@ -342,7 +340,7 @@ public function convertToBoltDiscountType($couponCode) } /** - * @param Magento\SalesRule\Model\Rule $rule + * @param \Magento\SalesRule\Model\Rule|mixed $rule * @return string */ public function getBoltDiscountType($rule) @@ -371,6 +369,7 @@ public function getBoltDiscountType($rule) */ public function setCouponCode($quote, $couponCode) { + /** @var Quote\Address|mixed $address */ $address = $quote->isVirtual() ? $quote->getBillingAddress() : $quote->getShippingAddress(); diff --git a/Helper/FeatureSwitch/Decider.php b/Helper/FeatureSwitch/Decider.php index e3a78826a..08a22effd 100644 --- a/Helper/FeatureSwitch/Decider.php +++ b/Helper/FeatureSwitch/Decider.php @@ -39,7 +39,7 @@ class Decider extends AbstractHelper private $_state; /** - * @var CoreSession + * @var CoreSession|mixed */ private $_session; @@ -135,7 +135,7 @@ public function isSwitchEnabled($switchName) { $defaultDef = Definitions::DEFAULT_SWITCH_VALUES[$switchName] ?? null; if (!$defaultDef) { - throw new LocalizedException(__("Unknown feature switch")); + throw new LocalizedException(__("Unknown feature switch")); /** @phpstan-ignore-line */ } $switch = null; try { diff --git a/Helper/FeatureSwitch/Manager.php b/Helper/FeatureSwitch/Manager.php index d2cf94a0a..4d1153f84 100644 --- a/Helper/FeatureSwitch/Manager.php +++ b/Helper/FeatureSwitch/Manager.php @@ -41,7 +41,7 @@ class Manager extends AbstractHelper private $gql; /** - * @var fsRepo + * @var FeatureSwitchRepository */ private $fsRepo; @@ -84,9 +84,9 @@ public function updateSwitchesFromBolt() if (isset($fs->name)) { $this->fsRepo->upsertByName( $fs->name, - $fs->value, - $fs->defaultValue, - $fs->rolloutPercentage + $fs->value, /** @phpstan-ignore-line */ + $fs->defaultValue, /** @phpstan-ignore-line */ + $fs->rolloutPercentage /** @phpstan-ignore-line */ ); } } diff --git a/Helper/Geolocation.php b/Helper/Geolocation.php index aa9178f17..6097efd35 100644 --- a/Helper/Geolocation.php +++ b/Helper/Geolocation.php @@ -45,7 +45,7 @@ class Geolocation extends AbstractHelper private $bugsnag; /** - * @var HttpClientAdapterFactory + * @var HttpClientAdapterFactory|mixed */ private $httpClientAdapterFactory; @@ -62,7 +62,7 @@ class Geolocation extends AbstractHelper * @param Context $context * @param Config $configHelper * @param Bugsnag $bugsnag - * @param HttpClientAdapterFactory $httpClientFactory + * @param HttpClientAdapterFactory $httpClientAdapterFactory * @param CacheInterface $cache */ public function __construct( diff --git a/Helper/GiftOptionsHandler.php b/Helper/GiftOptionsHandler.php index d71e27b53..7b8b646c0 100644 --- a/Helper/GiftOptionsHandler.php +++ b/Helper/GiftOptionsHandler.php @@ -50,7 +50,7 @@ public function __construct( /** * Handle gift options * - * @param OrderModel $order + * @param \Magento\Sales\Model\Order $order * @param \stdClass $transaction */ public function handle($order, $transaction) diff --git a/Helper/GraphQL/Client.php b/Helper/GraphQL/Client.php index 147c93866..e9d317486 100644 --- a/Helper/GraphQL/Client.php +++ b/Helper/GraphQL/Client.php @@ -43,7 +43,7 @@ class Client extends AbstractHelper const MERCHANT_API_GQL_ENDPOINT = 'v2/merchant/api'; /** - * @var HttpClientAdapterFactory + * @var HttpClientAdapterFactory|mixed */ private $httpClientAdapterFactory; @@ -60,7 +60,7 @@ class Client extends AbstractHelper /** * Response factory * - * @var ResponseFactory + * @var ResponseFactory|mixed */ private $responseFactory; @@ -167,19 +167,19 @@ private function makeGQLCall($query, $operation, $variables) ]); }); } catch (\Exception $e) { - throw new LocalizedException(__($e->getMessage())); + throw new LocalizedException(__($e->getMessage())); /** @phpstan-ignore-line */ } if ($responseBody) { try { $resultFromJSON = ApiUtils::getJSONFromResponseBody($responseBody); } catch (\Exception $e) { - throw new LocalizedException(__('Something went wrong when talking to Bolt.')); + throw new LocalizedException(__('Something went wrong when talking to Bolt.')); /** @phpstan-ignore-line */ } $result->setResponse($resultFromJSON); } else { - throw new LocalizedException(__('Something went wrong when talking to Bolt.')); + throw new LocalizedException(__('Something went wrong when talking to Bolt.')); /** @phpstan-ignore-line */ } return $result; } @@ -188,7 +188,6 @@ private function makeGQLCall($query, $operation, $variables) * This Method makes a call to Bolt and returns the feature switches and their values for this server with * its current version and the current merchant in question. * - * @return mixed * @throws LocalizedException */ public function getFeatureSwitches() diff --git a/Helper/Hook.php b/Helper/Hook.php index e05a2a44a..841968aa9 100644 --- a/Helper/Hook.php +++ b/Helper/Hook.php @@ -72,7 +72,7 @@ class Hook extends AbstractHelper private $request; /** - * @var DataObjectFactory + * @var DataObjectFactory|mixed */ private $dataObjectFactory; @@ -154,7 +154,7 @@ private function verifyWebhookApi($payload, $hmac_header) return false; } - return $result == 200; + return $result === 200; } /** @@ -213,7 +213,7 @@ public function verifyWebhook() $hmac_header = $this->request->getHeader(self::HMAC_HEADER); if (!$this->verifySignature($payload, $hmac_header) && !$this->verifyWebhookApi($payload, $hmac_header)) { - throw new WebapiException(__('Precondition Failed'), 6001, 412); + throw new WebapiException(__('Precondition Failed'), 6001, 412); /** @phpstan-ignore-line */ } } diff --git a/Helper/IntegrationManagement.php b/Helper/IntegrationManagement.php index ee1fddd5f..6cfc6af5b 100644 --- a/Helper/IntegrationManagement.php +++ b/Helper/IntegrationManagement.php @@ -17,6 +17,7 @@ namespace Bolt\Boltpay\Helper; +use Bolt\Boltpay\Model\Response; use Exception; use Magento\Config\Model\ResourceModel\Config as ResourceConfig; use Magento\Framework\App\Cache\TypeListInterface as Cache; @@ -101,17 +102,17 @@ class IntegrationManagement extends AbstractHelper protected $oauthService; /** - * @var Bolt\Boltpay\Helper\Bugsnag + * @var \Bolt\Boltpay\Helper\Bugsnag */ protected $bugsnag; /** - * @var Bolt\Boltpay\Helper\Config + * @var \Bolt\Boltpay\Helper\Config */ protected $configHelper; /** - * @var DataObjectFactory + * @var DataObjectFactory|mixed */ private $dataObjectFactory; @@ -126,7 +127,7 @@ class IntegrationManagement extends AbstractHelper protected $cache; /** - * @var HttpClientAdapterFactory + * @var HttpClientAdapterFactory|mixed */ protected $httpClientAdapterFactory; @@ -136,7 +137,7 @@ class IntegrationManagement extends AbstractHelper protected $dataHelper; /** - * @var Bolt\Boltpay\Helper\FeatureSwitch\Decider + * @var \Bolt\Boltpay\Helper\FeatureSwitch\Decider */ protected $deciderHelper; @@ -161,7 +162,8 @@ class IntegrationManagement extends AbstractHelper * @param DataObjectFactory $dataObjectFactory * @param ResourceConfig $resourceConfig * @param Cache $cache - * @param HttpClientAdapterFactory $httpClient + * @param HttpClientAdapterFactory $httpClientAdapterFactory + * @param IntegrationOauthHelper $dataHelper * @param DeciderHelper $deciderHelper * @param UrlInterface $urlBuilder * @param StoreManagerInterface $storeManager @@ -292,7 +294,7 @@ public function deleteMagentoIntegraion() $integrationData = $this->integrationService->delete($integrationId); if (!$integrationData[Info::DATA_ID]) { throw new Exception( - __('The Bolt integration no longer exists.') + __('The Bolt integration no longer exists.') /** @phpstan-ignore-line */ ); } else { //Integration deleted successfully, now safe to delete the associated consumer data @@ -303,7 +305,7 @@ public function deleteMagentoIntegraion() } } else { throw new Exception( - __('The Bolt integration no longer exists.') + __('The Bolt integration no longer exists.') /** @phpstan-ignore-line */ ); } } catch (Exception $e) { @@ -373,10 +375,7 @@ public function linkAccessTokenBoltMerchantAccountByOAuth($storeId = null) $consumer = $this->oauthService->loadConsumer($boltIntegration->getConsumerId()); if (!$consumer->getId()) { throw new Exception( - __( - 'A consumer with "%1" ID doesn\'t exist. Verify the ID and try again.', - $boltIntegration->getConsumerId() - ) + __('A consumer with "%1" ID doesn\'t exist. Verify the ID and try again.', $boltIntegration->getConsumerId()) /** @phpstan-ignore-line */ ); } @@ -412,7 +411,7 @@ private function prepareAndSendExchangeRequest($storeId, $consumer): bool if ( (method_exists($response, 'getStatus') && $response->getStatus() != 200) || (method_exists($response, 'getStatusCode') && $response->getStatusCode() != 200) ) { - $errorLog[$key . ' attempt'] = $response->getMessage(); + $errorLog[$key . ' attempt'] = $response->getMessage(); /** @phpstan-ignore-line */ } else { return true; } @@ -436,6 +435,7 @@ public function configureCallbackUrl(): array { $loginSuccessCallbackArray = []; $adminBaseUrl = $this->urlBuilder->getUrl(); + /** @var \Magento\Store\Model\Store $store */ foreach ($this->storeManager->getStores(true) as $store) { if (strpos($adminBaseUrl, $store->getBaseUrl()) === false) { $loginSuccessCallbackArray[] = $this->urlBuilder->getUrl( @@ -465,7 +465,7 @@ private function prepareErrorMessage($errorLog): \Magento\Framework\Phrase $errorDetails .= sprintf('%s: %s%s', $attempt, $errorMessage, PHP_EOL); } - return __( + return __( /** @phpstan-ignore-line */ 'An error occurred while processing token exchange: "%1".', $errorDetails ); diff --git a/Helper/JWT/JWT.php b/Helper/JWT/JWT.php index 5773a140a..3266cc483 100644 --- a/Helper/JWT/JWT.php +++ b/Helper/JWT/JWT.php @@ -136,7 +136,7 @@ public static function decode($jwt, $key, array $allowed_algs = []) } // Check the signature - if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { + if (!self::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { throw new SignatureInvalidException('Signature verification failed'); } @@ -267,7 +267,7 @@ public static function jsonDecode($input) } if ($errno = \json_last_error()) { - static::handleJsonError($errno); + self::handleJsonError($errno); } elseif ($obj === null && $input !== 'null') { throw new DomainException('Null result with non-null input'); } @@ -287,7 +287,7 @@ public static function jsonEncode($input) { $json = \json_encode($input); if ($errno = \json_last_error()) { - static::handleJsonError($errno); + self::handleJsonError($errno); } elseif ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } @@ -361,13 +361,13 @@ private static function verify($msg, $signature, $key, $alg) if (\function_exists('hash_equals')) { return \hash_equals($signature, $hash); } - $len = \min(static::safeStrlen($signature), static::safeStrlen($hash)); + $len = \min(self::safeStrlen($signature), self::safeStrlen($hash)); $status = 0; for ($i = 0; $i < $len; $i++) { $status |= (\ord($signature[$i]) ^ \ord($hash[$i])); } - $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); + $status |= (self::safeStrlen($signature) ^ self::safeStrlen($hash)); return $status === 0; } diff --git a/Helper/LogRetriever.php b/Helper/LogRetriever.php index ef287b8b5..ac66c3a1d 100644 --- a/Helper/LogRetriever.php +++ b/Helper/LogRetriever.php @@ -59,7 +59,7 @@ public function getLogs($logPath = self::DEFAULT_LOG_PATH, $lines = 100) /** * Function which returns the log of requested type if it exists. - * @param string $logType + * @param mixed $logType * @return array */ public function getLogOfType($logType){ diff --git a/Helper/Metric.php b/Helper/Metric.php index cb335392d..9025331d8 100644 --- a/Helper/Metric.php +++ b/Helper/Metric.php @@ -45,8 +45,7 @@ function __construct($key, $data) /** * Gets JSON for object - * - * @return JSON + * @return mixed */ public function getMetricJson() { diff --git a/Helper/MetricsClient.php b/Helper/MetricsClient.php index 1901df1df..2d4128531 100644 --- a/Helper/MetricsClient.php +++ b/Helper/MetricsClient.php @@ -85,7 +85,6 @@ class MetricsClient extends AbstractHelper /** * @param Context $context * @param Config $configHelper - * @param DirectoryList $directoryList * @param StoreManagerInterface $storeManager * @param Bugsnag $bugsnag * @param LogHelper $logHelper @@ -97,7 +96,6 @@ class MetricsClient extends AbstractHelper public function __construct( Context $context, ConfigHelper $configHelper, - DirectoryList $directoryList, StoreManagerInterface $storeManager, Bugsnag $bugsnag, LogHelper $logHelper, diff --git a/Helper/Order.php b/Helper/Order.php index 918350eea..b728c7a1f 100644 --- a/Helper/Order.php +++ b/Helper/Order.php @@ -24,6 +24,7 @@ use Bolt\Boltpay\Model\Api\CreateOrder; use Bolt\Boltpay\Model\Payment; use Bolt\Boltpay\Model\Response; +use Bolt\Boltpay\Model\WebhookLog; use Magento\Customer\Api\Data\GroupInterface; use Magento\Directory\Model\Region as RegionModel; use Magento\Framework\Api\SearchCriteriaBuilder; @@ -40,6 +41,7 @@ use Magento\Sales\Api\OrderRepositoryInterface as OrderRepository; use Magento\Sales\Model\AdminOrder\Create; use Magento\Sales\Model\Order as OrderModel; +use Magento\Sales\Model\Order\Creditmemo; use Magento\Sales\Model\Order\Email\Container\InvoiceIdentity as InvoiceEmailIdentity; use Magento\Sales\Model\Order\Email\Sender\InvoiceSender; use Magento\Sales\Model\Order\Email\Sender\OrderSender; @@ -189,7 +191,7 @@ class Order extends AbstractHelper private $orderRepository; /** - * @var DataObjectFactory + * @var DataObjectFactory|mixed */ private $dataObjectFactory; @@ -291,7 +293,7 @@ class Order extends AbstractHelper private $giftOptionsHandler; /** - * @var TransactionRepositoryInterface + * @var TransactionRepositoryInterface|mixed */ private $transactionRepository; @@ -417,7 +419,7 @@ public function __construct( * @param string $reference * @param $storeId * - * @return Response + * @return Response|mixed * @throws LocalizedException * * @api @@ -435,6 +437,7 @@ public function fetchTransactionInfo($reference, $storeId = null) //Build Request $request = $this->apiHelper->buildRequest($requestData, $storeId); + /** @var Response|mixed $result */ $result = $this->apiHelper->sendRequest($request); $response = $result->getResponse(); $this->transactionInfo[$reference] = $response; @@ -469,7 +472,7 @@ protected function setShippingMethod($quote, $transaction) /** * Set Quote address data helper method. * - * @param Address $quoteAddress + * @param Address|mixed $quoteAddress * @param $address * * @throws \Exception @@ -591,7 +594,7 @@ protected function addCustomerDetails($quote, $email, $transaction) /** * Set Quote payment method, 'boltpay' * - * @param Quote $quote + * @param Quote|mixed $quote * * @throws LocalizedException * @throws \Exception @@ -652,7 +655,7 @@ private function adjustTaxMismatch($transaction, $order, $quote) */ private function checkExistingOrder($parentQuoteId) { - /** @var OrderModel $order */ + /** @var $order */ if ($order = $this->getExistingOrder(null, $parentQuoteId)) { $this->bugsnag->notifyError( 'Duplicate Order Creation Attempt', @@ -693,11 +696,7 @@ protected function createOrder($immutableQuote, $transaction, $boltTraceId = nul throw $e; } if ($order === null) { - throw new LocalizedException(__( - 'Quote Submit Error. Parent Quote ID: %1 Immutable Quote ID: %2', - $quote->getId(), - $immutableQuote->getId() - )); + throw new LocalizedException(__('Quote Submit Error. Parent Quote ID: %1 Immutable Quote ID: %2', $quote->getId(), $immutableQuote->getId())); /** @phpstan-ignore-line */ } if (Hook::$fromBolt) { $order->addStatusHistoryComment( @@ -712,7 +711,7 @@ protected function createOrder($immutableQuote, $transaction, $boltTraceId = nul * Save additional order data and dispatch the after submit event * * @param OrderModel $order - * @param Quote $quote + * @param Quote|mixed $quote * @param \stdClass $transaction */ protected function orderPostprocess($order, $quote, $transaction) @@ -740,7 +739,7 @@ protected function orderPostprocess($order, $quote, $transaction) // Save reference to the Bolt transaction with the order if (isset($transaction->reference)) { $order->addStatusHistoryComment( - __('Bolt transaction: %1', $this->formatReferenceUrl($transaction->reference)) + __('Bolt transaction: %1', $this->formatReferenceUrl($transaction->reference)) /** @phpstan-ignore-line */ ); } // Add the user_note to the order comments and make it visible for the customer. @@ -795,7 +794,7 @@ private function adjustPriceMismatch($transaction, $order, $quote) /** * Assign data to the order payment instance * - * @param OrderPaymentInterface $payment + * @param \Magento\Sales\Model\Order\Payment $payment * @param \stdClass $transaction * @return void */ @@ -863,7 +862,7 @@ public function setOrderPaymentInfoData($payment, $transaction) /** * Delete redundant immutable quotes. * - * @param Quote $quote + * @param Quote|mixed $quote */ private function deleteRedundantQuotes($quote) { @@ -888,7 +887,6 @@ private function deleteRedundantQuotes($quote) * Required for the order to be imported by some ERP systems. * * @param OrderModel $order - * @param string $state */ public function resetOrderState($order) { @@ -913,7 +911,7 @@ public function verifyOrderCreationHookType($hookType) && ! in_array($hookType, static::VALID_HOOKS_FOR_ORDER_CREATION) ) { throw new BoltException( - __('Order creation is forbidden from hook of type: %1', $hookType), + __('Order creation is forbidden from hook of type: %1', $hookType), /** @phpstan-ignore-line */ null, CreateOrder::E_BOLT_REJECTED_ORDER ); @@ -925,7 +923,7 @@ public function verifyOrderCreationHookType($hookType) * * @param string $quoteId * - * @return OrderInterface|false + * @return \Magento\Sales\Model\Order|false|mixed */ public function getOrderByQuoteId($quoteId) { @@ -952,6 +950,7 @@ public function getOrderById($orderId) */ public function saveUpdateOrder($reference, $storeId = null, $boltTraceId = null, $hookType = null, $hookPayload = null) { + /** @var mixed $transaction */ $transaction = $this->fetchTransactionInfo($reference, $storeId); $parentQuoteId = $transaction->order->cart->order_reference; @@ -995,12 +994,13 @@ public function saveUpdateOrder($reference, $storeId = null, $boltTraceId = null /////////////////////////////////////////////////////////////// // check if the order exists + /** @var \Magento\Sales\Model\Order $order */ $order = $this->getExistingOrder($incrementId, $parentQuoteId); // if not create the order if (!$order || !$order->getId()) { if (!$immutableQuote) { - $exception = new LocalizedException(__('Unknown quote id: %1', $quoteId)); + $exception = new LocalizedException(__('Unknown quote id: %1', $quoteId)); /** @phpstan-ignore-line */ if (Hook::$fromBolt && in_array($transaction->status, [Payment::TRANSACTION_AUTHORIZED, Payment::TRANSACTION_CANCELLED])) { if ($transaction->status == Payment::TRANSACTION_AUTHORIZED) { $this->voidTransactionOnBolt($transaction->id, $storeId); @@ -1018,7 +1018,6 @@ public function saveUpdateOrder($reference, $storeId = null, $boltTraceId = null /** @var \Bolt\Boltpay\Model\ResourceModel\WebhookLog\Collection $webhookLogCollection */ $webhookLogCollection = $this->webhookLogCollectionFactory->create(); - if ($webhookLog = $webhookLogCollection->getWebhookLogByTransactionId($transaction->id, $hookType)) { $numberOfMissingQuoteFailedHooks = $webhookLog->getNumberOfMissingQuoteFailedHooks(); if ($numberOfMissingQuoteFailedHooks > 10) { @@ -1088,7 +1087,6 @@ public function isTotalValidationIgnored($transaction, $order) /** * @param $transactionId * @param $storeId - * @param OrderInterface $order * @return $this * @throws LocalizedException */ @@ -1113,13 +1111,13 @@ public function voidTransactionOnBolt($transactionId, $storeId) if (empty($response)) { throw new LocalizedException( - __('Bad void response from boltpay') + __('Bad void response from boltpay') /** @phpstan-ignore-line */ ); } $status = $response->status ?? null; if ($status != 'cancelled') { - throw new LocalizedException(__('Payment void error.')); + throw new LocalizedException(__('Payment void error.')); /** @phpstan-ignore-line */ } return $this; @@ -1191,7 +1189,7 @@ public function applyExternalQuoteData($quote) /** * @param OrderInterface $order - * @param Quote $quote + * @param Quote|mixed $quote */ public function dispatchPostCheckoutEvents($order, $quote) { @@ -1226,7 +1224,7 @@ public function dispatchPostCheckoutEvents($order, $quote) /** * Cancel or detete the failed payment order depending on settings via feature switches * - * @param string $displayId + * @param string $display_id * @param string $immutableQuoteId * @return string log message * @throws \Magento\Framework\Exception\AlreadyExistsException @@ -1256,17 +1254,8 @@ public function processExistingOrder($quote, $transaction) { // check if the order has been created in the meanwhile if ($order = $this->getExistingOrder(null, $quote->getId())) { - if ($order->isCanceled()) { - throw new BoltException( - __( - 'Order has been canceled due to the previously declined payment. Quote ID: %1 Order Increment ID %2', - $quote->getId(), - $order->getIncrementId() - ), - null, - CreateOrder::E_BOLT_REJECTED_ORDER - ); + throw new BoltException(__('Order has been canceled due to the previously declined payment. Quote ID: %1 Order Increment ID %2', $quote->getId(), $order->getIncrementId()), null, CreateOrder::E_BOLT_REJECTED_ORDER); /** @phpstan-ignore-line */ } if ($order->getState() === OrderModel::STATE_PENDING_PAYMENT) { @@ -1301,7 +1290,6 @@ public function processExistingOrder($quote, $transaction) */ public function submitQuote($quote, $orderData = []) { - /** @var OrderModel $order */ try { $order = $this->quoteManagement->submit($quote, $orderData); } catch (\Exception $e) { @@ -1341,6 +1329,7 @@ public function processNewOrder($quote, $transaction) $originalOrderId = $transaction->order->cart->metadata->original_order_entity_id ) { try { + /** @var \Magento\Sales\Model\Order|mixed $originalOrder */ $originalOrder = $this->orderRepository->get($originalOrderId); $originalId = $originalOrder->getOriginalIncrementId(); if (!$originalId) { @@ -1388,10 +1377,7 @@ public function processNewOrder($quote, $transaction) ]); }); throw new BoltException( - __( - 'Quote Submit Error. Parent Quote ID: %1', - $quote->getId() - ), + __('Quote Submit Error. Parent Quote ID: %1', $quote->getId()), /** @phpstan-ignore-line */ null, CreateOrder::E_BOLT_GENERAL_ERROR ); @@ -1402,11 +1388,9 @@ public function processNewOrder($quote, $transaction) $existingOrder = $this->eventsForThirdPartyModules->runFilter('beforeGetOrderByIdProcessNewOrder', $this->cartHelper->getOrderById($order->getId()), $order); $orderPayment = $existingOrder->getPayment(); if ($orderPayment && $orderPayment->getMethod() !== Payment::METHOD_CODE) { - throw new LocalizedException(__( - 'Payment method assigned to order %1 is: %2', - $order->getIncrementId(), - $orderPayment->getMethod() - )); + throw new LocalizedException( + __('Payment method assigned to order %1 is: %2', $order->getIncrementId(), $orderPayment->getMethod()) /** @phpstan-ignore-line */ + ); } $order = $existingOrder; @@ -1507,11 +1491,7 @@ public function tryDeclinedPaymentCancelation($incrementId, $immutableQuoteId) if (!$order) { throw new BoltException( - __( - 'Order Cancelation Error. Order does not exist. Order #: %1 Immutable Quote ID: %2', - $incrementId, - $immutableQuoteId - ), + __('Order Cancelation Error. Order does not exist. Order #: %1 Immutable Quote ID: %2', $incrementId, $immutableQuoteId), /** @phpstan-ignore-line */ null, CreateOrder::E_BOLT_GENERAL_ERROR ); @@ -1519,7 +1499,7 @@ public function tryDeclinedPaymentCancelation($incrementId, $immutableQuoteId) if ($order->getState() === OrderModel::STATE_PENDING_PAYMENT) { $this->cancelOrder($order); - $order->addCommentToStatusHistory(__('BOLTPAY INFO :: Order was canceled due to Bolt rejection before authorization')); + $order->addCommentToStatusHistory(__('BOLTPAY INFO :: Order was canceled due to Bolt rejection before authorization')); /** @phpstan-ignore-line */ $this->orderRepository->save($order); } return $order->getState() === OrderModel::STATE_CANCELED; @@ -1544,12 +1524,7 @@ public function deleteOrderByIncrementId($incrementId, $immutableQuoteId) $state = $order->getState(); if ($state !== OrderModel::STATE_PENDING_PAYMENT) { throw new BoltException( - __( - 'Order Delete Error. Order is in invalid state. Order #: %1 State: %2 Immutable Quote ID: %3', - $incrementId, - $state, - $immutableQuoteId - ), + __('Order Delete Error. Order is in invalid state. Order #: %1 State: %2 Immutable Quote ID: %3', $incrementId, $state, $immutableQuoteId) /** @phpstan-ignore-line */, null, CreateOrder::E_BOLT_GENERAL_ERROR ); @@ -1579,11 +1554,10 @@ public function deleteOrderByIncrementId($incrementId, $immutableQuoteId) /** * @param $orderIncrementId * @param null $quoteId - * @return false|OrderInterface|OrderModel + * @return OrderModel|mixed */ public function getExistingOrder($orderIncrementId, $quoteId = null) { - /** @var OrderModel $order */ $order = $this->cartHelper->getOrderByIncrementId($orderIncrementId, true); // If we had timeout issue on the create_order hook and the third party change the order increment id @@ -1614,7 +1588,7 @@ protected function quoteAfterChange($quote) /** * Load and prepare parent quote * - * @param Quote $immutableQuote + * @param Quote|mixed $immutableQuote * @param \stdClass $transaction * @return Quote * @throws LocalizedException @@ -1624,7 +1598,6 @@ protected function quoteAfterChange($quote) */ public function prepareQuote($immutableQuote, $transaction) { - /** @var Quote $quote */ $boltParentQuoteId = $immutableQuote->getBoltParentQuoteId(); if ($boltParentQuoteId) { $quote = $this->cartHelper->getQuoteById($boltParentQuoteId); @@ -1728,7 +1701,7 @@ public function formatReferenceUrl($reference) /** * Get processed items (captures or refunds) as an array * - * @param OrderPaymentInterface $payment + * @param OrderPaymentInterface|mixed $payment * @param string $itemType 'captures' | 'refunds' * @return array */ @@ -1740,7 +1713,7 @@ private function getProcessedItems($payment, $itemType) /** * Get processed capture ids array * - * @param OrderPaymentInterface $payment + * @param OrderPaymentInterface|mixed $payment * @return array */ private function getProcessedCaptures($payment) @@ -1751,7 +1724,7 @@ private function getProcessedCaptures($payment) /** * Get processed refund ids array * - * @param OrderPaymentInterface $payment + * @param OrderPaymentInterface|mixed $payment * @return array */ private function getProcessedRefunds($payment) @@ -1764,7 +1737,7 @@ private function getProcessedRefunds($payment) * Infer eventually missing states. Represent Bolt partial capture AUTHORIZED state as CAPTURED. * * @param \stdClass $transaction - * @param OrderPaymentInterface $payment + * @param OrderPaymentInterface|mixed $payment * @param null $hookType * @return string */ @@ -1879,7 +1852,7 @@ private function holdOnTotalsMismatch($order, $transaction) // Do it once only, skip on subsequent hooks if ($order->getState() != OrderModel::STATE_HOLDED) { // Add order status history comment - $comment = __( + $comment = __( /** @phpstan-ignore-line */ 'BOLTPAY INFO :: THERE IS A MISMATCH IN THE ORDER PAID AND ORDER RECORDED.
Paid amount: %1 Recorded amount: %2
Bolt transaction: %3', CurrencyUtils::toMajor($boltTotal, $currencyCode), @@ -1931,13 +1904,14 @@ private function holdOnTotalsMismatch($order, $transaction) ]); }); - throw new LocalizedException(__( + throw new LocalizedException(__( /** @phpstan-ignore-line */ 'Order Totals Mismatch Reference: %1 Order: %2 Bolt Total: %3 Store Total: %4', $transaction->reference, $incrementId, $boltTotal, $storeTotal - )); + ) + ); } /** @@ -2080,7 +2054,7 @@ private function checkPaymentMethod($payment) $paymentMethod = $payment->getMethod(); if ($paymentMethod != Payment::METHOD_CODE) { - throw new LocalizedException(__( + throw new LocalizedException(__( /** @phpstan-ignore-line */ 'Payment method assigned to order is: %1', $paymentMethod )); @@ -2137,7 +2111,7 @@ public function updateOrderPayment($order, $transaction = null, $reference = nul $reference = $transaction->reference; } - /** @var OrderPaymentInterface $payment */ + /** @var OrderPaymentInterface|mixed $payment */ $payment = $order->getPayment(); $this->checkPaymentMethod($payment); @@ -2267,7 +2241,7 @@ public function updateOrderPayment($order, $transaction = null, $reference = nul break; default: - throw new LocalizedException(__( + throw new LocalizedException(__(/** @phpstan-ignore-line */ 'Unhandled transaction state : %1', $transactionState )); @@ -2294,7 +2268,7 @@ public function updateOrderPayment($order, $transaction = null, $reference = nul 'token_type' => $transaction->from_credit_card->token_type ?? $transaction->processor ]; - $message = __( + $message = __(/** @phpstan-ignore-line */ 'BOLTPAY INFO :: PAYMENT Status: %1 Amount: %2
Bolt transaction: %3', $this->getBoltTransactionStatus($transactionState), $this->formatAmountForDisplay($order, $amount / 100), @@ -2461,14 +2435,17 @@ public function createOrderInvoice($order, $amount, $notify = false, $transactio $currencyCode = $order->getOrderCurrencyCode(); try { if (CurrencyUtils::toMinor($order->getTotalInvoiced() + $amount, $currencyCode) === CurrencyUtils::toMinor($order->getGrandTotal(), $currencyCode)) { + /** @var Invoice|mixed $invoice */ $invoice = $this->invoiceService->prepareInvoice($order); } else { + /** @var Invoice|mixed $invoice */ $invoice = $this->invoiceService->prepareInvoiceWithoutItems($order, $amount); } } catch (\Exception $e) { $this->bugsnag->notifyException($e); throw $e; } + $invoice->setRequestedCaptureCase(Invoice::CAPTURE_OFFLINE); $invoice->setTransactionId($transactionId); $invoice->setGrandTotal($amount); @@ -2508,7 +2485,7 @@ public function createOrderInvoice($order, $amount, $notify = false, $transactio $order->setBaseShippingAmount($baseShippingAmount); //Add notification comment to order $order->addStatusHistoryComment( - __('Invoice #%1 is created. Notification email is sent to customer.', $invoice->getId()) + __('Invoice #%1 is created. Notification email is sent to customer.', $invoice->getId()) /** @phpstan-ignore-line */ )->setIsCustomerNotified(true); } @@ -2538,11 +2515,11 @@ public function createCreditMemoForHookRequest(OrderModel $order, $transaction) $adjustment['qtys'][$item->getId()] = 0; } } - + /** @var Creditmemo|mixed $creditMemo */ $creditMemo = $this->creditmemoFactory->createByOrder($order, $adjustment); $creditMemo->setAutomaticallyCreated(true) - ->addComment(__('The credit memo has been created automatically.')); + ->addComment(__('The credit memo has been created automatically.'));/** @phpstan-ignore-line */ $this->creditmemoManagement->refund($creditMemo, true); } @@ -2554,8 +2531,8 @@ public function createCreditMemoForHookRequest(OrderModel $order, $transaction) */ protected function validateRefundAmount(OrderModel $order, $refundAmount) { - if (!isset($refundAmount) || !is_numeric($refundAmount) || $refundAmount < 0) { - throw new \Exception(__('Refund amount is invalid')); + if (!$refundAmount || !is_numeric($refundAmount) || $refundAmount < 0) { + throw new \Exception(__('Refund amount is invalid'));/** @phpstan-ignore-line */ } $totalRefunded = $order->getTotalRefunded() ?: 0; @@ -2564,7 +2541,7 @@ protected function validateRefundAmount(OrderModel $order, $refundAmount) if ($availableRefund < $refundAmount) { throw new \Exception( - __('Refund amount is invalid: refund amount [%1], available refund [%2]', $refundAmount, $availableRefund) + __('Refund amount is invalid: refund amount [%1], available refund [%2]', $refundAmount, $availableRefund) /** @phpstan-ignore-line */ ); } } @@ -2599,8 +2576,8 @@ protected function isCaptureHookRequest($newCapture) */ protected function validateCaptureAmount(OrderInterface $order, $captureAmount) { - if (!isset($captureAmount) || !is_numeric($captureAmount) || $captureAmount < 0) { - throw new \Exception(__('Capture amount is invalid')); + if (!$captureAmount || !is_numeric($captureAmount) || $captureAmount < 0) { + throw new \Exception(__('Capture amount is invalid')); /** @phpstan-ignore-line */ } $currencyCode = $order->getOrderCurrencyCode(); @@ -2631,13 +2608,13 @@ function (\Bugsnag\Report $report) use ($order, $grandTotal, $totalInvoicedAfter ); if ($previouslyCaptured == $captureAmountMinor) { throw new \Exception( - __( + __(/** @phpstan-ignore-line */ 'The same capture amount was already invoiced' ) ); } throw new \Exception( - __( + __( /** @phpstan-ignore-line */ 'Capture amount is invalid: capture amount [%1], previously captured [%2], grand total [%3]', $captureAmountMinor, $previouslyCaptured, @@ -2660,20 +2637,20 @@ protected function isAnAllowedUpdateFromAdminPanel(OrderInterface $order, $trans } /** - * @param OrderPaymentInterface $payment + * @param OrderPaymentInterface|mixed $payment * * @return \Magento\Framework\Phrase|string */ - protected function getVoidMessage(OrderPaymentInterface $payment) + protected function getVoidMessage($payment) { $authorizationTransaction = $payment->getAuthorizationTransaction(); /** @var OrderModel $order */ $order = $payment->getOrder(); $voidAmount = $order->getGrandTotal() - $order->getTotalPaid(); - $message = __('BOLT notification: Transaction authorization has been voided.'); - $message .= ' ' .__('Amount: %1.', $this->formatAmountForDisplay($order, $voidAmount)); - $message .= ' ' .__('Transaction ID: %1.', $authorizationTransaction->getHtmlTxnId()); + $message = __('BOLT notification: Transaction authorization has been voided.'); /** @phpstan-ignore-line */ + $message .= ' ' .__('Amount: %1.', $this->formatAmountForDisplay($order, $voidAmount)); /** @phpstan-ignore-line */ + $message .= ' ' .__('Transaction ID: %1.', $authorizationTransaction->getHtmlTxnId()); /** @phpstan-ignore-line */ return $message; } @@ -2747,18 +2724,14 @@ public function cancelFailedPaymentOrder($displayId, $immutableQuoteId) } if ($order->getState() !== OrderModel::STATE_PENDING_PAYMENT) { throw new BoltException( - __( - 'Order Delete Error. Order is in invalid state. Order #: %1 State: %2 Immutable Quote ID: %3', - $displayId, - $order->getState(), - $immutableQuoteId - ), + __('Order Delete Error. Order is in invalid state. Order #: %1 State: %2 Immutable Quote ID: %3', $displayId, $order->getState(), $immutableQuoteId) /** @phpstan-ignore-line */, null, CreateOrder::E_BOLT_GENERAL_ERROR ); } $this->orderManagement->cancel($order->getId()); /** reload order because {@see \Bolt\Boltpay\Helper\Cart::getOrderByIncrementId} */ + /** @var \Magento\Sales\Model\Order|mixed $order */ $order = $this->orderRepository->get($order->getId()); $parentQuoteId = $order->getQuoteId(); @@ -2783,7 +2756,7 @@ public function cancelFailedPaymentOrder($displayId, $immutableQuoteId) $this->eventsForThirdPartyModules->dispatchEvent("beforeFailedPaymentOrderSave", $order); $order->addData(['quote_id' => null]); - $order->addCommentToStatusHistory(__('BOLTPAY INFO :: Order was canceled due to Processor rejection')); + $order->addCommentToStatusHistory(__('BOLTPAY INFO :: Order was canceled due to Processor rejection')); /** @phpstan-ignore-line */ $this->orderRepository->save($order); } } diff --git a/Helper/SSOHelper.php b/Helper/SSOHelper.php index 32a8b2ef5..36a3c420f 100644 --- a/Helper/SSOHelper.php +++ b/Helper/SSOHelper.php @@ -21,6 +21,7 @@ use Bolt\Boltpay\Helper\Api as ApiHelper; use Bolt\Boltpay\Helper\Config as ConfigHelper; use Bolt\Boltpay\Helper\JWT\JWT; +use Bolt\Boltpay\Model\Response; use Exception; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; @@ -43,7 +44,7 @@ class SSOHelper extends AbstractHelper private $storeManager; /** - * @var DataObjectFactory + * @var DataObjectFactory|mixed */ private $dataObjectFactory; diff --git a/Helper/Session.php b/Helper/Session.php index 3e81fe9f3..b77dd9c48 100644 --- a/Helper/Session.php +++ b/Helper/Session.php @@ -169,7 +169,7 @@ private function replaceQuote($quote) * Load logged in customer checkout and customer sessions from cached session id. * Replace parent quote with immutable quote in checkout session. * - * @param Quote $quote + * @param Quote|mixed $quote * @param array $metadata * * @throws \Magento\Framework\Exception\LocalizedException diff --git a/Helper/Shared/ApiUtils.php b/Helper/Shared/ApiUtils.php index b77c5e66c..d20b648c4 100644 --- a/Helper/Shared/ApiUtils.php +++ b/Helper/Shared/ApiUtils.php @@ -57,11 +57,11 @@ public static function getJSONFromResponseBody($responseBody) $resultFromJSON = json_decode((string)$responseBody); $jsonError = self::handleJsonParseError(); if ($jsonError != null) { - throw new LocalizedException(__('JSON Parse Error: ' . $jsonError)); + throw new LocalizedException(__('JSON Parse Error: ' . $jsonError)); /** @phpstan-ignore-line */ } if (self::isApiError($resultFromJSON)) { - $message = isset($resultFromJSON->errors[0]->message) ? __($resultFromJSON->errors[0]->message) : __('Bolt API Error Response'); + $message = isset($resultFromJSON->errors[0]->message) ? __($resultFromJSON->errors[0]->message) : __('Bolt API Error Response'); /** @phpstan-ignore-line */ throw new LocalizedException($message); } return $resultFromJSON; diff --git a/Model/HttpClientAdapter.php b/Model/HttpClientAdapter.php index e4567561c..033c52f24 100644 --- a/Model/HttpClientAdapter.php +++ b/Model/HttpClientAdapter.php @@ -130,10 +130,10 @@ public function setParameterPost($post) } /** - * Send client request - * - * @param string $methodType - * @return \Laminas\Http\Response|void + * @param $methodType + * @return \Laminas\Http\Response|null + * @throws \Laminas\Http\Client\Exception\RuntimeException + * @throws \Laminas\Http\Exception\RuntimeException */ public function request($methodType) { diff --git a/Model/ResourceModel/WebhookLog/Collection.php b/Model/ResourceModel/WebhookLog/Collection.php index 870af2ef4..1ae588eda 100644 --- a/Model/ResourceModel/WebhookLog/Collection.php +++ b/Model/ResourceModel/WebhookLog/Collection.php @@ -36,7 +36,7 @@ protected function _construct() /** * @param $transactionId * @param $hookType - * @return bool|\Magento\Framework\DataObject + * @return false|\Bolt\Boltpay\Model\WebhookLog|mixed */ public function getWebhookLogByTransactionId($transactionId, $hookType) {