diff --git a/app/Http/Controllers/PlanetAbandonController.php b/app/Http/Controllers/PlanetAbandonController.php index 2d627592..0b3ec939 100644 --- a/app/Http/Controllers/PlanetAbandonController.php +++ b/app/Http/Controllers/PlanetAbandonController.php @@ -143,9 +143,22 @@ public function abandon(PlayerService $player): JsonResponse ]); } - // Abandon the planet. - $planetToDelete->abandonPlanet(); + try { + // Abandon the planet. + $planetToDelete->abandonPlanet(); + } catch (Exception $e) { + // Exception occured, return error. + return response()->json([ + 'status' => 'error', + 'errorbox' => [ + 'type' => 'fadeBox', + 'text' => $e->getMessage(), + 'failed' => true, + ], + ]); + } + // Return success message. return response()->json([ 'status' => 'error', 'errorbox' => [ diff --git a/app/Services/PlanetService.php b/app/Services/PlanetService.php index 92c66e94..110d1c6f 100644 --- a/app/Services/PlanetService.php +++ b/app/Services/PlanetService.php @@ -172,6 +172,11 @@ public function isValidPlanetName(string $name): bool */ public function abandonPlanet(): void { + // Sanity check: disallow abandoning the last remaining planet of user. + if ($this->isPlanet() && $this->player->planets->planetCount() < 2) { + throw new RuntimeException('Cannot abandon only remaining planet.'); + } + // If this is a planet and has a moon, delete the moon first if ($this->isPlanet() && $this->hasMoon()) { $this->moon()->abandonPlanet(); @@ -187,10 +192,6 @@ public function abandonPlanet(): void // Building queues BuildingQueue::where('planet_id', $this->planet->id)->delete(); - if ($this->isPlanet() && $this->player->planets->planetCount() < 2) { - throw new RuntimeException('Cannot abandon only remaining planet.'); - } - // Update the player's current planet if it is the planet being abandoned. if ($this->getPlayer()->getCurrentPlanetId() === $this->planet->id) { $this->getPlayer()->setCurrentPlanetId(0); diff --git a/tests/Feature/PlanetAbandonTest.php b/tests/Feature/PlanetAbandonTest.php index 64fd3298..3e866a92 100644 --- a/tests/Feature/PlanetAbandonTest.php +++ b/tests/Feature/PlanetAbandonTest.php @@ -60,6 +60,9 @@ public function testFirstPlanetAbandonFail(): void '_token' => csrf_token(), 'password' => 'password', ]); - $response->assertStatus(500); + + // Assert that response is HTTP 200 but contains error message. + $response->assertStatus(200); + $this->assertStringContainsString('Cannot abandon only remaining planet', (string)$response->getContent()); } }