ctrlpanel/app/Models/Node.php

98 lines
2.3 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;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
2021-06-05 09:26:32 +00:00
class Node extends Model
{
use HasFactory;
public $incrementing = false;
public $guarded = [];
2021-11-07 11:07:30 +00:00
public static function boot()
2021-06-05 09:26:32 +00:00
{
2021-11-07 11:07:30 +00:00
parent::boot(); // TODO: Change the autogenerated stub
static::deleting(function (Node $node) {
$node->products()->detach();
});
2021-06-05 09:26:32 +00:00
}
/**
* @throws Exception
*/
2021-11-07 11:07:30 +00:00
public static function syncNodes()
{
2021-06-05 09:26:32 +00:00
Location::syncLocations();
$nodes = Pterodactyl::getNodes();
2021-06-05 09:26:32 +00:00
2021-11-07 11:07:30 +00:00
//map response
$nodes = array_map(function ($node) {
return [
'id' => $node['attributes']['id'],
2021-06-05 09:26:32 +00:00
'location_id' => $node['attributes']['location_id'],
'name' => $node['attributes']['name'],
2021-06-05 09:26:32 +00:00
'description' => $node['attributes']['description'],
];
2021-06-05 09:26:32 +00:00
}, $nodes);
2021-11-07 11:07:30 +00:00
//update or create
2021-06-05 09:26:32 +00:00
foreach ($nodes as $node) {
2021-11-07 11:07:30 +00:00
self::query()->updateOrCreate(
[
'id' => $node['id'],
2021-11-07 11:07:30 +00:00
],
[
'name' => $node['name'],
2021-11-07 11:07:30 +00:00
'description' => $node['description'],
'location_id' => $node['location_id'],
'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::removeDeletedNodes($nodes);
}
/**
* @description remove nodes that have been deleted on pterodactyl
*
* @param array $nodes
2021-11-07 11:07:30 +00:00
*/
private static function removeDeletedNodes(array $nodes): void
{
$ids = array_map(function ($data) {
return $data['id'];
}, $nodes);
self::all()->each(function (Node $node) use ($ids) {
if (! in_array($node->id, $ids)) {
$node->delete();
}
2021-11-07 11:07:30 +00:00
});
}
/**
* @return BelongsTo
*/
public function location(): BelongsTo
{
return $this->belongsTo(Location::class);
2021-06-05 09:26:32 +00:00
}
/**
* @return BelongsToMany
*/
public function products()
{
return $this->belongsToMany(Product::class);
}
2021-06-05 09:26:32 +00:00
}