Address.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App;
  3. use Exception;
  4. /**
  5. * Class Address
  6. * @property int $id
  7. * @property string $address_1
  8. * @property string $address_2
  9. * @property string $city
  10. * @property string $county
  11. * @property string $postal_code
  12. * @property string $state
  13. * @property string $country
  14. * @property float $latitude
  15. * @property float $longitude
  16. */
  17. class Address extends Model {
  18. protected static $table = "address";
  19. protected static $idField = "id";
  20. protected static $fillableFields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country", "latitude", "longitude"];
  21. // Static methods
  22. public static function getCountryOptions(): array {
  23. return [
  24. "GB" => __("United Kingdom"),
  25. "AU" => __("Australia"),
  26. "BG" => __("Bulgaria"),
  27. "CA" => __("Canada"),
  28. "CN" => __("China"),
  29. "CZ" => __("Czech Republic"),
  30. "DK" => __("Denmark"),
  31. "FR" => __("France"),
  32. "DE" => __("Germany"),
  33. "HK" => __("Hong Kong"),
  34. "IE" => __("Ireland"),
  35. "IT" => __("Italy"),
  36. "JP" => __("Japan"),
  37. "NZ" => __("New Zealand"),
  38. "NO" => __("Norway"),
  39. "PL" => __("Poland"),
  40. "ES" => __("Spain"),
  41. "SE" => __("Sweden"),
  42. "CH" => __("Switzerland"),
  43. "US" => __("United States"),
  44. ];
  45. }
  46. // Magic methods
  47. public function __toString(): string {
  48. return implode("\n", $this->getLines());
  49. }
  50. // Object methods
  51. public function hasGeolocation(): bool {
  52. return isset($this->latitude, $this->longitude);
  53. }
  54. public function geocode(): ?array {
  55. try {
  56. $results = Geolocation::geocode($this->postal_code);
  57. $result = $results[0];
  58. $this->latitude = $result->geometry->location->lat;
  59. $this->longitude = $result->geometry->location->lng;
  60. return [$this->latitude, $this->longitude];
  61. }
  62. catch(Exception $e) {
  63. return null;
  64. }
  65. }
  66. private function getDisplayCountry(): string {
  67. if($this->country) {
  68. return self::getCountryOptions()[$this->country] ?? "";
  69. }
  70. return "";
  71. }
  72. public function getLines(): array {
  73. $county_parts = array_filter([$this->county, $this->state, $this->postal_code]);
  74. return array_values(array_filter([
  75. $this->address_1,
  76. $this->address_2,
  77. $this->city,
  78. implode(", ", $county_parts),
  79. $this->getDisplayCountry()
  80. ]));
  81. }
  82. public function getLinesHtml(): string {
  83. return nl2br(htmlspecialchars(implode("\n", $this->getLines())));
  84. }
  85. }