GetGeoNameDataByAddress.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\InventoryDistanceBasedSourceSelection\Model\ResourceModel;
  8. use Magento\Framework\App\ResourceConnection;
  9. use Magento\Framework\Exception\NoSuchEntityException;
  10. use Magento\InventoryDistanceBasedSourceSelection\Model\Convert\AddressToString;
  11. use Magento\InventorySourceSelectionApi\Api\Data\AddressInterface;
  12. /**
  13. * Get geoname data by postcode
  14. */
  15. class GetGeoNameDataByAddress
  16. {
  17. /**
  18. * @var ResourceConnection
  19. */
  20. private $resourceConnection;
  21. /**
  22. * @var AddressToString
  23. */
  24. private $addressToString;
  25. /**
  26. * GetGeoNameDataByPostcode constructor.
  27. *
  28. * @param ResourceConnection $resourceConnection
  29. * @param AddressToString $addressToString
  30. */
  31. public function __construct(
  32. ResourceConnection $resourceConnection,
  33. AddressToString $addressToString
  34. ) {
  35. $this->resourceConnection = $resourceConnection;
  36. $this->addressToString = $addressToString;
  37. }
  38. /**
  39. * Return geonames information using a fallback mechanism
  40. *
  41. * @param AddressInterface $address
  42. * @return array
  43. * @throws NoSuchEntityException
  44. */
  45. public function execute(AddressInterface $address): array
  46. {
  47. $connection = $this->resourceConnection->getConnection();
  48. $tableName = $this->resourceConnection->getTableName('inventory_geoname');
  49. $qry = $connection->select()->from($tableName)
  50. ->where('country_code = ?', $address->getCountry())
  51. ->where('postcode = ?', $address->getPostcode())
  52. ->limit(1);
  53. $row = $connection->fetchRow($qry);
  54. if (!$row) {
  55. $qry = $connection->select()->from($tableName)
  56. ->where('country_code = ?', $address->getCountry())
  57. ->where('city = ?', $address->getCity())
  58. ->limit(1);
  59. $row = $connection->fetchRow($qry);
  60. }
  61. if (!$row) {
  62. $qry = $connection->select()->from($tableName)
  63. ->where('country_code = ?', $address->getCountry())
  64. ->where('region = ?', $address->getRegion())
  65. ->limit(1);
  66. $row = $connection->fetchRow($qry);
  67. }
  68. if (!$row) {
  69. throw new NoSuchEntityException(
  70. __('Unknown geoname for %1', $this->addressToString->execute($address))
  71. );
  72. }
  73. return $row;
  74. }
  75. }