Nest.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Models\Pterodactyl;
  3. use App\Classes\PterodactylClient;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. class Nest extends Model
  7. {
  8. use HasFactory;
  9. public $incrementing = false;
  10. public $fillable = [
  11. 'id',
  12. 'name',
  13. 'description',
  14. 'disabled',
  15. ];
  16. public static function boot()
  17. {
  18. parent::boot(); // TODO: Change the autogenerated stub
  19. static::deleting(function (Nest $nest) {
  20. $nest->eggs()->each(function (Egg $egg) {
  21. $egg->delete();
  22. });
  23. });
  24. }
  25. public static function syncNests()
  26. {
  27. $client = app(PterodactylClient::class);
  28. $nests = $client->getNests();
  29. //map response
  30. $nests = array_map(function ($nest) {
  31. return [
  32. 'id' => $nest['attributes']['id'],
  33. 'name' => $nest['attributes']['name'],
  34. 'description' => $nest['attributes']['description'],
  35. ];
  36. }, $nests);
  37. foreach ($nests as $nest) {
  38. self::query()->updateOrCreate([
  39. 'id' => $nest['id'],
  40. ], [
  41. 'name' => $nest['name'],
  42. 'description' => $nest['description'],
  43. 'disabled' => false,
  44. ]);
  45. }
  46. self::removeDeletedNests($nests);
  47. }
  48. /**
  49. * @description remove nests that have been deleted on pterodactyl
  50. *
  51. * @param array $nests
  52. */
  53. private static function removeDeletedNests(array $nests): void
  54. {
  55. $ids = array_map(function ($data) {
  56. return $data['id'];
  57. }, $nests);
  58. self::all()->each(function (Nest $nest) use ($ids) {
  59. if (! in_array($nest->id, $ids)) {
  60. $nest->delete();
  61. }
  62. });
  63. }
  64. public function eggs()
  65. {
  66. return $this->hasMany(Egg::class);
  67. }
  68. }