MethodListPlugin.php 2.43 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
<?php
/**
 * This file is part of the Klarna KP module
 *
 * (c) Klarna AB
 *
 * For the full copyright and license information, please view the NOTICE
 * and LICENSE files that were distributed with this source code.
 */

namespace Klarna\Kp\Plugin\Model;

use Klarna\Kp\Api\SessionInitiatorInterface;
use Klarna\Kp\Model\Payment\Kp;
use Klarna\Kp\Model\SessionInitiatorFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Payment\Model\MethodList;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Store\Model\ScopeInterface;

/**
 * Class MethodListPlugin
 *
 * @package Klarna\Kp\Plugin\Model
 */
class MethodListPlugin
{
    /**
     * @var SessionInitiatorFactory
     */
    private $sessInitFactory;

    /**
     * @var ScopeConfigInterface
     */
    private $config;

    /**
     * MethodListPlugin constructor.
     *
     * @param SessionInitiatorFactory $sessInitFactory
     * @param ScopeConfigInterface    $config
     */
    public function __construct(SessionInitiatorFactory $sessInitFactory, ScopeConfigInterface $config)
    {
        $this->sessInitFactory = $sessInitFactory;
        $this->config = $config;
    }

    /**
     * Ensure payment methods are initialized before first getting
     * list of available payment methods
     *
     * @param MethodList         $subject
     * @param CartInterface|null $quote
     * @SuppressWarnings(PMD.UnusedFormalParameter)
     * @return array
     */
    public function beforeGetAvailableMethods(MethodList $subject, CartInterface $quote = null)
    {
        if ($this->isEnabled($quote)) {
            $this->getSessionInitiator()->checkAvailable($quote, Kp::METHOD_CODE);
        }
        return [$quote];
    }

    /**
     * Check to see if we should run or not
     *
     * @param CartInterface $quote
     * @return bool
     */
    private function isEnabled(CartInterface $quote = null)
    {
        if (!$quote) {
            return false;
        }
        $store = $quote->getStore();
        $scope = ($store === null ? ScopeConfigInterface::SCOPE_TYPE_DEFAULT : ScopeInterface::SCOPE_STORES);
        if (!$this->config->isSetFlag('payment/' . Kp::METHOD_CODE . '/active', $scope, $store)) {
            return false;
        }
        return true;
    }

    /**
     * Get SessionInitiator instance
     *
     * @return SessionInitiatorInterface
     */
    private function getSessionInitiator()
    {
        return $this->sessInitFactory->create();
    }
}