user_address.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Class UserAddress
  4. *
  5. * @property int $id
  6. * @property int $user_id
  7. * @property string $name
  8. * @property string $address_1
  9. * @property string $address_2
  10. * @property string $city
  11. * @property string $county
  12. * @property string $postal_code
  13. * @property string $state
  14. * @property string $country
  15. * @property double $latitude
  16. * @property double $longitude
  17. * @property float $max_radius_miles
  18. * @property bool $invoice
  19. */
  20. class UserAddress extends Model {
  21. protected static $table = "user_address";
  22. protected static $id_field = "id";
  23. protected static $fillable_fields = ["user_id", "name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "latitude", "longitude", "max_radius_miles", "invoice"];
  24. const RADIUSES = [
  25. "0.25", "0.50", "1.00", "1.50", "2.00", "2.50", "3.00", "4.00", "5.00", "7.50", "10.00", "12.50", "15.00", "20.00", "25.00",
  26. ];
  27. // Object methods
  28. /**
  29. * @return User|null
  30. * @throws Exception
  31. */
  32. public function getUser(): ?User {
  33. return User::get($this->user_id);
  34. }
  35. /**
  36. * @return string
  37. */
  38. public function getDisplayAddress(): string {
  39. $parts = [];
  40. $fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"];
  41. foreach($fields as $field) {
  42. $parts[] = $this->$field;
  43. }
  44. return implode(", ", array_filter($parts));
  45. }
  46. /**
  47. * @return array
  48. */
  49. public function getGeolocation(): array {
  50. return [$this->latitude, $this->longitude];
  51. }
  52. public function geocode(): bool {
  53. try {
  54. $results = Geolocation::geocode($this->postal_code . ", " . $this->country);
  55. $result = $results[0];
  56. foreach($result->address_components as $component) {
  57. $types = $component->types;
  58. if(in_array("postal_code", $types)) $this->postal_code = $component->long_name;
  59. if(in_array("route", $types)) $this->address_1 = $component->long_name;
  60. if(in_array("postal_town", $types)) $this->city = $component->long_name;
  61. if(in_array("administrative_area_level_1", $types)) $this->state = $component->long_name;
  62. if(in_array("country", $types)) $this->country = $component->long_name;
  63. }
  64. $this->latitude = $result->geometry->location->lat;
  65. $this->longitude = $result->geometry->location->lng;
  66. return true;
  67. }
  68. catch(Exception $e) {
  69. return false;
  70. }
  71. }
  72. }