Location.php 2.0 KB

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