GetLatLngFromAddress.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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\InventoryDistanceBasedSourceSelectionApi\Model;
  8. use Magento\InventorySourceSelectionApi\Api\Data\AddressInterface;
  9. use Magento\InventoryDistanceBasedSourceSelectionApi\Api\Data\LatLngInterface;
  10. use Magento\InventoryDistanceBasedSourceSelectionApi\Api\GetDistanceProviderCodeInterface;
  11. use Magento\InventoryDistanceBasedSourceSelectionApi\Api\GetLatLngFromAddressInterface;
  12. use Magento\InventoryDistanceBasedSourceSelectionApi\Exception\NoSuchLatLngFromAddressProviderException;
  13. /**
  14. * Get latitude and longitude object from address
  15. *
  16. * @api
  17. */
  18. class GetLatLngFromAddress implements GetLatLngFromAddressInterface
  19. {
  20. /**
  21. * @var GetLatLngFromAddressInterface[]
  22. */
  23. private $providers;
  24. /**
  25. * @var GetDistanceProviderCodeInterface
  26. */
  27. private $getDistanceProviderCode;
  28. /**
  29. * GetLatLngFromSource constructor.
  30. *
  31. * @param GetDistanceProviderCodeInterface $getDistanceProviderCode
  32. * @param GetLatLngFromAddressInterface[] $providers
  33. * @SuppressWarnings(PHPMD.LongVariable)
  34. */
  35. public function __construct(
  36. GetDistanceProviderCodeInterface $getDistanceProviderCode,
  37. array $providers
  38. ) {
  39. foreach ($providers as $providerCode => $provider) {
  40. if (!($provider instanceof GetLatLngFromAddressInterface)) {
  41. throw new \InvalidArgumentException(
  42. 'LatLng provider ' . $providerCode . ' must implement ' . GetLatLngFromAddressInterface::class
  43. );
  44. }
  45. }
  46. $this->providers = $providers;
  47. $this->getDistanceProviderCode = $getDistanceProviderCode;
  48. }
  49. /**
  50. * @inheritdoc
  51. * @throws NoSuchLatLngFromAddressProviderException
  52. */
  53. public function execute(AddressInterface $address): LatLngInterface
  54. {
  55. $code = $this->getDistanceProviderCode->execute();
  56. if (!isset($this->providers[$code])) {
  57. throw new NoSuchLatLngFromAddressProviderException(
  58. __('No such latitude and longitude from address provider: %1', $code)
  59. );
  60. }
  61. return $this->providers[$code]->execute($address);
  62. }
  63. }