StringFormatter.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the Geocoder package.
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. *
  8. * @license MIT License
  9. */
  10. namespace Geocoder\Formatter;
  11. use Geocoder\Model\AdminLevelCollection;
  12. use Geocoder\Location;
  13. /**
  14. * @author William Durand <william.durand1@gmail.com>
  15. */
  16. final class StringFormatter
  17. {
  18. const STREET_NUMBER = '%n';
  19. const STREET_NAME = '%S';
  20. const LOCALITY = '%L';
  21. const POSTAL_CODE = '%z';
  22. const SUB_LOCALITY = '%D';
  23. const ADMIN_LEVEL = '%A';
  24. const ADMIN_LEVEL_CODE = '%a';
  25. const COUNTRY = '%C';
  26. const COUNTRY_CODE = '%c';
  27. const TIMEZONE = '%T';
  28. /**
  29. * Transform an `Address` instance into a string representation.
  30. *
  31. * @param Location $location
  32. * @param string $format
  33. *
  34. * @return string
  35. */
  36. public function format(Location $location, string $format): string
  37. {
  38. $countryName = null;
  39. $code = null;
  40. if (null !== $country = $location->getCountry()) {
  41. $countryName = $country->getName();
  42. if (null !== $code = $country->getCode()) {
  43. $code = strtoupper($code);
  44. }
  45. }
  46. $replace = [
  47. self::STREET_NUMBER => $location->getStreetNumber(),
  48. self::STREET_NAME => $location->getStreetName(),
  49. self::LOCALITY => $location->getLocality(),
  50. self::POSTAL_CODE => $location->getPostalCode(),
  51. self::SUB_LOCALITY => $location->getSubLocality(),
  52. self::COUNTRY => $countryName,
  53. self::COUNTRY_CODE => $code,
  54. self::TIMEZONE => $location->getTimezone(),
  55. ];
  56. for ($level = 1; $level <= AdminLevelCollection::MAX_LEVEL_DEPTH; ++$level) {
  57. $replace[self::ADMIN_LEVEL.$level] = null;
  58. $replace[self::ADMIN_LEVEL_CODE.$level] = null;
  59. }
  60. foreach ($location->getAdminLevels() as $level => $adminLevel) {
  61. $replace[self::ADMIN_LEVEL.$level] = $adminLevel->getName();
  62. $replace[self::ADMIN_LEVEL_CODE.$level] = $adminLevel->getCode();
  63. }
  64. return strtr($format, $replace);
  65. }
  66. }