Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Tablerate.php
Go to the documentation of this file.
1 <?php
13 
17 use Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\RateQueryFactory;
18 
27 {
33  protected $_importWebsiteId = 0;
34 
40  protected $_importErrors = [];
41 
47  protected $_importedRows = 0;
48 
54  protected $_importUniqueHash = [];
55 
62 
69 
76  protected $_importRegions;
77 
84 
90  protected $_conditionFullNames = [];
91 
96  protected $coreConfig;
97 
102  protected $logger;
103 
108  protected $storeManager;
109 
114  protected $carrierTablerate;
115 
122  protected $filesystem;
123 
127  private $import;
128 
132  private $rateQueryFactory;
133 
146  public function __construct(
147  \Magento\Framework\Model\ResourceModel\Db\Context $context,
148  \Psr\Log\LoggerInterface $logger,
149  \Magento\Framework\App\Config\ScopeConfigInterface $coreConfig,
150  \Magento\Store\Model\StoreManagerInterface $storeManager,
151  \Magento\OfflineShipping\Model\Carrier\Tablerate $carrierTablerate,
152  \Magento\Framework\Filesystem $filesystem,
153  Import $import,
154  RateQueryFactory $rateQueryFactory,
155  $connectionName = null
156  ) {
157  parent::__construct($context, $connectionName);
158  $this->coreConfig = $coreConfig;
159  $this->logger = $logger;
160  $this->storeManager = $storeManager;
161  $this->carrierTablerate = $carrierTablerate;
162  $this->filesystem = $filesystem;
163  $this->import = $import;
164  $this->rateQueryFactory = $rateQueryFactory;
165  }
166 
172  protected function _construct()
173  {
174  $this->_init('shipping_tablerate', 'pk');
175  }
176 
183  public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request)
184  {
185  $connection = $this->getConnection();
186 
187  $select = $connection->select()->from($this->getMainTable());
189  $rateQuery = $this->rateQueryFactory->create(['request' => $request]);
190 
191  $rateQuery->prepareSelect($select);
192  $bindings = $rateQuery->getBindings();
193 
194  $result = $connection->fetchRow($select, $bindings);
195  // Normalize destination zip code
196  if ($result && $result['dest_zip'] == '*') {
197  $result['dest_zip'] = '';
198  }
199 
200  return $result;
201  }
202 
208  private function deleteByCondition(array $condition)
209  {
210  $connection = $this->getConnection();
211  $connection->beginTransaction();
212  $connection->delete($this->getMainTable(), $condition);
213  $connection->commit();
214  return $this;
215  }
216 
223  private function importData(array $fields, array $values)
224  {
225  $connection = $this->getConnection();
226  $connection->beginTransaction();
227 
228  try {
229  if (count($fields) && count($values)) {
230  $this->getConnection()->insertArray($this->getMainTable(), $fields, $values);
231  $this->_importedRows += count($values);
232  }
233  } catch (\Magento\Framework\Exception\LocalizedException $e) {
234  $connection->rollBack();
235  throw new \Magento\Framework\Exception\LocalizedException(__('Unable to import data'), $e);
236  } catch (\Exception $e) {
237  $connection->rollBack();
238  $this->logger->critical($e);
239  throw new \Magento\Framework\Exception\LocalizedException(
240  __('Something went wrong while importing table rates.')
241  );
242  }
243  $connection->commit();
244  }
245 
257  public function uploadAndImport(\Magento\Framework\DataObject $object)
258  {
262  if (empty($_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'])) {
263  return $this;
264  }
265  $filePath = $_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'];
266 
267  $websiteId = $this->storeManager->getWebsite($object->getScopeId())->getId();
268  $conditionName = $this->getConditionName($object);
269 
270  $file = $this->getCsvFile($filePath);
271  try {
272  // delete old data by website and condition name
273  $condition = [
274  'website_id = ?' => $websiteId,
275  'condition_name = ?' => $conditionName,
276  ];
277  $this->deleteByCondition($condition);
278 
279  $columns = $this->import->getColumns();
280  $conditionFullName = $this->_getConditionFullName($conditionName);
281  foreach ($this->import->getData($file, $websiteId, $conditionName, $conditionFullName) as $bunch) {
282  $this->importData($columns, $bunch);
283  }
284  } catch (\Exception $e) {
285  $this->logger->critical($e);
286  throw new \Magento\Framework\Exception\LocalizedException(
287  __('Something went wrong while importing table rates.')
288  );
289  } finally {
290  $file->close();
291  }
292 
293  if ($this->import->hasErrors()) {
294  $error = __(
295  'We couldn\'t import this file because of these errors: %1',
296  implode(" \n", $this->import->getErrors())
297  );
298  throw new \Magento\Framework\Exception\LocalizedException($error);
299  }
300  }
301 
307  public function getConditionName(\Magento\Framework\DataObject $object)
308  {
309  if ($object->getData('groups/tablerate/fields/condition_name/inherit') == '1') {
310  $conditionName = (string)$this->coreConfig->getValue('carriers/tablerate/condition_name', 'default');
311  } else {
312  $conditionName = $object->getData('groups/tablerate/fields/condition_name/value');
313  }
314  return $conditionName;
315  }
316 
321  private function getCsvFile($filePath)
322  {
323  $pathInfo = pathinfo($filePath);
324  $dirName = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : '';
325  $fileName = isset($pathInfo['basename']) ? $pathInfo['basename'] : '';
326 
327  $directoryRead = $this->filesystem->getDirectoryReadByPath($dirName);
328 
329  return $directoryRead->openFile($fileName);
330  }
331 
338  protected function _getConditionFullName($conditionName)
339  {
340  if (!isset($this->_conditionFullNames[$conditionName])) {
341  $name = $this->carrierTablerate->getCode('condition_name_short', $conditionName);
342  $this->_conditionFullNames[$conditionName] = $name;
343  }
344 
345  return $this->_conditionFullNames[$conditionName];
346  }
347 
354  protected function _saveImportData(array $data)
355  {
356  if (!empty($data)) {
357  $columns = [
358  'website_id',
359  'dest_country_id',
360  'dest_region_id',
361  'dest_zip',
362  'condition_name',
363  'condition_value',
364  'price',
365  ];
366  $this->getConnection()->insertArray($this->getMainTable(), $columns, $data);
367  $this->_importedRows += count($data);
368  }
369 
370  return $this;
371  }
372 }
getConditionName(\Magento\Framework\DataObject $object)
Definition: Tablerate.php:307
$fields
Definition: details.phtml:14
$values
Definition: options.phtml:88
__()
Definition: __.php:13
$columns
Definition: default.phtml:15
$fileName
Definition: translate.phtml:15
$connection
Definition: bulk.php:13
__construct(\Magento\Framework\Model\ResourceModel\Db\Context $context, \Psr\Log\LoggerInterface $logger, \Magento\Framework\App\Config\ScopeConfigInterface $coreConfig, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\OfflineShipping\Model\Carrier\Tablerate $carrierTablerate, \Magento\Framework\Filesystem $filesystem, Import $import, RateQueryFactory $rateQueryFactory, $connectionName=null)
Definition: Tablerate.php:146
if(!isset($_GET['name'])) $name
Definition: log.php:14