Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AllowedCountries.php
Go to the documentation of this file.
1 <?php
8 
12 
20 {
21  const ALLOWED_COUNTRIES_PATH = 'general/country/allow';
22 
26  private $scopeConfig;
27 
31  private $storeManager;
32 
38  public function __construct(
39  ScopeConfigInterface $scopeConfig,
40  StoreManagerInterface $storeManager
41  ) {
42  $this->scopeConfig = $scopeConfig;
43  $this->storeManager = $storeManager;
44  }
45 
54  public function getAllowedCountries(
55  $scope = ScopeInterface::SCOPE_WEBSITE,
56  $scopeCode = null
57  ) {
58  if ($scopeCode === null) {
59  $scopeCode = $this->getDefaultScopeCode($scope);
60  }
61 
62  switch ($scope) {
63  case ScopeInterface::SCOPE_WEBSITES:
64  case ScopeInterface::SCOPE_STORES:
65  $allowedCountries = [];
66  foreach ($scopeCode as $singleFilter) {
67  $allowedCountries = array_merge(
68  $allowedCountries,
69  $this->getCountriesFromConfig($this->getSingleScope($scope), $singleFilter)
70  );
71  }
72  break;
73  default:
74  $allowedCountries = $this->getCountriesFromConfig($scope, $scopeCode);
75  }
76 
77  return $this->makeCountriesUnique($allowedCountries);
78  }
79 
87  private function getDefaultScopeCode($scope)
88  {
89  switch ($scope) {
90  case ScopeInterface::SCOPE_WEBSITE:
91  return $this->storeManager->getWebsite()->getId();
92  case ScopeInterface::SCOPE_STORE:
93  return $this->storeManager->getStore()->getId();
94  case ScopeInterface::SCOPE_GROUP:
95  return $this->storeManager->getGroup()->getId();
96  case ScopeInterface::SCOPE_WEBSITES:
97  return [$this->storeManager->getWebsite()->getId()];
98  case ScopeInterface::SCOPE_STORES:
99  return [$this->storeManager->getStore()->getId()];
100  default:
101  throw new \InvalidArgumentException("Invalid scope is specified");
102  }
103  }
104 
112  public function makeCountriesUnique(array $allowedCountries)
113  {
114  return array_combine($allowedCountries, $allowedCountries);
115  }
116 
125  public function getCountriesFromConfig($scope, $scopeCode)
126  {
127  return explode(
128  ',',
129  (string) $this->scopeConfig->getValue(
130  self::ALLOWED_COUNTRIES_PATH,
131  $scope,
132  $scopeCode
133  )
134  );
135  }
136 
143  private function getSingleScope($scope)
144  {
145  if ($scope == ScopeInterface::SCOPE_WEBSITES) {
146  return ScopeInterface::SCOPE_WEBSITE;
147  }
148 
149  if ($scope == ScopeInterface::SCOPE_STORES) {
150  return ScopeInterface::SCOPE_STORE;
151  }
152 
153  return $scope;
154  }
155 }
getAllowedCountries( $scope=ScopeInterface::SCOPE_WEBSITE, $scopeCode=null)
makeCountriesUnique(array $allowedCountries)
$storeManager
__construct(ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager)