Node.php 2.4 KB

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