ColumnResolver.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate\CSV;
  7. class ColumnResolver
  8. {
  9. const COLUMN_COUNTRY = 'Country';
  10. const COLUMN_REGION = 'Region/State';
  11. const COLUMN_ZIP = 'Zip/Postal Code';
  12. const COLUMN_WEIGHT = 'Weight (and above)';
  13. const COLUMN_WEIGHT_DESTINATION = 'Weight (and above)';
  14. const COLUMN_PRICE = 'Shipping Price';
  15. /**
  16. * @var array
  17. */
  18. private $nameToPositionIdMap = [
  19. self::COLUMN_COUNTRY => 0,
  20. self::COLUMN_REGION => 1,
  21. self::COLUMN_ZIP => 2,
  22. self::COLUMN_WEIGHT => 3,
  23. self::COLUMN_WEIGHT_DESTINATION => 3,
  24. self::COLUMN_PRICE => 4,
  25. ];
  26. /**
  27. * @var array
  28. */
  29. private $headers;
  30. /**
  31. * ColumnResolver constructor.
  32. * @param array $headers
  33. * @param array $columns
  34. */
  35. public function __construct(array $headers, array $columns = [])
  36. {
  37. $this->nameToPositionIdMap = array_merge($this->nameToPositionIdMap, $columns);
  38. $this->headers = array_map('trim', $headers);
  39. }
  40. /**
  41. * @param string $column
  42. * @param array $values
  43. * @return string|int|float|null
  44. * @throws ColumnNotFoundException
  45. */
  46. public function getColumnValue($column, array $values)
  47. {
  48. $column = (string) $column;
  49. $columnIndex = array_search($column, $this->headers, true);
  50. if (false === $columnIndex) {
  51. if (array_key_exists($column, $this->nameToPositionIdMap)) {
  52. $columnIndex = $this->nameToPositionIdMap[$column];
  53. } else {
  54. throw new ColumnNotFoundException(__('Requested column "%1" cannot be resolved', $column));
  55. }
  56. }
  57. if (!array_key_exists($columnIndex, $values)) {
  58. throw new ColumnNotFoundException(__('Column "%1" not found', $column));
  59. }
  60. return trim($values[$columnIndex]);
  61. }
  62. }