Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Context.php
Go to the documentation of this file.
1 <?php
8 
9 use Magento\Framework\App\Http\Context as HttpContext;
17 
21 class Context
22 {
26  protected $session;
27 
31  protected $httpContext;
32 
36  protected $storeManager;
37 
42 
49  public function __construct(
50  \Magento\Framework\Session\SessionManagerInterface $session,
51  \Magento\Framework\App\Http\Context $httpContext,
54  ) {
55  $this->session = $session;
56  $this->httpContext = $httpContext;
57  $this->storeManager = $storeManager;
58  $this->storeCookieManager = $storeCookieManager;
59  }
60 
69  public function beforeDispatch(
70  AbstractAction $subject,
72  ) {
73  if ($this->isAlreadySet()) {
74  //If required store related value were already set for
75  //HTTP processors then just continuing as we were.
76  return;
77  }
78 
80  $storeCode = $request->getParam(
82  $this->storeCookieManager->getStoreCodeFromCookie()
83  );
84  if (is_array($storeCode)) {
85  if (!isset($storeCode['_data']['code'])) {
86  $this->processInvalidStoreRequested();
87  }
88  $storeCode = $storeCode['_data']['code'];
89  }
90  if ($storeCode === '') {
91  //Empty code - is an invalid code and it was given explicitly
92  //(the value would be null if the code wasn't found).
93  $this->processInvalidStoreRequested();
94  }
95  try {
96  $currentStore = $this->storeManager->getStore($storeCode);
97  } catch (NoSuchEntityException $exception) {
98  $this->processInvalidStoreRequested($exception);
99  }
100 
101  $this->updateContext($currentStore);
102  }
103 
111  private function processInvalidStoreRequested(
112  \Throwable $previousException = null
113  ) {
114  $store = $this->storeManager->getStore();
115  $this->updateContext($store);
116 
117  throw new NotFoundException(
118  $previousException
119  ? __($previousException->getMessage())
120  : __('Invalid store requested.'),
121  $previousException
122  );
123  }
124 
131  private function updateContext(StoreInterface $store)
132  {
133  $this->httpContext->setValue(
135  $store->getCode(),
136  $this->storeManager->getDefaultStoreView()->getCode()
137  );
138 
140  $defaultStore = $this->storeManager->getWebsite()->getDefaultStore();
141  $this->httpContext->setValue(
142  HttpContext::CONTEXT_CURRENCY,
143  $this->session->getCurrencyCode()
144  ?: $store->getDefaultCurrencyCode(),
145  $defaultStore->getDefaultCurrencyCode()
146  );
147  }
148 
154  private function isAlreadySet(): bool
155  {
157 
158  return $this->httpContext->getValue($storeKey) !== null;
159  }
160 }
__()
Definition: __.php:13
__construct(\Magento\Framework\Session\SessionManagerInterface $session, \Magento\Framework\App\Http\Context $httpContext, \Magento\Store\Model\StoreManagerInterface $storeManager, StoreCookieManagerInterface $storeCookieManager)
Definition: Context.php:49
$storeCode
Definition: indexer.php:15
$currentStore
Definition: queue.php:17