Address.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "AU" => __("Australia"),
  25. "CA" => __("Canada"),
  26. "DK" => __("Denmark"),
  27. "FR" => __("France"),
  28. "DE" => __("Germany"),
  29. "JP" => __("Japan"),
  30. "NZ" => __("New Zealand"),
  31. "NO" => __("Norway"),
  32. "PL" => __("Poland"),
  33. "ES" => __("Spain"),
  34. "SE" => __("Sweden"),
  35. "CH" => __("Switzerland"),
  36. "GB" => __("United Kingdom"),
  37. "US" => __("United States"),
  38. ];
  39. }
  40. // Magic methods
  41. public function __toString(): string {
  42. return implode("\n", $this->getLines());
  43. }
  44. // Object methods
  45. public function hasGeolocation(): bool {
  46. return isset($this->latitude, $this->longitude);
  47. }
  48. public function geocode(): ?array {
  49. try {
  50. $results = Geolocation::geocode($this->postal_code);
  51. $result = $results[0];
  52. $this->latitude = $result->geometry->location->lat;
  53. $this->longitude = $result->geometry->location->lng;
  54. return [$this->latitude, $this->longitude];
  55. }
  56. catch(Exception $e) {
  57. return null;
  58. }
  59. }
  60. private function getDisplayCountry(): string {
  61. if($this->country) {
  62. return self::getCountryOptions()[$this->country] ?? "";
  63. }
  64. return "";
  65. }
  66. public function getLines(): array {
  67. $county_parts = array_filter([$this->county, $this->state, $this->postal_code]);
  68. return array_filter([
  69. $this->address_1,
  70. $this->address_2,
  71. $this->city,
  72. implode(", ", $county_parts),
  73. $this->getDisplayCountry()
  74. ]);
  75. }
  76. }