Node.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 array(
  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. * @param array $nodes
  55. */
  56. private static function removeDeletedNodes(array $nodes): void
  57. {
  58. $ids = array_map(function ($data) {
  59. return $data['id'];
  60. }, $nodes);
  61. self::all()->each(function (Node $node) use ($ids) {
  62. if (!in_array($node->id, $ids)) $node->delete();
  63. });
  64. }
  65. /**
  66. * @return BelongsTo
  67. */
  68. public function location(): BelongsTo
  69. {
  70. return $this->belongsTo(Location::class);
  71. }
  72. /**
  73. * @return BelongsToMany
  74. */
  75. public function products()
  76. {
  77. return $this->belongsToMany(Product::class);
  78. }
  79. }