Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
UpdateTaxRegionId.php
Go to the documentation of this file.
1 <?php
8 
15 use Magento\Tax\Setup\TaxSetupFactory;
16 
18 {
22  private $moduleDataSetup;
23 
27  private $taxRateRepository;
28 
32  private $searchCriteriaFactory;
33 
37  private $regionFactory;
38 
46  public function __construct(
47  \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup,
48  TaxRateRepositoryInterface $taxRateRepository,
49  SearchCriteriaFactory $searchCriteriaFactory,
50  \Magento\Directory\Model\RegionFactory $regionFactory
51  ) {
52  $this->moduleDataSetup = $moduleDataSetup;
53  $this->taxRateRepository = $taxRateRepository;
54  $this->searchCriteriaFactory = $searchCriteriaFactory;
55  $this->regionFactory = $regionFactory;
56  }
57 
61  public function apply()
62  {
63  $this->moduleDataSetup->getConnection()->startSetup();
64 
65  //Update the tax_region_id
66  $taxRateList = $this->taxRateRepository->getList($this->searchCriteriaFactory->create());
68  foreach ($taxRateList->getItems() as $taxRateData) {
69  $regionCode = $this->parseRegionFromTaxCode($taxRateData->getCode());
70  if ($regionCode) {
72  $region = $this->regionFactory->create();
73  $region->loadByCode($regionCode, $taxRateData->getTaxCountryId());
74  if ($taxRateData->getTaxPostcode() === null) {
75  $taxRateData->setTaxPostcode('*');
76  }
77  $taxRateData->setTaxRegionId($region->getRegionId());
78  $this->taxRateRepository->save($taxRateData);
79  }
80  }
81  $this->moduleDataSetup->getConnection()->endSetup();
82  }
83 
87  public static function getDependencies()
88  {
89  return [
90  UpdateTaxClassAttributeVisibility::class
91  ];
92  }
93 
97  public static function getVersion()
98  {
99  return '2.0.3';
100  }
101 
105  public function getAliases()
106  {
107  return [];
108  }
109 
116  private function parseRegionFromTaxCode($taxCode)
117  {
118  $result = '';
119  $parts = explode('-', $taxCode, 3);
120 
121  if (isset($parts[1])) {
122  $result = $parts[1];
123  }
124 
125  return $result;
126  }
127 }
__construct(\Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup, TaxRateRepositoryInterface $taxRateRepository, SearchCriteriaFactory $searchCriteriaFactory, \Magento\Directory\Model\RegionFactory $regionFactory)