|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\CustomerGraphQl\Model\Context; |
| 9 | + |
| 10 | +use Magento\Authorization\Model\UserContextInterface; |
| 11 | +use Magento\GraphQl\Model\Query\ContextParametersInterface; |
| 12 | +use Magento\GraphQl\Model\Query\ContextParametersProcessorInterface; |
| 13 | +use Magento\Customer\Model\Session as CustomerSession; |
| 14 | +use Magento\Customer\Model\Group; |
| 15 | +use Magento\Customer\Api\CustomerRepositoryInterface; |
| 16 | +use Magento\Framework\Exception\LocalizedException; |
| 17 | + |
| 18 | +/** |
| 19 | + * @inheritdoc |
| 20 | + */ |
| 21 | +class AddCustomerGroupToContext implements ContextParametersProcessorInterface |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @var CustomerSession |
| 25 | + */ |
| 26 | + private $customerSession; |
| 27 | + |
| 28 | + /** |
| 29 | + * @var CustomerRepositoryInterface |
| 30 | + */ |
| 31 | + private $customerRepository; |
| 32 | + |
| 33 | + /** |
| 34 | + * @param CustomerSession $customerSession |
| 35 | + * @param CustomerRepositoryInterface $customerRepository |
| 36 | + */ |
| 37 | + public function __construct( |
| 38 | + CustomerSession $customerSession, |
| 39 | + CustomerRepositoryInterface $customerRepository |
| 40 | + ) { |
| 41 | + $this->customerSession = $customerSession; |
| 42 | + $this->customerRepository = $customerRepository; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * @inheritdoc |
| 47 | + */ |
| 48 | + public function execute(ContextParametersInterface $contextParameters): ContextParametersInterface |
| 49 | + { |
| 50 | + $customerSession = $this->customerSession; |
| 51 | + $customerGroupId = null; |
| 52 | + if ($contextParameters->getUserType() === UserContextInterface::USER_TYPE_GUEST) { |
| 53 | + $customerGroupId = Group::NOT_LOGGED_IN_ID; |
| 54 | + } elseif ($contextParameters->getExtensionAttributes()->getIsCustomer() === true) { |
| 55 | + try { |
| 56 | + $customer = $this->customerRepository->getById($contextParameters->getUserId()); |
| 57 | + $customerGroupId = (int) $customer->getGroupId(); |
| 58 | + } catch (LocalizedException $e) { |
| 59 | + $customerGroupId = null; |
| 60 | + } |
| 61 | + } |
| 62 | + if ($customerGroupId !== null) { |
| 63 | + $customerSession->setCustomerGroupId($customerGroupId); |
| 64 | + $contextParameters->addExtensionAttribute('customer_group_id', $customerGroupId); |
| 65 | + } |
| 66 | + return $contextParameters; |
| 67 | + } |
| 68 | +} |
0 commit comments