GetDistance.php 2.1 KB

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