Location.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. 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. $locations = Pterodactyl::getLocations();
  29. //map response
  30. $locations = array_map(function ($val) {
  31. return [
  32. 'id' => $val['attributes']['id'],
  33. 'name' => $val['attributes']['short'],
  34. 'description' => $val['attributes']['long'],
  35. ];
  36. }, $locations);
  37. //update or create
  38. foreach ($locations as $location) {
  39. self::query()->updateOrCreate(
  40. [
  41. 'id' => $location['id'],
  42. ],
  43. [
  44. 'name' => $location['name'],
  45. 'description' => $location['name'],
  46. ]
  47. );
  48. }
  49. self::removeDeletedLocation($locations);
  50. }
  51. /**
  52. * @description remove locations that have been deleted on pterodactyl
  53. *
  54. * @param array $locations
  55. */
  56. private static function removeDeletedLocation(array $locations): void
  57. {
  58. $ids = array_map(function ($data) {
  59. return $data['id'];
  60. }, $locations);
  61. self::all()->each(function (Location $location) use ($ids) {
  62. if (! in_array($location->id, $ids)) {
  63. $location->delete();
  64. }
  65. });
  66. }
  67. public function nodes()
  68. {
  69. return $this->hasMany(Node::class, 'location_id', 'id');
  70. }
  71. }