clrghouz/app/Models/System.php

135 lines
2.8 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\Auth;
use App\Http\Controllers\DomainController;
class System extends Model
{
use HasFactory;
protected $dates = ['last_session'];
/* SCOPES */
/**
* Only query active records
*/
public function scopeActive($query)
{
$uo = Auth::user();
return $query
->when(! $uo->isAdmin(),function($query) use ($uo) {
return $query->whereIn('id',$uo->systems->pluck('id'))
->orWhere($this->getTable().'.active',TRUE);
})
->orderBy('name');
}
/* RELATIONS */
public function addresses()
{
return $this->hasMany(Address::class)
->orderBy('region_id')
->orderBy('host_id')
->orderBy('node_id')
->orderBy('point_id');
}
/**
* Session Passwords for system
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function sessions()
{
return $this->belongsToMany(Zone::class)
->withPivot(['sespass','pktpass','ticpass','fixpass','zt_ipv4','zt_ipv6','default']);
}
/**
* If this system is configured as this host
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function setup()
{
return $this->hasOne(Setup::class);
}
public function users()
{
return $this->belongsToMany(User::class);
}
/**
* This system is the ZC for the following zones
*/
public function zcs()
{
return $this->hasMany(Zone::class);
}
/**
* Zones a system has addresses for
*
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
public function zones()
{
return $this->hasManyThrough(Zone::class,Address::class,'system_id','id','id','zone_id');
}
/* METHODS */
public function echoareas()
{
return Echoarea::select('echoareas.*')
->join('address_echoarea',['address_echoarea.echoarea_id'=>'echoareas.id'])
->join('addresses',['addresses.id'=>'address_echoarea.address_id'])
->where('addresses.system_id',$this->id);
}
/**
* Return the system name, or role name for the zone
*
* @param Address $o
* @return string
*/
public function full_name(Address $o): string
{
switch ($o->attributes['role']) {
case DomainController::NODE_ZC;
return sprintf('ZC-%s-%05d',$o->zone->domain->name,$o->zone->zone_id);
case DomainController::NODE_RC;
return sprintf('RC-%s-%05d',$o->zone->domain->name,$o->region_id);
case DomainController::NODE_NC;
return sprintf('NC-%s-%05d',$o->zone->domain->name,$o->host_id);
case DomainController::NODE_HC;
case NULL:
default:
return $this->name;
}
}
/**
* Return the system's address in the same zone
*
* @param Zone $o
* @return Collection
*/
public function match(Zone $o): Collection
{
return $this->addresses->where('zone_id',$o->id);
}
}