MethodListPlugin.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * This file is part of the Klarna KP module
  4. *
  5. * (c) Klarna AB
  6. *
  7. * For the full copyright and license information, please view the NOTICE
  8. * and LICENSE files that were distributed with this source code.
  9. */
  10. namespace Klarna\Kp\Plugin\Model;
  11. use Klarna\Kp\Api\SessionInitiatorInterface;
  12. use Klarna\Kp\Model\Payment\Kp;
  13. use Klarna\Kp\Model\SessionInitiatorFactory;
  14. use Magento\Framework\App\Config\ScopeConfigInterface;
  15. use Magento\Payment\Model\MethodList;
  16. use Magento\Quote\Api\Data\CartInterface;
  17. use Magento\Store\Model\ScopeInterface;
  18. /**
  19. * Class MethodListPlugin
  20. *
  21. * @package Klarna\Kp\Plugin\Model
  22. */
  23. class MethodListPlugin
  24. {
  25. /**
  26. * @var SessionInitiatorFactory
  27. */
  28. private $sessInitFactory;
  29. /**
  30. * @var ScopeConfigInterface
  31. */
  32. private $config;
  33. /**
  34. * MethodListPlugin constructor.
  35. *
  36. * @param SessionInitiatorFactory $sessInitFactory
  37. * @param ScopeConfigInterface $config
  38. */
  39. public function __construct(SessionInitiatorFactory $sessInitFactory, ScopeConfigInterface $config)
  40. {
  41. $this->sessInitFactory = $sessInitFactory;
  42. $this->config = $config;
  43. }
  44. /**
  45. * Ensure payment methods are initialized before first getting
  46. * list of available payment methods
  47. *
  48. * @param MethodList $subject
  49. * @param CartInterface|null $quote
  50. * @SuppressWarnings(PMD.UnusedFormalParameter)
  51. * @return array
  52. */
  53. public function beforeGetAvailableMethods(MethodList $subject, CartInterface $quote = null)
  54. {
  55. if ($this->isEnabled($quote)) {
  56. $this->getSessionInitiator()->checkAvailable($quote, Kp::METHOD_CODE);
  57. }
  58. return [$quote];
  59. }
  60. /**
  61. * Check to see if we should run or not
  62. *
  63. * @param CartInterface $quote
  64. * @return bool
  65. */
  66. private function isEnabled(CartInterface $quote = null)
  67. {
  68. if (!$quote) {
  69. return false;
  70. }
  71. $store = $quote->getStore();
  72. $scope = ($store === null ? ScopeConfigInterface::SCOPE_TYPE_DEFAULT : ScopeInterface::SCOPE_STORES);
  73. if (!$this->config->isSetFlag('payment/' . Kp::METHOD_CODE . '/active', $scope, $store)) {
  74. return false;
  75. }
  76. return true;
  77. }
  78. /**
  79. * Get SessionInitiator instance
  80. *
  81. * @return SessionInitiatorInterface
  82. */
  83. private function getSessionInitiator()
  84. {
  85. return $this->sessInitFactory->create();
  86. }
  87. }