Location.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. class Location extends Model
  8. {
  9. use HasFactory;
  10. public $incrementing = false;
  11. public $guarded = [];
  12. public static function boot()
  13. {
  14. parent::boot(); // TODO: Change the autogenerated stub
  15. static::deleting(function (Location $location) {
  16. $location->nodes()->each(function (Node $node) {
  17. $node->delete();
  18. });
  19. });
  20. }
  21. /**
  22. * Sync locations with pterodactyl panel
  23. *
  24. * @throws Exception
  25. */
  26. public static function syncLocations()
  27. {
  28. $client = app(PterodactylClient::class);
  29. $locations = $client->getLocations();
  30. //map response
  31. $locations = array_map(function ($val) {
  32. return [
  33. 'id' => $val['attributes']['id'],
  34. 'name' => $val['attributes']['short'],
  35. 'description' => $val['attributes']['long'],
  36. ];
  37. }, $locations);
  38. //update or create
  39. foreach ($locations as $location) {
  40. self::query()->updateOrCreate(
  41. [
  42. 'id' => $location['id'],
  43. ],
  44. [
  45. 'name' => $location['name'],
  46. 'description' => $location['name'],
  47. ]
  48. );
  49. }
  50. self::removeDeletedLocation($locations);
  51. }
  52. /**
  53. * @description remove locations that have been deleted on pterodactyl
  54. *
  55. * @param array $locations
  56. */
  57. private static function removeDeletedLocation(array $locations): void
  58. {
  59. $ids = array_map(function ($data) {
  60. return $data['id'];
  61. }, $locations);
  62. self::all()->each(function (Location $location) use ($ids) {
  63. if (! in_array($location->id, $ids)) {
  64. $location->delete();
  65. }
  66. });
  67. }
  68. public function nodes()
  69. {
  70. return $this->hasMany(Node::class, 'location_id', 'id');
  71. }
  72. }