Address.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. $county_parts = array_filter([$this->county, $this->state, $this->postal_code]);
  43. $lines = array_filter([
  44. $this->address_1,
  45. $this->address_2,
  46. $this->city,
  47. implode(", ", $county_parts),
  48. $this->getDisplayCountry()
  49. ]);
  50. return implode("\n", $lines);
  51. }
  52. // Object methods
  53. public function hasGeolocation(): bool {
  54. return isset($this->latitude, $this->longitude);
  55. }
  56. public function geocode(): ?array {
  57. try {
  58. $results = Geolocation::geocode($this->postal_code);
  59. $result = $results[0];
  60. $this->latitude = $result->geometry->location->lat;
  61. $this->longitude = $result->geometry->location->lng;
  62. return [$this->latitude, $this->longitude];
  63. }
  64. catch(Exception $e) {
  65. return null;
  66. }
  67. }
  68. private function getDisplayCountry(): string {
  69. if($this->country) {
  70. return self::getCountryOptions()[$this->country] ?? "";
  71. }
  72. return "";
  73. }
  74. }