Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/old/vendor/extmag/shiplab/Model/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/old/vendor/extmag/shiplab/Model/Carrier.php
<?php
/**
 * Copyright © Extmag. All rights reserved.
 */
declare(strict_types=1);

namespace Extmag\Shiplab\Model;

use Exception;
use Extmag\Core\Helper\Registry;
use Extmag\Shiplab\Helper\DataPrepareFactory;
use Extmag\Shiplab\Helper\Manager;
use Extmag\Shiplab\Helper\Request;
use Extmag\Shiplab\Helper\RequestFactory;
use Extmag\Shiplab\Model\ResourceModel\ShippingMethods\Collection;
use Extmag\Shiplab\Model\ResourceModel\ShippingMethods\CollectionFactory;
use Extmag\Shiplab\Model\Source\AllShippingMethods;
use Extmag\Shiplab\Model\Source\Frequency;
use Extmag\Shiplab\Model\Source\ServiceCodes;
use Magento\Backend\Model\Session\Quote;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Customer\Model\Session;
use Magento\Directory\Helper\Data;
use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\CurrencyFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\State;
use Magento\Framework\DataObject;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\ClientFactory;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Xml\Security;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;
use Magento\Shipping\Model\Carrier\AbstractCarrierOnline;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Rate\ResultFactory;
use Magento\Shipping\Model\Simplexml\ElementFactory;
use Magento\Shipping\Model\Tracking\Result\StatusFactory;
use Psr\Log\LoggerInterface;
use Zend_Db_Expr;

