Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CountryWithWebsites.php
Go to the documentation of this file.
1 <?php
13 
17 
18 class CountryWithWebsites extends \Magento\Eav\Model\Entity\Attribute\Source\Table
19 {
23  private $countriesFactory;
24 
28  private $allowedCountriesReader;
29 
33  private $options;
34 
38  private $storeManager;
39 
43  private $shareConfig;
44 
54  public function __construct(
55  \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory $attrOptionCollectionFactory,
56  \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory $attrOptionFactory,
57  \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countriesFactory,
58  \Magento\Directory\Model\AllowedCountries $allowedCountriesReader,
59  \Magento\Store\Model\StoreManagerInterface $storeManager,
60  \Magento\Customer\Model\Config\Share $shareConfig
61  ) {
62  $this->countriesFactory = $countriesFactory;
63  $this->allowedCountriesReader = $allowedCountriesReader;
64  $this->storeManager = $storeManager;
65  $this->shareConfig = $shareConfig;
66  parent::__construct($attrOptionCollectionFactory, $attrOptionFactory);
67  }
68 
72  public function getAllOptions($withEmpty = true, $defaultValues = false)
73  {
74  if (!$this->options) {
75  $allowedCountries = [];
76  $websiteIds = [];
77 
78  if (!$this->shareConfig->isGlobalScope()) {
79  foreach ($this->storeManager->getWebsites() as $website) {
80  $countries = $this->allowedCountriesReader
81  ->getAllowedCountries(ScopeInterface::SCOPE_WEBSITE, $website->getId());
82  $allowedCountries = array_merge($allowedCountries, $countries);
83 
84  foreach ($countries as $countryCode) {
85  $websiteIds[$countryCode][] = $website->getId();
86  }
87  }
88  } else {
89  $allowedCountries = $this->allowedCountriesReader->getAllowedCountries();
90  }
91 
92  $this->options = $this->createCountriesCollection()
93  ->addFieldToFilter('country_id', ['in' => $allowedCountries])
94  ->toOptionArray();
95 
96  foreach ($this->options as &$option) {
97  if (isset($websiteIds[$option['value']])) {
98  $option['website_ids'] = $websiteIds[$option['value']];
99  }
100  }
101  }
102 
103  return $this->options;
104  }
105 
111  private function createCountriesCollection()
112  {
113  return $this->countriesFactory->create();
114  }
115 }
__construct(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory $attrOptionCollectionFactory, \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory $attrOptionFactory, \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countriesFactory, \Magento\Directory\Model\AllowedCountries $allowedCountriesReader, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Customer\Model\Config\Share $shareConfig)
$storeManager