ctrlpanel/app/Models/Location.php

86 lines
2 KiB
PHP
Raw Normal View History

2021-06-05 09:26:32 +00:00
<?php
namespace App\Models;
2021-06-05 09:26:32 +00:00
use App\Classes\Pterodactyl;
2021-06-05 09:26:32 +00:00
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
use HasFactory;
public $incrementing = false;
public $guarded = [];
2021-11-07 11:07:30 +00:00
public static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
static::deleting(function (Location $location) {
$location->nodes()->each(function (Node $node) {
$node->delete();
});
});
2021-06-05 09:26:32 +00:00
}
/**
* Sync locations with pterodactyl panel
*
2021-06-05 09:26:32 +00:00
* @throws Exception
*/
2021-11-07 11:07:30 +00:00
public static function syncLocations()
{
$locations = Pterodactyl::getLocations();
2021-06-05 09:26:32 +00:00
2021-11-07 11:07:30 +00:00
//map response
$locations = array_map(function ($val) {
return [
'id' => $val['attributes']['id'],
'name' => $val['attributes']['short'],
'description' => $val['attributes']['long'],
];
2021-06-05 09:26:32 +00:00
}, $locations);
2021-11-07 11:07:30 +00:00
//update or create
2021-06-05 09:26:32 +00:00
foreach ($locations as $location) {
2021-11-07 11:07:30 +00:00
self::query()->updateOrCreate(
[
'id' => $location['id'],
2021-11-07 11:07:30 +00:00
],
[
'name' => $location['name'],
2021-11-07 11:07:30 +00:00
'description' => $location['name'],
]
);
2021-06-05 09:26:32 +00:00
}
2021-11-07 11:07:30 +00:00
self::removeDeletedLocation($locations);
}
/**
* @description remove locations that have been deleted on pterodactyl
*
* @param array $locations
2021-11-07 11:07:30 +00:00
*/
private static function removeDeletedLocation(array $locations): void
{
$ids = array_map(function ($data) {
return $data['id'];
}, $locations);
self::all()->each(function (Location $location) use ($ids) {
if (! in_array($location->id, $ids)) {
$location->delete();
}
2021-11-07 11:07:30 +00:00
});
}
public function nodes()
{
return $this->hasMany(Node::class, 'location_id', 'id');
2021-06-05 09:26:32 +00:00
}
}