/**
 * Extmag shipping implementation
 * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Carrier extends AbstractCarrierOnline implements CarrierInterface
{
    /**
     * Code of the carrier
     *
     * @var string
     */
    public const CODE = 'extmag';
    public Manager $manager;

    /**
     * Code of the carrier
     *
     * @var string
     */
    protected $_code = self::CODE;

    /**
     * Rate request data
     *
     * @var RateRequest
     */
    protected $_request;

    /**
     * Rate result data
     *
     * @var Result
     */
    protected $_result;

    /**
     * @var LoggerInterface
     */
    protected $_logger;

    /**
     * @var ShippingMethodsRepository
     */
    protected $shippingMethodsRepository;
    /**
     * @var CollectionFactory
     */
    protected $shippingMethodsCollectionFactory;

    /**
     * @var DataPrepareFactory
     */
    protected $dataPrepareFactory;

    /**
     * @var Session
     */
    protected $customerSession;
    /**
     * @var Registry
     */
    protected $register;
    /**
     * @var Request
     */
    protected $helperRequest;
    /**
     * @var RequestFactory
     */
    protected $requestToAPI;

    /**
     * @var ClientFactory
     */
    protected $httpClientFactory;
    /**
     * @var ServiceCodes
     */
    protected $serviceCodes;
    /**
     * @var State
     */
    protected $appArea;
    /**
     * @var Quote
     */
    protected $backendSession;
    /**
     * @var Frequency
     */
    protected $frequency;
    /**
     * @var DateTime
     */
    protected $dateTime;

    /**
     * @var Escaper
     */
    protected $escaper;

    /**
     * @var ResourceModel\PriceRules\CollectionFactory
     */
    protected $priceRules;
    /**
     * @var array
     */
    protected $useDefaultAddress = [];
    protected AllShippingMethods $allShippingMethods;

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param ErrorFactory $rateErrorFactory
     * @param LoggerInterface $logger
     * @param Security $xmlSecurity
     * @param ElementFactory $xmlElFactory
     * @param ResultFactory $rateFactory
     * @param MethodFactory $rateMethodFactory
     * @param \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory
     * @param \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory
     * @param StatusFactory $trackStatusFactory
     * @param RegionFactory $regionFactory
     * @param CountryFactory $countryFactory
     * @param CurrencyFactory $currencyFactory
     * @param Data $directoryData
     * @param StockRegistryInterface $stockRegistry
     * @param ClientFactory $httpClientFactory
     * @param ShippingMethodsRepository $shippingMethodsRepository
     * @param CollectionFactory $shippingMethodsCollectionFactory
     * @param DataPrepareFactory $dataPrepareFactory
     * @param Session $customerSession
     * @param State $appArea
     * @param Quote $backendSession
     * @param ServiceCodes $serviceCodes
     * @param Registry $register
     * @param Request $helperRequest
     * @param RequestFactory $requestToAPI
     * @param Frequency $frequency
     * @param DateTime $dateTime
     * @param Escaper $escaper
     * @param ResourceModel\PriceRules\CollectionFactory $priceRules
     * @param Manager $manager
     * @param AllShippingMethods $allShippingMethods
     * @param array $data
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        ErrorFactory $rateErrorFactory,
        LoggerInterface $logger,
        Security $xmlSecurity,
        ElementFactory $xmlElFactory,
        ResultFactory $rateFactory,
        MethodFactory $rateMethodFactory,
        \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory,
        \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory,
        StatusFactory $trackStatusFactory,
        RegionFactory $regionFactory,
        CountryFactory $countryFactory,
        CurrencyFactory $currencyFactory,
        Data $directoryData,
        StockRegistryInterface $stockRegistry,
        ClientFactory $httpClientFactory,
        ShippingMethodsRepository $shippingMethodsRepository,
        CollectionFactory $shippingMethodsCollectionFactory,
        DataPrepareFactory $dataPrepareFactory,
        Session $customerSession,
        State $appArea,
        Quote $backendSession,
        ServiceCodes $serviceCodes,
        Registry $register,
        Request $helperRequest,
        RequestFactory $requestToAPI,
        Frequency $frequency,
        DateTime $dateTime,
        Escaper $escaper,
        ResourceModel\PriceRules\CollectionFactory $priceRules,
        Manager $manager,
        AllShippingMethods $allShippingMethods,
        array $data = []
    ) {
        parent::__construct(
            $scopeConfig,
            $rateErrorFactory,
            $logger,
            $xmlSecurity,
            $xmlElFactory,
            $rateFactory,
            $rateMethodFactory,
            $trackFactory,
            $trackErrorFactory,
            $trackStatusFactory,
            $regionFactory,
            $countryFactory,
            $currencyFactory,
            $directoryData,
            $stockRegistry,
            $data
        );
        $this->httpClientFactory = $httpClientFactory;
        $this->shippingMethodsRepository = $shippingMethodsRepository;
        $this->shippingMethodsCollectionFactory = $shippingMethodsCollectionFactory;
        $this->dataPrepareFactory = $dataPrepareFactory;
        $this->customerSession = $customerSession;
        $this->register = $register;
        $this->helperRequest = $helperRequest;
        $this->requestToAPI = $requestToAPI;
        $this->serviceCodes = $serviceCodes;
        $this->appArea = $appArea;
        $this->backendSession = $backendSession;
        $this->frequency = $frequency;
        $this->dateTime = $dateTime;
        $this->escaper = $escaper;
        $this->priceRules = $priceRules;
        $this->manager = $manager;
        $this->allShippingMethods = $allShippingMethods;
    }

    /**
     * Collect and get rates/errors
     *
     * @param RateRequest $request
     *
     * @return  Result|Error|bool
     */
    public function collectRates(RateRequest $request)
    {
        $this->_request = $request;
        return $this->_doShipmentRequest($request);
    }

    /**
     * @inheritDoc
     */
    protected function _doShipmentRequest(DataObject $request)
    {
        /**
         * @var Result $result
         */
        $this->_result = $this->_rateFactory->create();
        $equalsMethods = [];
        try {
            $extmagShippingMethods = $this->getExtmagShippingMethods();
            $this->helperRequest->clearRequestData();

            if (!empty($extmagShippingMethods)) {
                foreach ($extmagShippingMethods as $carrierCode => $value) {
                    foreach ($value as $methodCode => $method) {
                        /* If a method with this carrier code and the Access Point setting has already been processed,
                        then we skip this method so as not to make unnecessary requests to the API server */
                        if (empty($equalsMethods[$carrierCode . "|" . ((int)$method->getAccessPoint())])) {
                            $equalsMethods[$carrierCode . "|" . ((int)$method->getAccessPoint())] = 1;
                        } else {
                            continue;
                        }

                        if (!empty($this->useDefaultAddress) && empty($this->useDefaultAddress[$carrierCode])
                            && $this->getConfigData('use_default_address') == 1
                        ) {
                            continue;
                        }
                        $dataPrepare = $this->dataPrepareFactory->create($carrierCode);
                        $dataPrepare->setRateRequest($request);
                        $dataPrepare->setConfigScopeFilter();
                        if (!empty($this->useDefaultAddress[$carrierCode])
                            && $this->getConfigData('use_default_address') == 1
                        ) {
                            $dataPrepare->setUseDefaultAddress(true);
                        } else {
                            $dataPrepare->setUseDefaultAddress(false);
                        }
                        $dataPrepare->getStepOne();
                        $dataPrepare->getStepTwo();
                        $dataPrepare->getStepThree();
                        $dataPrepare->setDiscount(1);

                        if ($dataPrepare->applyAccessPoint($method)) {
                            $connector = $dataPrepare->getConnector($this->requestToAPI->create($carrierCode, 'rate'));
                            $connector->addRequest();
                            foreach ($connector->getRequestData()['Request'] as $requestDatum) {
                                $this->helperRequest->addRequestData($requestDatum);
                            }
                        }
                    }
                }

                $cacheData = $this->helperRequest->getRequestData();
                $responseBody = $this->_getCachedQuotes(json_encode([$this->_code => $cacheData]));
                if ($responseBody === null) {
                    $rates = $this->helperRequest->send();
                    $responses = $this->helperRequest->parseResponse($rates, null, true);
                    $this->_setCachedQuotes(json_encode([$this->_code => $cacheData]), json_encode($responses));
                } else {
                    $responses = json_decode($responseBody);
                }

                foreach ($responses as $response) {
                    if (!empty($response['service_codes'])) {
                        /**
                         * @var ShippingMethods $shippingMethod
                         */
                        foreach ($extmagShippingMethods as $carrierCode => $value) {
                            $serviceCodes = $response['service_codes'][$carrierCode] ?? null;
                            if ($serviceCodes !== null) {
                                foreach ($value as $shippingMethod) {
                                    if ((int)$shippingMethod->getAccessPoint() != (int)($response['access_point_active'] ?? 0)) {
                                        continue;
                                    }
                                    if ($shippingMethod->getCarrierMethodsType() == 'all') {
                                        foreach ($serviceCodes as $methodCode => $serviceCode) {
                                            $this->addRate($serviceCode, $shippingMethod, $response);
                                        }
                                    } elseif ($shippingMethod->getCarrierMethodsType() == 'specific'
                                        && strlen($shippingMethod->getCarrierMethods()) > 0
                                    ) {
                                        $carrierMethods = explode(',', $shippingMethod->getCarrierMethods());
                                        foreach ($serviceCodes as $methodCode => $serviceCode) {
                                            if (in_array($methodCode, $carrierMethods)) {
                                                $this->addRate($serviceCode, $shippingMethod, $response);
                                            }
                                        }
                                    } elseif ($shippingMethod->getCarrierMethodsType() == 'minprice') {
                                        $serviceCode = $this->getMethodWithMinPrice($serviceCodes);
                                        $this->addRate($serviceCode, $shippingMethod, $response);
                                    } elseif ($shippingMethod->getCarrierMethodsType() == 'maxprice') {
                                        $serviceCode = $this->getMethodWithMaxPrice($serviceCodes);
                                        $this->addRate($serviceCode, $shippingMethod, $response);
                                    }

                                    $this->updateFreeMethodQuote($shippingMethod);
                                }
                            }
                        }
                    } elseif (!empty($response['rate_error'])) {
                        if ($this->getConfigData('debug') == 1) {
                            /**
                             * @var Error $error
                             */
                            $error = $this->_rateErrorFactory->create();
                            $error->setCarrier($this->_code);
                            $error->setCarrierTitle($this->getConfigData('title'));
                            $error->setErrorMessage(_($response['rate_error'][0]));
                            $this->_result->append($error);
                        }

                        if (empty($this->useDefaultAddress[$response['carrier']])
                            && $this->getConfigData('use_default_address') == 1
                        ) {
                            $this->useDefaultAddress[$response['carrier']] = true;
                            $result = $this->_doShipmentRequest($request);
                            unset($this->useDefaultAddress[$response['carrier']]);
                            return $result;
                        } else {
                            $this->_logger->error("Shipping Method request have an error ", $response['rate_error']);
                        }
                    }
                }

                return $this->_result;
            }
        } catch (Exception $e) {
            $this->_logger->critical($e->getMessage(), $e->getTrace());
            if ($this->getConfigData('debug') == 1) {
                $nativeData = $this->helperRequest->getNativeData();
                if (!empty($nativeData)) {
                    foreach ($nativeData as $nativeDatum) {
                        $error = $this->_rateErrorFactory->create();
                        $error->setCarrier($this->_code);
                        $error->setCarrierTitle($this->getConfigData('title'));
                        $error->setErrorMessage(var_export($nativeDatum, true));
                        $this->_result->append($error);
                    }

                    return $this->_result;
                }
            }
        }

        return false;
    }

    /**
     * @param                 $serviceCode
     * @param ShippingMethods $shippingMethod
     * @param array $responseApiData
     * @throws Exception
     */
    protected function addRate($serviceCode, ShippingMethods $shippingMethod, array $responseApiData)
    {
        $cost = (float)$serviceCode['price'];
        if ($shippingMethod->getCarrierDiscount() == 1) {
            $discount = (float)$serviceCode['price_with_discount'];
            if ($cost > $discount) {
                $cost -= $discount;
            }
        }

        if (empty($serviceCode['price_with_discount'])
            && !empty($responseApiData['duty_and_tax_payer'])
            && $responseApiData['duty_and_tax_payer'] == 'customer'
            && $cost > (float)$serviceCode['price_without_tax']
        ) {
            $cost -= (float)$serviceCode['price_without_tax'];
        }
        $cost = $this->convertCurrencyByCarrier($serviceCode['currency'], $cost);
        $price = $this->calculatePrice($shippingMethod, $cost);
        if ($cost !== false) {
            /**
             * @var Method $rate
             */
            $rate = $this->_rateMethodFactory->create();
            $rate->setCarrier($this->_code);
            $rate->setCarrierTitle($shippingMethod->getCarrierTitle() ?: $this->getConfigData('title'));
            $logo = $shippingMethod->getLogo();
            if (!empty($logo)) {
                $logo = json_decode($logo, true);
                $this->register->setValue(
                    'extmag_carrier_logo_' . $this->_code . '_' . $shippingMethod->getId() . '_' . $serviceCode['key'],
                    '<img class="shipping-carrier-logo' . $this->_code . '-carrier-logo" src="' . $logo[0]['url'] . '" alt="' . $this->escaper->escapeHtmlAttr($shippingMethod->getCarrierTitle() ?: $this->getConfigData('title')) . '"  title="' . $this->escaper->escapeHtmlAttr($shippingMethod->getCarrierTitle() ?: $this->getConfigData('title')) . '">'
                );
            }
            $rate->setMethod($shippingMethod->getId() . '_' . $serviceCode['key']);
            $rate->setMethodTitle(
                $this->getMethodNameWithTiT(
                    $serviceCode,
                    $shippingMethod,
                    $responseApiData
                )
            );
            $rate->setCost($cost);
            $rate->setPrice($price);
            $uniqueCode = $this->_code . '_' . $shippingMethod->getId() . '_' . $serviceCode['key'];
            $this->register->setValue(
                'ap_code_' . $uniqueCode,
                $shippingMethod->getAccessPoint()
            );
            $this->register->setValue(
                'ap_carrier' . $uniqueCode,
                $shippingMethod->getCarrier()
            );
            $this->register->setValue(
                'ap_top_text' . $uniqueCode,
                $this->escaper->escapeHtml(
                    $this->manager->getConfig(
                        $shippingMethod->getCarrier() . "_access_point/general/top_text",
                        $this->_request->getStoreId(),
                        'shipment',
                        $this->_request->getDestCountryId()
                    ) ?? ''
                )
            );
            $this->_result->append($rate);
        }
    }

    /**
     * @param                 $serviceCode
     * @param ShippingMethods $shippingMethod
     *
     * @return string
     */
    protected function getMethodNameWithTiT($serviceCode, ShippingMethods $shippingMethod, $responseApiData)
    {
        $methodTitle = $this->allShippingMethods
            ->getNameByMapping(
                $shippingMethod->getMethodsNamesMapping(),
                $shippingMethod->getCarrier(),
                $serviceCode['key'],
                $responseApiData['ship_from_country_code'] ?? $responseApiData['shipper_country_code'],
                $responseApiData['ship_to_country_code']
            )??$serviceCode['label'];
        if ($shippingMethod->getIsTit() == 1 && !empty($serviceCode['tit']['Arrival'])) {
            $date = $serviceCode['tit']['Arrival']['Date'];
            $time = $serviceCode['tit']['Arrival']['Time'];
            $year = $date['Y'];
            $month = $date['m'];
            if (strpos($month, "0") === 0) {
                $month = substr($month, 1, 1);
            }

            $day = $date['d'];
            if (strpos($day, "0") === 0) {
                $day = substr($day, 1, 1);
            }

            $hour = $time['H'];
            $minute = $time['i'];
            $second = 0;

            $timeStamp = mktime((int)$hour, (int)$minute, $second, (int)$month, (int)$day, (int)$year);

            if ($timeStamp !== false) {
                $changedDate = date($shippingMethod->getTitFormat(), $timeStamp);

                if ($changedDate !== false) {
                    $methodTitle = $methodTitle . ' ' . $shippingMethod->getTitPrefix()
                        . $changedDate . $shippingMethod->getTitSuffix();
                }
            }
        }

        return $methodTitle;
    }

    /**
     * @param ShippingMethods $shippingMethod
     * @param                 $price
     *
     * @return float|int|string|string[]
     */
    protected function calculatePrice(ShippingMethods $shippingMethod, $price)
    {
        $priceTemplate = trim($shippingMethod->getPrice());
        if ($priceTemplate != "") {
            $item = $this->_request->getAllItems()[0];
            if ($shippingMethod->getActions()->validate($item)) {
                $price = $this->calculatePriceItem($priceTemplate, $price);
            }
        }

        return $this->calculatePriceActions($shippingMethod, $price);
    }

    /**
     * @param ShippingMethods $shippingMethod
     * @param $basePrice
     * @return float|int|string|string[]
     */
    protected function calculatePriceActions(ShippingMethods $shippingMethod, $basePrice)
    {
        $price = $basePrice;
        $priceRuleIdsAsArray = $shippingMethod->getPriceRuleIdsAsArray();
        if (!empty($priceRuleIdsAsArray)) {
            /**
             * @var ResourceModel\PriceRules\Collection $priceRulesCollection
             */
            $priceRulesCollection = $this->priceRules->create();
            $priceRulesCollection->addFieldToFilter('status', 1)
                ->addFieldToFilter('entity_id', ['in' => $priceRuleIdsAsArray]);
            $priceRulesCollection->getSelect()
                ->order(
                    new Zend_Db_Expr('FIELD(entity_id, ' . implode(',', $priceRuleIdsAsArray) . ')')
                );

            if ($priceRulesCollection->count() > 0) {
                $applyType = $shippingMethod->getPriceRulesApply();
                $item = $this->_request->getAllItems()[0];
                /**
                 * @var PriceRules $priceRule
                 */
                foreach ($priceRulesCollection as $priceRule) {
                    if ($applyType === 'all_base_price') {
                        $price = $basePrice;
                    }
                    if ($this->filterDate($priceRule) === true) {
                        $priceTemplate = trim($priceRule->getPrice());
                        if ($priceTemplate != "") {
                            if ($priceRule->getConditions()->validate($item)) {
                                $price = $this->calculatePriceItem($priceTemplate, $price);
                                if ($applyType === 'first_match') {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        return $price;
    }

    protected function calculatePriceItem($priceTemplate, $price)
    {
        $priceTemplate = str_replace(" ", "", $priceTemplate);
        $firstSymbol = substr($priceTemplate, 0, 1);
        $lastSymbol = substr($priceTemplate, -1, 1);
        $clearNumeric = str_replace(['-', '+', '%', 'max', 'min'], "", $priceTemplate);
        if ($firstSymbol == "-") {
            if ($lastSymbol == "%") {
                return $price - ($clearNumeric / 100) * $price;
            } else {
                return max($price - $clearNumeric, 0);
            }
        } elseif ($firstSymbol == "+") {
            if ($lastSymbol == "%") {
                return $price + ($clearNumeric / 100) * $price;
            } else {
                return $price + $clearNumeric;
            }
        } elseif (substr($priceTemplate, 0, 3) == 'max') {
            return min($price, $clearNumeric);
        } elseif (substr($priceTemplate, 0, 3) == 'min') {
            return max($price, $clearNumeric);
        } elseif ($lastSymbol == "%") {
            return ($clearNumeric / 100) * $price;
        } elseif (is_numeric($priceTemplate)) {
            return $priceTemplate;
        }

        return $price;
    }

    /**
     * Allows free shipping when all product items have free shipping.
     *
     * @param ShippingMethods $method
     *
     * @return void
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    protected function updateFreeMethodQuote($method)
    {
        if ($method->getFreeShipping() != 1 || !$this->_request->getFreeShipping()) {
            return;
        }

        /**
         * if we can apply free shipping for all order we should force price
         * to $0.00 for shipping with out sending second request to carrier
         */
        $price = 0;

        /**
         * if we did not get our free shipping method in response we must use its old price
         */
        if (is_object($this->_result)) {
            foreach ($this->_result->getAllRates() as $i => $item) {
                if (strpos($item->getMethod(), $method->getId() . '_') === 0) {
                    $this->_result->getRateById($i)->setPrice($price);
                }
            }
        }
    }

    /**
     * @param        $serviceCodes
     * @param string $priceFieldName
     *
     * @return mixed
     */
    protected function getMethodWithMinPrice($serviceCodes, $priceFieldName = 'price')
    {
        $minKey = null;
        $minPrice = 999999999;

        foreach ($serviceCodes as $key => $serviceCode) {
            if ($minPrice > $serviceCode[$priceFieldName]) {
                $minKey = $key;
                $minPrice = $serviceCode[$priceFieldName];
            }
        }

        if ($minKey !== null) {
            return $serviceCodes[$minKey];
        }

        return $serviceCodes;
    }

    /**
     * @param        $serviceCodes
     * @param string $priceFieldName
     *
     * @return mixed
     */
    protected function getMethodWithMaxPrice($serviceCodes, $priceFieldName = 'price')
    {
        $maxKey = null;
        $maxPrice = 0;

        foreach ($serviceCodes as $key => $serviceCode) {
            if ($maxPrice < $serviceCode[$priceFieldName]) {
                $maxKey = $key;
                $maxPrice = $serviceCode[$priceFieldName];
            }
        }

        if ($maxKey !== null) {
            return $serviceCodes[$maxKey];
        }

        return $serviceCodes;
    }

    /**
     * @param $responseCurrencyCode
     * @param $cost
     *
     * @return float
     */
    protected function convertCurrencyByCarrier($responseCurrencyCode, $cost)
    {
        $allowedCurrencies = $this->_currencyFactory->create()->getConfigAllowCurrencies();
        //convert price with Origin country currency code to base currency code
        if ($responseCurrencyCode && $responseCurrencyCode != $this->_request->getPackageCurrency()->getCode()) {
            if (in_array($responseCurrencyCode, $allowedCurrencies)) {
                return ((double)$cost / $this->_getBaseCurrencyRate($responseCurrencyCode));
            } else {
                $errorTitle = __(
                    'We can\'t convert a rate from "%1-%2".',
                    $responseCurrencyCode,
                    $this->_request->getPackageCurrency()->getCode()
                );
                $error = $this->_rateErrorFactory->create();
                $error->setCarrier($this->_code);
                $error->setCarrierTitle($this->getConfigData('title'));
                $error->setErrorMessage($errorTitle);
                $this->_result->append($error);
            }
        }

        return $cost;
    }

    /**
     * Get base currency rate
     *
     * @param string $code
     *
     * @return float
     */
    protected function _getBaseCurrencyRate($code)
    {
        return $this->_currencyFactory->create()->load(
            $this->_request->getBaseCurrency()->getCode()
        )->getAnyRate(
            $code
        );
    }

    /**
     * Get allowed shipping methods
     *
     * @return array
     */
    public function getAllowedMethods()
    {
        $arr = [];
        /**
         * @var Collection $collection
         */
        $collection = $this->shippingMethodsCollectionFactory->create();
        /**
         * @var ShippingMethods $item
         */
        foreach ($collection as $item) {
            $codes = $this->serviceCodes->getCodesOnly($item->getCarrier());
            if ($codes) {
                foreach ($codes as $key => $code) {
                    $arr[$item->getId() . '_' . $key] = $item->getAdminTitle() . ' [' . $code . ']';
                }
            } else {
                $arr[$item->getId()] = $item->getAdminTitle();
            }
        }

        return $arr;
    }

    /**
     * Get all shipping methods
     *
     * @return array
     * @throws LocalizedException
     */
    public function getExtmagShippingMethods()
    {
        $arr = [];
        /**
         * @var Collection $collection
         */
        $collection = $this->shippingMethodsCollectionFactory->create();
        $customerGroupId = 0;
        if ($this->appArea->getAreaCode() == Area::AREA_ADMINHTML) {
            $customerGroupId = $this->backendSession->getQuote()->getCustomer()->getGroupId();
        } elseif ($this->customerSession->isLoggedIn()) {
            $customerGroupId = $this->customerSession->getCustomer()->getGroupId();
            $collection->addFieldToFilter('area', 'all');
        }

        $collection->addFieldToFilter('status', 1)->addFieldToFilter(
            ['customer_group_type', 'customer_group_ids',],
            [
                ['eq' => 'all'],
                ['finset' => [$customerGroupId]],
            ]
        )->addFieldToFilter(
            ['website_type', 'website_ids',],
            [
                ['eq' => 'all'],
                ['finset' => [$this->_request->getStoreId()]],
            ]
        );
        if ($collection->count() > 0) {
            $firstItem = $this->_request->getAllItems()[0];
            /**
             * @var ShippingMethods $item
             */
            foreach ($collection as $item) {
                if ($this->filterDate($item) !== true || !$item->validate($firstItem)) {
                    continue;
                }

                $arr[$item->getCarrier()][$item->getId()] = $item;
            }
        }

        return $arr;
    }

    /**
     * @param $shippingMethod
     * @return bool
     */
    protected function filterDate($shippingMethod)
    {
        $frequency = $shippingMethod->getFrequency();
        if (!empty($frequency) && isset($this->frequency->getArray()[$frequency])) {
            switch ($frequency) {
                case "once":
                    $dateFrom = $shippingMethod->getDateFrom();
                    if (!empty($dateFrom) && $dateFrom > $this->dateTime->date()) {
                        return false;
                    }

                    $dateTo = $shippingMethod->getDateTo();
                    if (!empty($dateTo) && $dateTo < $this->dateTime->date()) {
                        return false;
                    }

                    break;
                case "daily":
                    $dayWeek = $shippingMethod->getDayWeekAsArray();
                    if (!in_array($this->dateTime->date('w'), $dayWeek)) {
                        return false;
                    }

                    $dateFrom = $shippingMethod->getDateFrom();
                    if (!empty($dateFrom)) {
                        $time = explode(' ', $dateFrom, 2);
                        if (count($time) > 1 && $time[1] > $this->dateTime->date('H:i:s')) {
                            return false;
                        }
                    }

                    $dateTo = $shippingMethod->getDateTo();
                    if (!empty($dateTo)) {
                        $time = explode(' ', $dateTo, 2);
                        if (count($time) > 1 && $time[1] < $this->dateTime->date('H:i:s')) {
                            return false;
                        }
                    }

                    break;
                case "monthly":
                    $dayWeek = $shippingMethod->getDayWeekAsArray();
                    if (!in_array($this->dateTime->date('w'), $dayWeek)) {
                        return false;
                    }

                    $dateFrom = $shippingMethod->getDateFrom();
                    if (!empty($dateFrom)) {
                        $time = explode('-', $dateFrom, 3);
                        if (count($time) > 2 && $time[2] > $this->dateTime->date('d H:i:s')) {
                            return false;
                        }
                    }

                    $dateTo = $shippingMethod->getDateTo();
                    if (!empty($dateTo)) {
                        $time = explode('-', $dateTo, 3);
                        if (count($time) > 2 && $time[2] < $this->dateTime->date('d H:i:s')) {
                            return false;
                        }
                    }

                    break;
                case "annually":
                    $dayWeek = $shippingMethod->getDayWeekAsArray();
                    if (!in_array($this->dateTime->date('w'), $dayWeek)) {
                        return false;
                    }

                    $dateFrom = $shippingMethod->getDateFrom();
                    if (!empty($dateFrom)) {
                        $time = explode('-', $dateFrom, 2);
                        if (count($time) > 1 && $time[1] > $this->dateTime->date('m-d H:i:s')) {
                            return false;
                        }
                    }

                    $dateTo = $shippingMethod->getDateTo();
                    if (!empty($dateTo)) {
                        $time = explode('-', $dateTo, 2);
                        if (count($time) > 1 && $time[1] < $this->dateTime->date('m-d H:i:s')) {
                            return false;
                        }
                    }

                    break;
            }
        }

        return true;
    }
}

Spamworldpro Mini