osb/app/Models/Site.php

120 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class Site extends Model
{
use HasFactory;
public $timestamps = FALSE;
protected $casts = [
'address'=>'array',
];
/* RELATIONS */
public function country()
{
return $this->belongsTo(Country::class);
}
public function currency()
{
return $this->belongsTo(Currency::class);
}
public function details()
{
return $this->hasMany(SiteDetail::class,NULL,'site_id');
}
public function language()
{
return $this->belongsTo(Language::class);
}
/* ATTRIBUTES */
public function getAllowedKeysAttribute(): Collection
{
return $this->_sampledata()->keys();
}
/* METHODS */
public function __get($key)
{
static $details = NULL;
if ($x = parent::__get($key))
return $x;
// Get the value from the details table
if (($x=$this->detail_item($key)) !== NULL)
return $x;
if (is_null($details))
$details = new SiteDetail;
// Get a default value for this key
$value = $details->sample($key);
// At this point our DB doesnt have this value, we'll log an alert
if ($this->exists)
Log::alert(sprintf('Site is missing value for key [%s] - providing a default [%s]',$key,serialize($value)));
return $value;
}
/* GENERAL METHODS */
/**
* Get a key from the site_details
*
* @param $key
* @return mixed
*/
private function detail_item($key)
{
if (($x=$this->details->search(function($item) use ($key) { return $item->key == $key; })) !== FALSE)
return $this->details->get($x)->value;
return NULL;
}
public function getAddressAttribute(): array
{
return [
$this->site_address1,
$this->site_address2,
sprintf('%s %s %s',$this->site_city.(($this->site_state OR $this->site_postcode) ? ',' : ''),$this->site_state,$this->site_postcode)
];
}
/**
* Add the path to the mail logo, so it can be displayed.
*
* @return string
*/
public function getEmailLogoAttribute()
{
return (($x=$this->detail_item('email_logo')) !== NULL) ? '/storage/'.$x : '/image/generic/150/20/fff';
}
/**
* Add the path to the site logo, so it can be displayed.
*
* @param $value
* @return string
*/
public function getSiteLogoAttribute($value)
{
return (($x=$this->detail_item('site_logo')) !== NULL) ? '/storage/'.$x : '/image/generic/150/20/fff';
}
}