user_address.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. // Static method
  28. public static function getByUser(int $id, User $user) {
  29. return UserAddress::queryOne([
  30. "id" => $id,
  31. "user_id" => $user->id
  32. ]);
  33. }
  34. // Object methods
  35. /**
  36. * @return User|null
  37. * @throws Exception
  38. */
  39. public function getUser(): ?User {
  40. return User::get($this->user_id);
  41. }
  42. /**
  43. * @return string
  44. */
  45. public function getDisplayAddress(): string {
  46. $parts = [];
  47. $fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"];
  48. foreach($fields as $field) {
  49. $parts[] = $this->$field;
  50. }
  51. return implode(", ", array_filter($parts));
  52. }
  53. /**
  54. * @return array
  55. */
  56. public function getGeolocation(): array {
  57. return [$this->latitude, $this->longitude];
  58. }
  59. public function geocode(): bool {
  60. try {
  61. $results = Geolocation::geocode($this->postal_code . ", " . $this->country);
  62. $result = $results[0];
  63. foreach($result->address_components as $component) {
  64. $types = $component->types;
  65. if(in_array("postal_code", $types)) $this->postal_code = $component->long_name;
  66. if(in_array("route", $types)) $this->address_1 = $component->long_name;
  67. if(in_array("postal_town", $types)) $this->city = $component->long_name;
  68. if(in_array("administrative_area_level_1", $types)) $this->state = $component->long_name;
  69. if(in_array("country", $types)) $this->country = $component->long_name;
  70. }
  71. $this->latitude = $result->geometry->location->lat;
  72. $this->longitude = $result->geometry->location->lng;
  73. return true;
  74. }
  75. catch(Exception $e) {
  76. return false;
  77. }
  78. }
  79. }