Transition to using a json column for all external urls of a place

This commit is contained in:
Jonny Barnes 2017-06-30 13:21:40 +01:00
parent 31ae5b749b
commit 4afb6a3ae9
4 changed files with 47 additions and 10 deletions

View file

@ -76,6 +76,19 @@ class Place extends Model
return $query->where($field, '<=', $distance)->orderBy($field);
}
public function scopeWhereExternalURL(Builder $query, string $url)
{
$type = $this->getType($url);
if ($type === null) {
// we havent set a type, therefore result must be empty set
// id cant be null, so this will return empty set
return $query->whereNull('id');
}
return $query->where('external_urls', '@>', json_encode([
$type => $url
]));
}
/**
* Get the latitude from the `location` property.
*
@ -115,4 +128,31 @@ class Place extends Model
{
return config('app.shorturl') . '/places/' . $this->slug;
}
public function setExternalUrlsAttribute($value)
{
$type = $this->getType($value);
if ($type === null) {
throw new \Exception('Unkown external url type');
}
$already = [];
if (array_key_exists('external_urls', $this->attributes)) {
$already = json_decode($this->attributes['external_urls'], true);
}
$already[$type] = $value;
$this->attributes['external_urls'] = json_encode($already);
}
private function getType(string $url): ?string
{
$host = parse_url($url, PHP_URL_HOST);
if (ends_with($host, 'foursquare.com') === true) {
return 'foursquare';
}
if (ends_with($host, 'openstreetmap.org') === true) {
return 'osm';
}
return null;
}
}