Node.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Models;
  3. use App\Classes\Pterodactyl;
  4. use Exception;
  5. use Illuminate\Database\Eloquent\Factories\HasFactory;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  8. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  9. class Node extends Model
  10. {
  11. use HasFactory;
  12. public $incrementing = false;
  13. public $guarded = [];
  14. public static function boot()
  15. {
  16. parent::boot(); // TODO: Change the autogenerated stub
  17. static::deleting(function (Node $node) {
  18. $node->products()->detach();
  19. });
  20. }
  21. /**
  22. * @throws Exception
  23. */
  24. public static function syncNodes()
  25. {
  26. Location::syncLocations();
  27. $nodes = Pterodactyl::getNodes();
  28. //map response
  29. $nodes = array_map(function ($node) {
  30. return [
  31. 'id' => $node['attributes']['id'],
  32. 'location_id' => $node['attributes']['location_id'],
  33. 'name' => $node['attributes']['name'],
  34. 'description' => $node['attributes']['description'],
  35. ];
  36. }, $nodes);
  37. //update or create
  38. foreach ($nodes as $node) {
  39. self::query()->updateOrCreate(
  40. [
  41. 'id' => $node['id'],
  42. ],
  43. [
  44. 'name' => $node['name'],
  45. 'description' => $node['description'],
  46. 'location_id' => $node['location_id'],
  47. 'disabled' => false,
  48. ]);
  49. }
  50. self::removeDeletedNodes($nodes);
  51. }
  52. /**
  53. * @description remove nodes that have been deleted on pterodactyl
  54. *
  55. * @param array $nodes
  56. */
  57. private static function removeDeletedNodes(array $nodes): void
  58. {
  59. $ids = array_map(function ($data) {
  60. return $data['id'];
  61. }, $nodes);
  62. self::all()->each(function (Node $node) use ($ids) {
  63. if (! in_array($node->id, $ids)) {
  64. $node->delete();
  65. }
  66. });
  67. }
  68. /**
  69. * @return BelongsTo
  70. */
  71. public function location(): BelongsTo
  72. {
  73. return $this->belongsTo(Location::class);
  74. }
  75. /**
  76. * @return BelongsToMany
  77. */
  78. public function products()
  79. {
  80. return $this->belongsToMany(Product::class);
  81. }
  82. }