Nest.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Models;
  3. use App\Classes\Pterodactyl;
  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. $nests = Pterodactyl::getNests();
  28. //map response
  29. $nests = array_map(function ($nest) {
  30. return [
  31. 'id' => $nest['attributes']['id'],
  32. 'name' => $nest['attributes']['name'],
  33. 'description' => $nest['attributes']['description'],
  34. ];
  35. }, $nests);
  36. foreach ($nests as $nest) {
  37. self::query()->updateOrCreate([
  38. 'id' => $nest['id'],
  39. ], [
  40. 'name' => $nest['name'],
  41. 'description' => $nest['description'],
  42. 'disabled' => false,
  43. ]);
  44. }
  45. self::removeDeletedNests($nests);
  46. }
  47. /**
  48. * @description remove nests that have been deleted on pterodactyl
  49. *
  50. * @param array $nests
  51. */
  52. private static function removeDeletedNests(array $nests): void
  53. {
  54. $ids = array_map(function ($data) {
  55. return $data['id'];
  56. }, $nests);
  57. self::all()->each(function (Nest $nest) use ($ids) {
  58. if (! in_array($nest->id, $ids)) {
  59. $nest->delete();
  60. }
  61. });
  62. }
  63. public function eggs()
  64. {
  65. return $this->hasMany(Egg::class);
  66. }
  67. }