Address.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. "IT" => __("Italy"),
  35. "JP" => __("Japan"),
  36. "NZ" => __("New Zealand"),
  37. "NO" => __("Norway"),
  38. "PL" => __("Poland"),
  39. "ES" => __("Spain"),
  40. "SE" => __("Sweden"),
  41. "CH" => __("Switzerland"),
  42. "US" => __("United States"),
  43. ];
  44. }
  45. // Magic methods
  46. public function __toString(): string {
  47. return implode("\n", $this->getLines());
  48. }
  49. // Object methods
  50. public function hasGeolocation(): bool {
  51. return isset($this->latitude, $this->longitude);
  52. }
  53. public function geocode(): ?array {
  54. try {
  55. $results = Geolocation::geocode($this->postal_code);
  56. $result = $results[0];
  57. $this->latitude = $result->geometry->location->lat;
  58. $this->longitude = $result->geometry->location->lng;
  59. return [$this->latitude, $this->longitude];
  60. }
  61. catch(Exception $e) {
  62. return null;
  63. }
  64. }
  65. private function getDisplayCountry(): string {
  66. if($this->country) {
  67. return self::getCountryOptions()[$this->country] ?? "";
  68. }
  69. return "";
  70. }
  71. public function getLines(): array {
  72. $county_parts = array_filter([$this->county, $this->state, $this->postal_code]);
  73. return array_values(array_filter([
  74. $this->address_1,
  75. $this->address_2,
  76. $this->city,
  77. implode(", ", $county_parts),
  78. $this->getDisplayCountry()
  79. ]));
  80. }
  81. public function getLinesHtml(): string {
  82. return nl2br(htmlspecialchars(implode("\n", $this->getLines())));
  83. }
  84. }