FillSourceLatitudeAndLongitude.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\Plugin;
  8. use Magento\InventoryApi\Api\Data\SourceInterface;
  9. use Magento\InventoryApi\Api\SourceRepositoryInterface;
  10. use Magento\InventoryDistanceBasedSourceSelection\Model\DistanceProvider\GetLatLngFromSource;
  11. use Magento\InventoryDistanceBasedSourceSelectionApi\Model\GetLatLngFromSourceInterface;
  12. /**
  13. * Compute latitude and longitude for a source if none is defined
  14. */
  15. class FillSourceLatitudeAndLongitude
  16. {
  17. /**
  18. * @var GetLatLngFromSource
  19. */
  20. private $getLatLngFromSource;
  21. /**
  22. * ComputeSourceLatitudeAndLongitude constructor.
  23. *
  24. * @param GetLatLngFromSource $getLatLngFromSource
  25. * @SuppressWarnings(PHPMD.LongVariable)
  26. */
  27. public function __construct(
  28. GetLatLngFromSource $getLatLngFromSource
  29. ) {
  30. $this->getLatLngFromSource = $getLatLngFromSource;
  31. }
  32. /**
  33. * Calculate latitude and longitude using google map if api key is defined
  34. *
  35. * @param SourceRepositoryInterface $subject
  36. * @param SourceInterface $source
  37. * @return array
  38. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  39. */
  40. public function beforeSave(
  41. SourceRepositoryInterface $subject,
  42. SourceInterface $source
  43. ): array {
  44. if (!$source->getLatitude() && !$source->getLongitude()) {
  45. try {
  46. $latLng = $this->getLatLngFromSource->execute($source);
  47. $source->setLatitude($latLng->getLat());
  48. $source->setLongitude($latLng->getLng());
  49. } catch (\Exception $e) {
  50. unset($e); // Silently fail geo coding
  51. }
  52. }
  53. return [$source];
  54. }
  55. }