ctrlpanel/app/Models/Nest.php

82 lines
1.9 KiB
PHP
Raw Permalink 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 Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Nest extends Model
{
use HasFactory;
public $incrementing = false;
public $fillable = [
'id',
'name',
'description',
'disabled',
];
2021-11-07 11:07:30 +00:00
public static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
2021-06-05 09:26:32 +00:00
2021-11-07 11:07:30 +00:00
static::deleting(function (Nest $nest) {
$nest->eggs()->each(function (Egg $egg) {
$egg->delete();
});
});
2021-06-05 09:26:32 +00:00
}
2021-11-07 11:07:30 +00:00
public static function syncNests()
{
$nests = Pterodactyl::getNests();
2021-06-05 09:26:32 +00:00
2021-11-07 11:07:30 +00:00
//map response
$nests = array_map(function ($nest) {
return [
'id' => $nest['attributes']['id'],
'name' => $nest['attributes']['name'],
2021-11-07 11:07:30 +00:00
'description' => $nest['attributes']['description'],
];
2021-11-07 11:07:30 +00:00
}, $nests);
2021-06-05 09:26:32 +00:00
foreach ($nests as $nest) {
2021-11-07 11:07:30 +00:00
self::query()->updateOrCreate([
'id' => $nest['id'],
2021-11-07 11:07:30 +00:00
], [
'name' => $nest['name'],
2021-11-07 11:07:30 +00:00
'description' => $nest['description'],
'disabled' => false,
2021-11-07 11:07:30 +00:00
]);
2021-06-05 09:26:32 +00:00
}
2021-11-07 11:07:30 +00:00
self::removeDeletedNests($nests);
}
/**
* @description remove nests that have been deleted on pterodactyl
*
* @param array $nests
2021-11-07 11:07:30 +00:00
*/
private static function removeDeletedNests(array $nests): void
{
$ids = array_map(function ($data) {
return $data['id'];
}, $nests);
self::all()->each(function (Nest $nest) use ($ids) {
if (! in_array($nest->id, $ids)) {
$nest->delete();
}
2021-11-07 11:07:30 +00:00
});
}
public function eggs()
{
return $this->hasMany(Egg::class);
2021-06-05 09:26:32 +00:00
}
}