diff --git a/app/Console/Commands/Tests/TestCommand.php b/app/Console/Commands/Tests/TestCommand.php index e10b4196..507b1c58 100644 --- a/app/Console/Commands/Tests/TestCommand.php +++ b/app/Console/Commands/Tests/TestCommand.php @@ -18,7 +18,6 @@ use OGame\Factories\PlayerServiceFactory; use OGame\Models\Planet\Coordinate; use OGame\Models\User; -use OGame\Services\ObjectService; use OGame\Services\PlanetService; use OGame\Services\PlayerService; @@ -70,11 +69,6 @@ abstract class TestCommand extends Command */ protected PlayerService $playerService; - /** - * @var ObjectService The objectService. - */ - protected ObjectService $objectService; - /** * @var PlanetService The current planet service of the test user. */ @@ -117,7 +111,6 @@ protected function setup(): void $this->info("Test user created with ID: {$user->id}"); $this->playerService = $playerServiceFactory->make($user->id); - $this->objectService = $this->playerService->planets->current()->objects; // Load current planet. $this->currentPlanetService = $this->playerService->planets->current(); diff --git a/app/Console/Commands/Tests/TestRaceConditionGameMission.php b/app/Console/Commands/Tests/TestRaceConditionGameMission.php index 553a275d..08877db8 100644 --- a/app/Console/Commands/Tests/TestRaceConditionGameMission.php +++ b/app/Console/Commands/Tests/TestRaceConditionGameMission.php @@ -6,6 +6,7 @@ use GuzzleHttp\Exception\GuzzleException; use Illuminate\Validation\ValidationException; use OGame\Models\FleetMission; +use OGame\Services\ObjectService; /** * Class TestRaceConditionGameMission. @@ -119,7 +120,7 @@ private function dispatchFleetMissionTransport(): void 'metal' => 0, 'crystal' => 0, 'deuterium' => 0, - 'am' . $this->objectService->getUnitObjectByMachineName('small_cargo')->id => '10', + 'am' . ObjectService::getUnitObjectByMachineName('small_cargo')->id => '10', ] ]); diff --git a/app/Console/Commands/Tests/TestRaceConditionUnitQueue.php b/app/Console/Commands/Tests/TestRaceConditionUnitQueue.php index 5b7355fb..9d55520b 100644 --- a/app/Console/Commands/Tests/TestRaceConditionUnitQueue.php +++ b/app/Console/Commands/Tests/TestRaceConditionUnitQueue.php @@ -8,6 +8,7 @@ use Illuminate\Support\Carbon; use Illuminate\Validation\ValidationException; use OGame\Models\Resources; +use OGame\Services\ObjectService; use OGame\Services\UnitQueueService; /** @@ -65,9 +66,9 @@ private function testSetup(): void { // Prepare user for testing the race conditions by adding some entries to the build queues. $this->currentPlanetService->addResources(new Resources(1000000, 1000000, 1000000, 0)); - $this->currentPlanetService->setObjectLevel($this->objectService->getObjectByMachineName('robot_factory')->id, 2); - $this->currentPlanetService->setObjectLevel($this->objectService->getObjectByMachineName('shipyard')->id, 1); - $this->currentPlanetService->setObjectLevel($this->objectService->getObjectByMachineName('research_lab')->id, 1); + $this->currentPlanetService->setObjectLevel(ObjectService::getObjectByMachineName('robot_factory')->id, 2); + $this->currentPlanetService->setObjectLevel(ObjectService::getObjectByMachineName('shipyard')->id, 1); + $this->currentPlanetService->setObjectLevel(ObjectService::getObjectByMachineName('research_lab')->id, 1); $this->playerService->setResearchLevel('energy_technology', 1); $this->playerService->setResearchLevel('combustion_drive', 1); @@ -77,7 +78,7 @@ private function testSetup(): void // Add light fighter build job. $unitQueueService = resolve(UnitQueueService::class); - $unitQueueService->add($this->playerService->planets->current(), $this->objectService->getUnitObjectByMachineName('light_fighter')->id, 10); + $unitQueueService->add($this->playerService->planets->current(), ObjectService::getUnitObjectByMachineName('light_fighter')->id, 10); } /** diff --git a/app/GameMessages/Abstracts/GameMessage.php b/app/GameMessages/Abstracts/GameMessage.php index 71406cc0..5e794110 100644 --- a/app/GameMessages/Abstracts/GameMessage.php +++ b/app/GameMessages/Abstracts/GameMessage.php @@ -7,7 +7,6 @@ use OGame\Factories\PlayerServiceFactory; use OGame\Models\Message; use OGame\Models\Planet\Coordinate; -use OGame\Services\ObjectService; /** * GameMessage class which contains unique parsing logic for a specific message type. @@ -43,17 +42,14 @@ abstract class GameMessage protected PlayerServiceFactory $playerServiceFactory; - protected ObjectService $objects; - /** * GameMessage constructor. * * @param Message $message * @param PlanetServiceFactory $planetServiceFactory * @param PlayerServiceFactory $playerServiceFactory - * @param ObjectService $objectService */ - public function __construct(Message $message, PlanetServiceFactory $planetServiceFactory, PlayerServiceFactory $playerServiceFactory, ObjectService $objectService) + public function __construct(Message $message, PlanetServiceFactory $planetServiceFactory, PlayerServiceFactory $playerServiceFactory) { // Clone the message to prevent any changes to the original message affecting this object. // This is important because otherwise mutations such as setting the viewed flag after loading this object @@ -61,7 +57,6 @@ public function __construct(Message $message, PlanetServiceFactory $planetServic $this->message = clone $message; $this->planetServiceFactory = $planetServiceFactory; $this->playerServiceFactory = $playerServiceFactory; - $this->objects = $objectService; $this->initialize(); } diff --git a/app/GameMessages/BattleReport.php b/app/GameMessages/BattleReport.php index 1a651dca..cee0c53e 100644 --- a/app/GameMessages/BattleReport.php +++ b/app/GameMessages/BattleReport.php @@ -9,6 +9,7 @@ use OGame\Models\Planet\Coordinate; use OGame\Models\Resources; use OGame\Services\DebrisFieldService; +use OGame\Services\ObjectService; class BattleReport extends GameMessage { @@ -163,12 +164,12 @@ private function getBattleReportParams(): array $attacker_units = new UnitCollection(); foreach ($this->battleReportModel->attacker['units'] as $machine_name => $amount) { - $attacker_units->addUnit($this->objects->getUnitObjectByMachineName($machine_name), $amount); + $attacker_units->addUnit(ObjectService::getUnitObjectByMachineName($machine_name), $amount); } $defender_units = new UnitCollection(); foreach ($this->battleReportModel->defender['units'] as $machine_name => $amount) { - $defender_units->addUnit($this->objects->getUnitObjectByMachineName($machine_name), $amount); + $defender_units->addUnit(ObjectService::getUnitObjectByMachineName($machine_name), $amount); } // Load rounds and cast to battle result round object. @@ -184,32 +185,32 @@ private function getBattleReportParams(): array $obj->hitsDefender = $round['hits_defender']; $obj->defenderShips = new UnitCollection(); foreach ($round['defender_ships'] as $machine_name => $amount) { - $unit = $this->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $obj->defenderShips->addUnit($unit, $amount); } $obj->attackerShips = new UnitCollection(); foreach ($round['attacker_ships'] as $machine_name => $amount) { - $unit = $this->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $obj->attackerShips->addUnit($unit, $amount); } $obj->defenderLosses = new UnitCollection(); foreach ($round['defender_losses'] as $machine_name => $amount) { - $unit = $this->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $obj->defenderLosses->addUnit($unit, $amount); } $obj->attackerLosses = new UnitCollection(); foreach ($round['attacker_losses'] as $machine_name => $amount) { - $unit = $this->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $obj->attackerLosses->addUnit($unit, $amount); } $obj->defenderLossesInThisRound = new UnitCollection(); foreach ($round['defender_losses_in_this_round'] as $machine_name => $amount) { - $unit = $this->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $obj->defenderLossesInThisRound->addUnit($unit, $amount); } $obj->attackerLossesInThisRound = new UnitCollection(); foreach ($round['attacker_losses_in_this_round'] as $machine_name => $amount) { - $unit = $this->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $obj->attackerLossesInThisRound->addUnit($unit, $amount); } $rounds[] = $obj; @@ -260,9 +261,9 @@ private function getBattleReportParams(): array 'defender_weapons' => $defender_weapons, 'defender_shields' => $defender_shields, 'defender_armor' => $defender_armor, - 'military_objects' => $this->objects->getMilitaryShipObjects(), - 'civil_objects' => $this->objects->getCivilShipObjects(), - 'defense_objects' => $this->objects->getDefenseObjects(), + 'military_objects' => ObjectService::getMilitaryShipObjects(), + 'civil_objects' => ObjectService::getCivilShipObjects(), + 'defense_objects' => ObjectService::getDefenseObjects(), 'attacker_units_start' => $attacker_units, 'defender_units_start' => $defender_units, 'rounds' => $rounds, diff --git a/app/GameMessages/EspionageReport.php b/app/GameMessages/EspionageReport.php index da3ed804..9a1232fe 100644 --- a/app/GameMessages/EspionageReport.php +++ b/app/GameMessages/EspionageReport.php @@ -5,6 +5,7 @@ use OGame\GameMessages\Abstracts\GameMessage; use OGame\Models\Planet\Coordinate; use OGame\Models\Resources; +use OGame\Services\ObjectService; use OGame\ViewModels\UnitViewModel; class EspionageReport extends GameMessage @@ -134,7 +135,7 @@ private function getEspionageReportParams(): array if ($this->espionageReportModel->ships !== null) { foreach ($this->espionageReportModel->ships as $machine_name => $amount) { // Get object - $unit = $planet->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $unitViewModel = new UnitViewModel(); $unitViewModel->amount = $amount; @@ -149,7 +150,7 @@ private function getEspionageReportParams(): array if ($this->espionageReportModel->defense !== null) { foreach ($this->espionageReportModel->defense as $machine_name => $amount) { // Get object - $unit = $planet->objects->getUnitObjectByMachineName($machine_name); + $unit = ObjectService::getUnitObjectByMachineName($machine_name); $unitViewModel = new UnitViewModel(); $unitViewModel->amount = $amount; @@ -164,7 +165,7 @@ private function getEspionageReportParams(): array if ($this->espionageReportModel->buildings !== null) { foreach ($this->espionageReportModel->buildings as $machine_name => $amount) { // Get object - $unit = $planet->objects->getObjectByMachineName($machine_name); + $unit = ObjectService::getObjectByMachineName($machine_name); $unitViewModel = new UnitViewModel(); $unitViewModel->amount = $amount; @@ -179,7 +180,7 @@ private function getEspionageReportParams(): array if ($this->espionageReportModel->research !== null) { foreach ($this->espionageReportModel->research as $machine_name => $amount) { // Get object - $unit = $planet->objects->getObjectByMachineName($machine_name); + $unit = ObjectService::getObjectByMachineName($machine_name); $unitViewModel = new UnitViewModel(); $unitViewModel->amount = $amount; diff --git a/app/GameMissions/ColonisationMission.php b/app/GameMissions/ColonisationMission.php index 72d87b2e..a1a9425b 100644 --- a/app/GameMissions/ColonisationMission.php +++ b/app/GameMissions/ColonisationMission.php @@ -11,6 +11,7 @@ use OGame\Models\FleetMission; use OGame\Models\Planet\Coordinate; use OGame\Models\Resources; +use OGame\Services\ObjectService; use OGame\Services\PlanetService; class ColonisationMission extends GameMission @@ -103,7 +104,7 @@ protected function processArrival(FleetMission $mission): void // Assembly new unit collection. $units = $this->fleetMissionService->getFleetUnits($mission); // Remove one colony ship from the fleet as it was used to colonize the planet. - $colony_ship = $target_planet->objects->getUnitObjectByMachineName('colony_ship'); + $colony_ship = ObjectService::getUnitObjectByMachineName('colony_ship'); $units->removeUnit($colony_ship, 1); // Create and start the return mission (if the colonisation mission had ships other than the colony ship itself). diff --git a/app/GameMissions/RecycleMission.php b/app/GameMissions/RecycleMission.php index 7d37c577..3cd7241e 100644 --- a/app/GameMissions/RecycleMission.php +++ b/app/GameMissions/RecycleMission.php @@ -11,8 +11,8 @@ use OGame\Models\Enums\PlanetType; use OGame\Models\FleetMission; use OGame\Models\Planet\Coordinate; -use OGame\Models\Resources; use OGame\Services\DebrisFieldService; +use OGame\Services\ObjectService; use OGame\Services\PlanetService; class RecycleMission extends GameMission @@ -57,7 +57,7 @@ protected function processArrival(FleetMission $mission): void $debrisField->loadOrCreateForCoordinates($targetCoordinate); // Get recycler unit count - $recycler = $originPlanet->objects->getShipObjectByMachineName('recycler'); + $recycler = ObjectService::getShipObjectByMachineName('recycler'); $recyclerCount = $this->fleetMissionService->getFleetUnits($mission)->getAmountByMachineName($recycler->machine_name); // Calculate total recycler capacity. diff --git a/app/Http/Controllers/Abstracts/AbstractBuildingsController.php b/app/Http/Controllers/Abstracts/AbstractBuildingsController.php index d11852ba..617b6fba 100644 --- a/app/Http/Controllers/Abstracts/AbstractBuildingsController.php +++ b/app/Http/Controllers/Abstracts/AbstractBuildingsController.php @@ -67,11 +67,10 @@ public function __construct(BuildingQueueService $queue) * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects): View + public function index(Request $request, PlayerService $player): View { $this->planet = $player->planets->current(); @@ -90,16 +89,16 @@ public function index(Request $request, PlayerService $player, ObjectService $ob $count++; // Get object - $object = $objects->getObjectByMachineName($object_machine_name); + $object = ObjectService::getObjectByMachineName($object_machine_name); // Get current level of building $current_level = $this->planet->getObjectLevel($object_machine_name); // Check requirements of this building - $requirements_met = $objects->objectRequirementsMet($object_machine_name, $this->planet, $player); + $requirements_met = ObjectService::objectRequirementsMet($object_machine_name, $this->planet, $player); // Check if the current planet has enough resources to build this building. - $enough_resources = $this->planet->hasResources($objects->getObjectPrice($object_machine_name, $this->planet)); + $enough_resources = $this->planet->hasResources(ObjectService::getObjectPrice($object_machine_name, $this->planet)); // If building level is 1 or higher, add to header filename parts to // render the header of this planet. diff --git a/app/Http/Controllers/Abstracts/AbstractUnitsController.php b/app/Http/Controllers/Abstracts/AbstractUnitsController.php index e1909137..aebb79f9 100644 --- a/app/Http/Controllers/Abstracts/AbstractUnitsController.php +++ b/app/Http/Controllers/Abstracts/AbstractUnitsController.php @@ -61,11 +61,10 @@ public function __construct(UnitQueueService $queue) * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects): View + public function index(Request $request, PlayerService $player): View { $planet = $player->planets->current(); @@ -88,19 +87,19 @@ public function index(Request $request, PlayerService $player, ObjectService $ob foreach ($objects_row as $object_machine_name) { $count++; - $object = $objects->getUnitObjectByMachineName($object_machine_name); + $object = ObjectService::getUnitObjectByMachineName($object_machine_name); - // Get current level of building + // Get current amount of this unit. $amount = $planet->getObjectAmount($object->machine_name); // Check requirements of this building - $requirements_met = $objects->objectRequirementsMet($object->machine_name, $planet, $player, 0, false); + $requirements_met = ObjectService::objectRequirementsMet($object->machine_name, $planet, $player, 0, false); // Check if the current planet has enough resources to build this building. - $enough_resources = $planet->hasResources($objects->getObjectPrice($object->machine_name, $planet)); + $enough_resources = $planet->hasResources(ObjectService::getObjectPrice($object->machine_name, $planet)); // Get maximum build amount of this building - $max_build_amount = $objects->getObjectMaxBuildAmount($object->machine_name, $planet, $requirements_met); + $max_build_amount = ObjectService::getObjectMaxBuildAmount($object->machine_name, $planet, $requirements_met); $view_model = new UnitViewModel(); $view_model->object = $object; @@ -127,7 +126,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob } /** - * Handles an incoming add buildrequest. + * Handles an incoming add build request. * * @param Request $request * @param PlayerService $player diff --git a/app/Http/Controllers/Admin/DeveloperShortcutsController.php b/app/Http/Controllers/Admin/DeveloperShortcutsController.php index 76ddf0d7..4118cda1 100644 --- a/app/Http/Controllers/Admin/DeveloperShortcutsController.php +++ b/app/Http/Controllers/Admin/DeveloperShortcutsController.php @@ -8,22 +8,18 @@ use OGame\Models\Enums\ResourceType; use OGame\Services\ObjectService; use OGame\Services\PlayerService; -use OGame\Services\SettingsService; class DeveloperShortcutsController extends OGameController { /** - * Shows the server settings page. + * Shows the developer shortcuts page. * - * @param PlayerService $player - * @param SettingsService $settingsService - * @param ObjectService $objectService * @return View */ - public function index(PlayerService $player, SettingsService $settingsService, ObjectService $objectService): View + public function index(): View { // Get all unit objects - $units = $objectService->getUnitObjects(); + $units = ObjectService::getUnitObjects(); return view('ingame.admin.developershortcuts')->with([ 'units' => $units, @@ -35,56 +31,55 @@ public function index(PlayerService $player, SettingsService $settingsService, O * * @param \Illuminate\Http\Request $request * @param PlayerService $playerService - * @param ObjectService $objectService * @return RedirectResponse * @throws \Exception */ - public function update(\Illuminate\Http\Request $request, PlayerService $playerService, ObjectService $objectService): RedirectResponse + public function update(\Illuminate\Http\Request $request, PlayerService $playerService): RedirectResponse { if ($request->has('set_mines')) { // Handle "Set all mines to level 30" - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('metal_mine')->id, 30); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('crystal_mine')->id, 30); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('deuterium_synthesizer')->id, 30); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('solar_plant')->id, 30); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('metal_mine')->id, 30); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('crystal_mine')->id, 30); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('deuterium_synthesizer')->id, 30); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('solar_plant')->id, 30); } elseif ($request->has('set_storages')) { // Handle "Set all storages to level 30" - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('metal_store')->id, 15); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('crystal_store')->id, 15); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('deuterium_store')->id, 15); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('metal_store')->id, 15); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('crystal_store')->id, 15); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('deuterium_store')->id, 15); } elseif ($request->has('set_shipyard')) { // Handle "Set all shipyard facilities to level 12" - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('shipyard')->id, 12); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('robot_factory')->id, 12); - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('nano_factory')->id, 12); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('shipyard')->id, 12); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('robot_factory')->id, 12); + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('nano_factory')->id, 12); } elseif ($request->has('set_research')) { // Handle "Set all research to level 10" - $playerService->planets->current()->setObjectLevel($objectService->getObjectByMachineName('research_lab')->id, 12); - foreach ($objectService->getResearchObjects() as $research) { + $playerService->planets->current()->setObjectLevel(ObjectService::getObjectByMachineName('research_lab')->id, 12); + foreach (ObjectService::getResearchObjects() as $research) { $playerService->setResearchLevel($research->machine_name, 10); } } elseif ($request->has('reset_buildings')) { // Handle "Reset all buildings" - foreach ($objectService->getBuildingObjects() as $building) { + foreach (ObjectService::getBuildingObjects() as $building) { $playerService->planets->current()->setObjectLevel($building->id, 0); } - foreach ($objectService->getStationObjects() as $building) { + foreach (ObjectService::getStationObjects() as $building) { $playerService->planets->current()->setObjectLevel($building->id, 0); } } elseif ($request->has('reset_research')) { // Handle "Reset all research" - foreach ($objectService->getResearchObjects() as $research) { + foreach (ObjectService::getResearchObjects() as $research) { $playerService->setResearchLevel($research->machine_name, 0); } } elseif ($request->has('reset_units')) { // Handle "Reset all units" - foreach ($objectService->getUnitObjects() as $unit) { + foreach (ObjectService::getUnitObjects() as $unit) { $playerService->planets->current()->removeUnit($unit->machine_name, $playerService->planets->current()->getObjectAmount($unit->machine_name)); } } else { // Handle unit submission - foreach ($objectService->getUnitObjects() as $unit) { + foreach (ObjectService::getUnitObjects() as $unit) { if ($request->has('unit_' . $unit->id)) { // Handle adding the specific unit $playerService->planets->current()->addUnit($unit->machine_name, $request->input('amount_of_units')); diff --git a/app/Http/Controllers/DefenseController.php b/app/Http/Controllers/DefenseController.php index a17459be..e2df8d65 100644 --- a/app/Http/Controllers/DefenseController.php +++ b/app/Http/Controllers/DefenseController.php @@ -7,7 +7,6 @@ use Illuminate\Http\Request; use Illuminate\View\View; use OGame\Http\Controllers\Abstracts\AbstractUnitsController; -use OGame\Services\ObjectService; use OGame\Services\PlayerService; use OGame\Services\UnitQueueService; @@ -27,11 +26,10 @@ public function __construct(UnitQueueService $queue) * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects): View + public function index(Request $request, PlayerService $player): View { $this->setBodyId('defense'); @@ -52,7 +50,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob ]; $this->view_name = 'ingame.defense.index'; - return parent::index($request, $player, $objects); + return parent::index($request, $player); } /** @@ -60,12 +58,11 @@ public function index(Request $request, PlayerService $player, ObjectService $ob * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return JsonResponse * @throws Exception */ - public function ajax(Request $request, PlayerService $player, ObjectService $objects): JsonResponse + public function ajax(Request $request, PlayerService $player): JsonResponse { - return $this->ajaxHandler($request, $player, $objects); + return $this->ajaxHandler($request, $player); } } diff --git a/app/Http/Controllers/FacilitiesController.php b/app/Http/Controllers/FacilitiesController.php index d4c43d8e..3390e297 100644 --- a/app/Http/Controllers/FacilitiesController.php +++ b/app/Http/Controllers/FacilitiesController.php @@ -8,7 +8,6 @@ use Illuminate\View\View; use OGame\Http\Controllers\Abstracts\AbstractBuildingsController; use OGame\Services\BuildingQueueService; -use OGame\Services\ObjectService; use OGame\Services\PlayerService; class FacilitiesController extends AbstractBuildingsController @@ -27,11 +26,10 @@ public function __construct(BuildingQueueService $queue) * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects): View + public function index(Request $request, PlayerService $player): View { $this->setBodyId('station'); @@ -42,7 +40,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob ]; $this->view_name = 'ingame.facilities.index'; - return parent::index($request, $player, $objects); + return parent::index($request, $player); } /** @@ -50,12 +48,11 @@ public function index(Request $request, PlayerService $player, ObjectService $ob * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return JsonResponse * @throws Exception */ - public function ajax(Request $request, PlayerService $player, ObjectService $objects): JsonResponse + public function ajax(Request $request, PlayerService $player): JsonResponse { - return $this->ajaxHandler($request, $player, $objects); + return $this->ajaxHandler($request, $player); } } diff --git a/app/Http/Controllers/FleetController.php b/app/Http/Controllers/FleetController.php index dcba785b..51968961 100644 --- a/app/Http/Controllers/FleetController.php +++ b/app/Http/Controllers/FleetController.php @@ -26,12 +26,11 @@ class FleetController extends OGameController * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @param SettingsService $settings * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects, SettingsService $settings): View + public function index(Request $request, PlayerService $player, SettingsService $settings): View { // Define ship ids to include in the fleet screen. // 0 = military ships @@ -50,7 +49,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob foreach ($objects_row as $object_machine_name) { $count++; - $object = $objects->getUnitObjectByMachineName($object_machine_name); + $object = ObjectService::getUnitObjectByMachineName($object_machine_name); // Get current level of building $amount = $planet->getObjectAmount($object_machine_name); @@ -68,7 +67,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob 'player' => $player, 'planet' => $planet, 'units' => $units, - 'objects' => $objects->getShipObjects(), + 'objects' => ObjectService::getShipObjects(), 'shipAmount' => $planet->getFlightShipAmount(), 'galaxy' => $request->get('galaxy'), 'system' => $request->get('system'), @@ -93,18 +92,17 @@ public function movement(): View * Checks the target planet for possible missions. * * @param PlayerService $currentPlayer - * @param ObjectService $objects * @param PlanetServiceFactory $planetServiceFactory * @return JsonResponse * @throws Exception */ - public function dispatchCheckTarget(PlayerService $currentPlayer, ObjectService $objects, PlanetServiceFactory $planetServiceFactory): JsonResponse + public function dispatchCheckTarget(PlayerService $currentPlayer, PlanetServiceFactory $planetServiceFactory): JsonResponse { $currentPlanet = $currentPlayer->planets->current(); // Return ships data for this planet taking into account the current planet's properties and research levels. $shipsData = []; - foreach ($objects->getShipObjects() as $shipObject) { + foreach (ObjectService::getShipObjects() as $shipObject) { $shipsData[$shipObject->id] = [ 'id' => $shipObject->id, 'name' => $shipObject->title, @@ -304,11 +302,11 @@ public function dispatchSendMiniFleet(PlayerService $player, FleetMissionService case 6: // Espionage // TODO: make espionage probe amount configurable in user settings and use that value here. $responseMessage = __('Send espionage probe to:'); - $units->addUnit($planet->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $units->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); break; case 8: // Recycle $responseMessage = __('Send recycler to:'); - $units->addUnit($planet->objects->getUnitObjectByMachineName('recycler'), $shipCount); + $units->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), $shipCount); break; } @@ -411,7 +409,7 @@ private function getUnitsFromRequest(PlanetService $planet): UnitCollection if (str_starts_with($key, 'am')) { $unit_id = (int)str_replace('am', '', $key); // Create GameObject - $unitObject = $planet->objects->getUnitObjectById($unit_id); + $unitObject = ObjectService::getUnitObjectById($unit_id); $units->addUnit($unitObject, (int)$value); } } diff --git a/app/Http/Controllers/ResearchController.php b/app/Http/Controllers/ResearchController.php index 755834b4..329f08c9 100644 --- a/app/Http/Controllers/ResearchController.php +++ b/app/Http/Controllers/ResearchController.php @@ -45,11 +45,10 @@ public function __construct(ResearchQueueService $queue) * Shows the research index page * * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(PlayerService $player, ObjectService $objects): View + public function index(PlayerService $player): View { $this->setBodyId('research'); $planet = $player->planets->current(); @@ -74,16 +73,16 @@ public function index(PlayerService $player, ObjectService $objects): View foreach ($objects_row as $object_machine_name) { $count++; - $object = $objects->getResearchObjectByMachineName($object_machine_name); + $object = ObjectService::getResearchObjectByMachineName($object_machine_name); // Get current level of building $current_level = $player->getResearchLevel($object->machine_name); // Check requirements of this building - $requirements_met = $objects->objectRequirementsMet($object->machine_name, $planet, $player); + $requirements_met = ObjectService::objectRequirementsMet($object->machine_name, $planet, $player); // Check if the current planet has enough resources to build this building. - $enough_resources = $planet->hasResources($objects->getObjectPrice($object->machine_name, $planet)); + $enough_resources = $planet->hasResources(ObjectService::getObjectPrice($object->machine_name, $planet)); $view_model = new BuildingViewModel(); $view_model->object = $object; @@ -118,17 +117,16 @@ public function index(PlayerService $player, ObjectService $objects): View * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return JsonResponse * @throws Exception */ - public function ajax(Request $request, PlayerService $player, ObjectService $objects): JsonResponse + public function ajax(Request $request, PlayerService $player): JsonResponse { - return $this->ajaxHandler($request, $player, $objects); + return $this->ajaxHandler($request, $player); } /** - * Handles an incoming add buildrequest. + * Handles an incoming add build request. * * @param Request $request * @param PlayerService $player diff --git a/app/Http/Controllers/ResourcesController.php b/app/Http/Controllers/ResourcesController.php index 55978201..79289010 100644 --- a/app/Http/Controllers/ResourcesController.php +++ b/app/Http/Controllers/ResourcesController.php @@ -30,11 +30,10 @@ public function __construct(BuildingQueueService $queue) * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects): View + public function index(Request $request, PlayerService $player): View { $this->setBodyId('resources'); @@ -45,7 +44,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob ]; $this->view_name = 'ingame.resources.index'; - return parent::index($request, $player, $objects); + return parent::index($request, $player); } /** @@ -53,13 +52,12 @@ public function index(Request $request, PlayerService $player, ObjectService $ob * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return JsonResponse * @throws Exception */ - public function ajax(Request $request, PlayerService $player, ObjectService $objects): JsonResponse + public function ajax(Request $request, PlayerService $player): JsonResponse { - return $this->ajaxHandler($request, $player, $objects); + return $this->ajaxHandler($request, $player); } /** @@ -67,11 +65,10 @@ public function ajax(Request $request, PlayerService $player, ObjectService $obj * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function settings(Request $request, PlayerService $player, ObjectService $objects): View + public function settings(Request $request, PlayerService $player): View { $this->setBodyId('resourceSettings'); $this->planet = $player->planets->current(); @@ -85,7 +82,7 @@ public function settings(Request $request, PlayerService $player, ObjectService // Buildings that provide resource income // Get all buildings that have production values. - foreach ($objects->getGameObjectsWithProduction() as $building) { + foreach (ObjectService::getGameObjectsWithProduction() as $building) { // Retrieve all buildings that have production values. $production = $this->planet->getObjectProduction($building->machine_name); $production_total->add($production); @@ -151,11 +148,11 @@ public function settings(Request $request, PlayerService $player, ObjectService * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * * @return RedirectResponse + * @throws Exception */ - public function settingsUpdate(Request $request, PlayerService $player, ObjectService $objects): RedirectResponse + public function settingsUpdate(Request $request, PlayerService $player): RedirectResponse { $this->planet = $player->planets->current(); diff --git a/app/Http/Controllers/ShipyardController.php b/app/Http/Controllers/ShipyardController.php index f5428fb4..50e83a83 100644 --- a/app/Http/Controllers/ShipyardController.php +++ b/app/Http/Controllers/ShipyardController.php @@ -7,7 +7,6 @@ use Illuminate\Http\Request; use Illuminate\View\View; use OGame\Http\Controllers\Abstracts\AbstractUnitsController; -use OGame\Services\ObjectService; use OGame\Services\PlayerService; use OGame\Services\UnitQueueService; @@ -29,11 +28,10 @@ public function __construct(UnitQueueService $queue) * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function index(Request $request, PlayerService $player, ObjectService $objects): View + public function index(Request $request, PlayerService $player): View { $this->setBodyId('shipyard'); @@ -44,7 +42,7 @@ public function index(Request $request, PlayerService $player, ObjectService $ob ]; $this->view_name = 'ingame.shipyard.index'; - return parent::index($request, $player, $objects); + return parent::index($request, $player); } /** @@ -52,12 +50,11 @@ public function index(Request $request, PlayerService $player, ObjectService $ob * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return JsonResponse * @throws Exception */ - public function ajax(Request $request, PlayerService $player, ObjectService $objects): JsonResponse + public function ajax(Request $request, PlayerService $player): JsonResponse { - return $this->ajaxHandler($request, $player, $objects); + return $this->ajaxHandler($request, $player); } } diff --git a/app/Http/Controllers/TechtreeController.php b/app/Http/Controllers/TechtreeController.php index 2adc31a1..f1be127d 100644 --- a/app/Http/Controllers/TechtreeController.php +++ b/app/Http/Controllers/TechtreeController.php @@ -16,15 +16,14 @@ class TechtreeController extends OGameController { /** - * Returns techtree ajax content. + * Returns tech tree ajax content. * * @param Request $request - * @param ObjectService $objects * @param PlayerService $player * @return View * @throws Exception */ - public function ajax(Request $request, ObjectService $objects, PlayerService $player): View + public function ajax(Request $request, PlayerService $player): View { $object_id = (int)$request->input('object_id'); $tab = (int)$request->input('tab'); @@ -32,7 +31,7 @@ public function ajax(Request $request, ObjectService $objects, PlayerService $pl $planet = $player->planets->current(); // Load object - $object = $objects->getObjectById($object_id); + $object = ObjectService::getObjectById($object_id); if ($tab === 1) { return view('ingame.techtree.techtree')->with([ @@ -45,10 +44,10 @@ public function ajax(Request $request, ObjectService $objects, PlayerService $pl 'object' => $object, 'object_id' => $object_id, 'planet' => $planet, - 'production_table' => $this->getProductionTable($object, $player, $objects), - 'storage_table' => $this->getStorageTable($object, $player, $objects), - 'rapidfire_table' => $this->getRapidfireTable($object, $objects), - 'properties_table' => $this->getPropertiesTable($object, $player, $objects), + 'production_table' => $this->getProductionTable($object, $player), + 'storage_table' => $this->getStorageTable($object, $player), + 'rapidfire_table' => $this->getRapidfireTable($object), + 'properties_table' => $this->getPropertiesTable($object, $player), 'plasma_table' => $this->getPlasmaTable($object, $player), 'astrophysics_table' => $this->getAstrophysicsTable($object, $player), ]); @@ -63,7 +62,7 @@ public function ajax(Request $request, ObjectService $objects, PlayerService $pl 'object' => $object, 'object_id' => $object_id, 'planet' => $planet, - 'required_by' => $this->getRequiredBy($object, $player, $objects, $planet) + 'required_by' => $this->getRequiredBy($object, $player, $planet) ]); } @@ -71,22 +70,21 @@ public function ajax(Request $request, ObjectService $objects, PlayerService $pl } /** - * Returns techtree production table. + * Returns tech tree production table. * * @param GameObject $object * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function getProductionTable(GameObject $object, PlayerService $player, ObjectService $objects): View + public function getProductionTable(GameObject $object, PlayerService $player): View { if ($object->type !== GameObjectType::Building) { return view('empty'); } // Reload object to get the BuildingObject - $object = $objects->getBuildingObjectByMachineName($object->machine_name); + $object = ObjectService::getBuildingObjectByMachineName($object->machine_name); $planet = $player->planets->current(); $current_level = $player->planets->current()->getObjectLevel($object->machine_name); @@ -125,22 +123,21 @@ public function getProductionTable(GameObject $object, PlayerService $player, Ob } /** - * Returns techtree storage table. + * Returns tech tree storage table. * * @param GameObject $object * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function getStorageTable(GameObject $object, PlayerService $player, ObjectService $objects): View + public function getStorageTable(GameObject $object, PlayerService $player): View { if ($object->type !== GameObjectType::Building) { return view('empty'); } // Reload object to get the BuildingObject - $object = $objects->getBuildingObjectByMachineName($object->machine_name); + $object = ObjectService::getBuildingObjectByMachineName($object->machine_name); $planet = $player->planets->current(); $current_level = $player->planets->current()->getObjectLevel($object->machine_name); @@ -175,13 +172,12 @@ public function getStorageTable(GameObject $object, PlayerService $player, Objec } /** - * Returns techtree rapidfire table. + * Returns tech tree rapidfire table. * * @param GameObject $object - * @param ObjectService $objects * @return View */ - public function getRapidfireTable(GameObject $object, ObjectService $objects): View + public function getRapidfireTable(GameObject $object): View { if ($object->type !== GameObjectType::Ship && $object->type !== GameObjectType::Defense) { return view('empty'); @@ -197,7 +193,7 @@ public function getRapidfireTable(GameObject $object, ObjectService $objects): V // ] $rapidfire_from = []; - foreach ($objects->getObjects() as $from_object) { + foreach (ObjectService::getObjects() as $from_object) { if (empty($from_object->rapidfire)) { continue; } @@ -217,7 +213,7 @@ public function getRapidfireTable(GameObject $object, ObjectService $objects): V if (!empty($object->rapidfire)) { foreach ($object->rapidfire as $rapidfire) { // Add object name to rapidfire array - $object = $objects->getObjectByMachineName($rapidfire->object_machine_name); + $object = ObjectService::getObjectByMachineName($rapidfire->object_machine_name); $rapidfire_against[$object->id] = [ 'rapidfire' => $rapidfire, 'object' => $object, @@ -233,15 +229,14 @@ public function getRapidfireTable(GameObject $object, ObjectService $objects): V } /** - * Returns techtree properties table. + * Returns tech tree properties table. * * @param GameObject $object * @param PlayerService $player - * @param ObjectService $objects * @return View * @throws Exception */ - public function getPropertiesTable(GameObject $object, PlayerService $player, ObjectService $objects): View + public function getPropertiesTable(GameObject $object, PlayerService $player): View { if ($object->type !== GameObjectType::Ship && $object->type !== GameObjectType::Defense) { return view('empty'); @@ -253,7 +248,7 @@ public function getPropertiesTable(GameObject $object, PlayerService $player, Ob } // Load object again to get the UnitObject - $object = $objects->getUnitObjectByMachineName($object->machine_name); + $object = ObjectService::getUnitObjectByMachineName($object->machine_name); // Get UnitObject properties... $properties = $object->properties; @@ -382,13 +377,12 @@ public function getAstrophysicsTable(GameObject $object, PlayerService $player): /** * @param GameObject $object * @param PlayerService $player - * @param ObjectService $objects * @param PlanetService $planet * @return array */ - private function getRequiredBy(GameObject $object, PlayerService $player, ObjectService $objects, PlanetService $planet): array + private function getRequiredBy(GameObject $object, PlayerService $player, PlanetService $planet): array { - $all_objects = $objects->getObjects(); + $all_objects = ObjectService::getObjects(); $required_by = []; $require_objects = array_filter($all_objects, function ($a_object) use ($object) { @@ -403,7 +397,7 @@ private function getRequiredBy(GameObject $object, PlayerService $player, Object }); foreach ($require_objects as $r_object) { - $required_by[] = new TechtreeRequiredBy($r_object, $objects->objectRequirementsMet($r_object->machine_name, $planet, $player)); + $required_by[] = new TechtreeRequiredBy($r_object, ObjectService::objectRequirementsMet($r_object->machine_name, $planet, $player)); } return $required_by; diff --git a/app/Http/Middleware/GlobalGame.php b/app/Http/Middleware/GlobalGame.php index efa90f15..188da638 100644 --- a/app/Http/Middleware/GlobalGame.php +++ b/app/Http/Middleware/GlobalGame.php @@ -5,9 +5,7 @@ use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use OGame\Services\ObjectService; use OGame\Services\PlayerService; -use OGame\Services\SettingsService; use Throwable; class GlobalGame @@ -23,15 +21,7 @@ class GlobalGame public function handle(Request $request, Closure $next): mixed { if (Auth::check()) { - // Get objects. - $object = new ObjectService(); - app()->instance(ObjectService::class, $object); - - // Instantiate settings service. - $settings = resolve(SettingsService::class); - app()->instance(SettingsService::class, $settings); - - // Load player. + // Load current player and make it available as a request singleton via PlayerService. $player = resolve(PlayerService::class, ['player_id' => $request->user()->id]); app()->instance(PlayerService::class, $player); diff --git a/app/Http/Traits/ObjectAjaxTrait.php b/app/Http/Traits/ObjectAjaxTrait.php index 53baed34..f015af2b 100644 --- a/app/Http/Traits/ObjectAjaxTrait.php +++ b/app/Http/Traits/ObjectAjaxTrait.php @@ -17,11 +17,10 @@ trait ObjectAjaxTrait * * @param Request $request * @param PlayerService $player - * @param ObjectService $objects * @return JsonResponse * @throws Exception */ - public function ajaxHandler(Request $request, PlayerService $player, ObjectService $objects): JsonResponse + public function ajaxHandler(Request $request, PlayerService $player): JsonResponse { $planet = $player->planets->current(); @@ -30,7 +29,7 @@ public function ajaxHandler(Request $request, PlayerService $player, ObjectServi throw new Exception('No object ID provided.'); } - $object = $objects->getObjectById($object_id); + $object = ObjectService::getObjectById($object_id); $current_level = 0; if ($object->type == GameObjectType::Research) { @@ -43,12 +42,12 @@ public function ajaxHandler(Request $request, PlayerService $player, ObjectServi $next_level = $current_level + 1; // Check requirements of this object - $requirements_met = $objects->objectRequirementsMet($object->machine_name, $planet, $player); + $requirements_met = ObjectService::objectRequirementsMet($object->machine_name, $planet, $player); - $price = $objects->getObjectPrice($object->machine_name, $planet); + $price = ObjectService::getObjectPrice($object->machine_name, $planet); // Get max build amount of this object (unit). - $max_build_amount = $objects->getObjectMaxBuildAmount($object->machine_name, $planet, $requirements_met); + $max_build_amount = ObjectService::getObjectMaxBuildAmount($object->machine_name, $planet, $requirements_met); // Switch $production_time = ''; diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index dc094848..6e5ee60a 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -32,6 +32,10 @@ final public function boot(): void */ final public function register(): void { + $this->app->singleton(SettingsService::class, function ($app) { + return new SettingsService(); + }); + $this->app->singleton(PlayerServiceFactory::class, function ($app) { return new PlayerServiceFactory(); }); diff --git a/app/Services/BuildingQueueService.php b/app/Services/BuildingQueueService.php index 68297853..2693dddc 100644 --- a/app/Services/BuildingQueueService.php +++ b/app/Services/BuildingQueueService.php @@ -19,23 +19,6 @@ */ class BuildingQueueService { - /** - * Information about objects. - * - * @var ObjectService - */ - private ObjectService $objects; - - /** - * BuildingQueue constructor. - * - * @param ObjectService $objects - */ - public function __construct(ObjectService $objects) - { - $this->objects = $objects; - } - /** * Retrieve all build queue items that already should be finished for a planet. * @@ -91,11 +74,12 @@ public function add(PlanetService $planet, int $building_id): void throw new Exception('Maximum number of items already in queue.'); } - $building = $this->objects->getObjectById($building_id); + // Check if user satisfies requirements to build this object. + $building = ObjectService::getObjectById($building_id); - // Check if user satisifes requirements to build this object. + // Check if user satisfies requirements to build this object. // TODO: refactor throw exception into a more user-friendly message. - $requirements_met = $this->objects->objectRequirementsMet($building->machine_name, $planet, $planet->getPlayer()); + $requirements_met = ObjectService::objectRequirementsMet($building->machine_name, $planet, $planet->getPlayer()); if (!$requirements_met) { throw new Exception('Requirements not met to build this object.'); } @@ -135,7 +119,7 @@ public function retrieveQueue(PlanetService $planet): BuildingQueueListViewModel // Convert to ViewModel array $list = array(); foreach ($queue_items as $item) { - $object = $this->objects->getObjectById($item['object_id']); + $object = ObjectService::getObjectById($item['object_id']); $time_countdown = $item->time_end - (int)Carbon::now()->timestamp; if ($time_countdown < 0) { @@ -206,10 +190,10 @@ public function start(PlanetService $planet, int $time_start = 0): void ->get(); foreach ($queue_items as $queue_item) { - $object = $this->objects->getObjectById($queue_item->object_id); + $object = ObjectService::getObjectById($queue_item->object_id); // See if the planet has enough resources for this build attempt. - $price = $this->objects->getObjectPrice($object->machine_name, $planet); + $price = ObjectService::getObjectPrice($object->machine_name, $planet); $build_time = $planet->getBuildingConstructionTime($object->machine_name); // Only start the queue item if there are no other queue items building @@ -243,7 +227,7 @@ public function start(PlanetService $planet, int $time_start = 0): void // Sanity check: check if the building requirements are still met. If not, // then cancel build request. - if (!$this->objects->objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer(), $queue_item->object_level_target, false)) { + if (!ObjectService::objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer(), $queue_item->object_level_target, false)) { $this->cancel($planet, $queue_item->id, $queue_item->object_id); continue; @@ -334,7 +318,7 @@ public function objectInBuildingQueue(PlanetService $planet, string $machine_nam $queue_items = $this->retrieveQueueItems($planet); foreach ($queue_items as $item) { - $object = $this->objects->getObjectById($item->object_id); + $object = ObjectService::getObjectById($item->object_id); if ($object->machine_name === $machine_name && $item->object_level_target === $level) { return true; @@ -355,9 +339,9 @@ public function cancelItemMissingRequirements(PlanetService $planet): void $build_queue_items = $this->retrieveQueueItems($planet); foreach ($build_queue_items as $build_queue_item) { - $object = $this->objects->getObjectById($build_queue_item->object_id); + $object = ObjectService::getObjectById($build_queue_item->object_id); - if (!$this->objects->objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer(), $build_queue_item->object_level_target)) { + if (!ObjectService::objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer(), $build_queue_item->object_level_target)) { $this->cancel($planet, $build_queue_item->id, $object->id); break; } diff --git a/app/Services/DebrisFieldService.php b/app/Services/DebrisFieldService.php index f9ee0dae..4f184fb6 100644 --- a/app/Services/DebrisFieldService.php +++ b/app/Services/DebrisFieldService.php @@ -23,11 +23,6 @@ class DebrisFieldService */ private DebrisField $debrisField; - /** - * @var ObjectService - */ - private ObjectService $objectService; - /** * @var PlayerService */ @@ -36,12 +31,10 @@ class DebrisFieldService /** * DebrisFieldService constructor. * - * @param ObjectService $objectService * @param PlayerService $playerService */ - public function __construct(ObjectService $objectService, PlayerService $playerService) + public function __construct(PlayerService $playerService) { - $this->objectService = $objectService; $this->playerService = $playerService; } @@ -201,7 +194,7 @@ public function delete(): void */ public function calculateRequiredRecyclers(): int { - $recycler = $this->objectService->getUnitObjectByMachineName('recycler'); + $recycler = ObjectService::getUnitObjectByMachineName('recycler'); $recyclerCapacity = $recycler->properties->capacity->calculate($this->playerService)->totalValue; $totalDebris = $this->debrisField->metal + $this->debrisField->crystal + $this->debrisField->deuterium; diff --git a/app/Services/FleetMissionService.php b/app/Services/FleetMissionService.php index 959a6160..8fc7b4f7 100644 --- a/app/Services/FleetMissionService.php +++ b/app/Services/FleetMissionService.php @@ -28,11 +28,6 @@ class FleetMissionService */ private PlayerService $player; - /** - * @var ObjectService $objects - */ - private ObjectService $objects; - /** * @var MessageService $messageService */ @@ -55,10 +50,9 @@ class FleetMissionService /** * FleetMissionService constructor. */ - public function __construct(PlayerService $player, ObjectService $objects, MessageService $messageService, GameMissionFactory $gameMissionFactory, SettingsService $settingsService) + public function __construct(PlayerService $player, MessageService $messageService, GameMissionFactory $gameMissionFactory, SettingsService $settingsService) { $this->player = $player; - $this->objects = $objects; $this->messageService = $messageService; $this->gameMissionFactory = $gameMissionFactory; $this->settingsService = $settingsService; @@ -196,7 +190,7 @@ public function getFleetUnitCount(FleetMission $mission): int // Loop through all known unit types and sum them up. $unit_count = 0; - foreach ($this->objects->getShipObjects() as $ship) { + foreach (ObjectService::getShipObjects() as $ship) { $unit_count += $mission->{$ship->machine_name}; } @@ -213,7 +207,7 @@ public function getFleetUnits(FleetMission $mission): UnitCollection { $units = new UnitCollection(); - foreach ($this->objects->getShipObjects() as $ship) { + foreach (ObjectService::getShipObjects() as $ship) { $amount = $mission->{$ship->machine_name}; if ($amount > 0) { $units->addUnit($ship, $mission->{$ship->machine_name}); diff --git a/app/Services/ObjectService.php b/app/Services/ObjectService.php index 0ba6272b..07123421 100644 --- a/app/Services/ObjectService.php +++ b/app/Services/ObjectService.php @@ -21,9 +21,9 @@ use RuntimeException; /** - * Class ObjectService. + * Static class ObjectService. * - * Contains all information about game objects such as buildings, research, + * Contains static helper methods to retrieve information about game objects such as buildings, research, * ships, defense etc. * * @package OGame\Services @@ -35,7 +35,7 @@ class ObjectService * * @return array */ - public function getObjects(): array + public static function getObjects(): array { return array_merge(BuildingObjects::get(), StationObjects::get(), ResearchObjects::get(), MilitaryShipObjects::get(), CivilShipObjects::get(), DefenseObjects::get()); } @@ -45,7 +45,7 @@ public function getObjects(): array * * @return array */ - public function getBuildingObjects(): array + public static function getBuildingObjects(): array { return BuildingObjects::get(); } @@ -55,7 +55,7 @@ public function getBuildingObjects(): array * * @return array */ - public function getStationObjects(): array + public static function getStationObjects(): array { return StationObjects::get(); } @@ -65,7 +65,7 @@ public function getStationObjects(): array * * @return array */ - public function getResearchObjects(): array + public static function getResearchObjects(): array { return ResearchObjects::get(); } @@ -75,7 +75,7 @@ public function getResearchObjects(): array * * @return array */ - public function getUnitObjects(): array + public static function getUnitObjects(): array { return array_merge(MilitaryShipObjects::get(), CivilShipObjects::get(), DefenseObjects::get()); } @@ -85,7 +85,7 @@ public function getUnitObjects(): array * * @return array */ - public function getShipObjects(): array + public static function getShipObjects(): array { return array_merge(MilitaryShipObjects::get(), CivilShipObjects::get()); } @@ -95,7 +95,7 @@ public function getShipObjects(): array * * @return array */ - public function getDefenseObjects(): array + public static function getDefenseObjects(): array { return DefenseObjects::get(); } @@ -105,7 +105,7 @@ public function getDefenseObjects(): array * * @return array */ - public function getMilitaryShipObjects(): array + public static function getMilitaryShipObjects(): array { return MilitaryShipObjects::get(); } @@ -115,7 +115,7 @@ public function getMilitaryShipObjects(): array * * @return array */ - public function getCivilShipObjects(): array + public static function getCivilShipObjects(): array { return CivilShipObjects::get(); } @@ -126,7 +126,7 @@ public function getCivilShipObjects(): array * @param string $machine_name * @return BuildingObject */ - public function getBuildingObjectByMachineName(string $machine_name): BuildingObject + public static function getBuildingObjectByMachineName(string $machine_name): BuildingObject { // Loop through all buildings and return the one with the matching UID foreach (BuildingObjects::get() as $building) { @@ -144,7 +144,7 @@ public function getBuildingObjectByMachineName(string $machine_name): BuildingOb * @param string $machine_name * @return ShipObject */ - public function getShipObjectByMachineName(string $machine_name): ShipObject + public static function getShipObjectByMachineName(string $machine_name): ShipObject { // Loop through all buildings and return the one with the matching UID $shipObjects = array_merge(MilitaryShipObjects::get(), CivilShipObjects::get()); @@ -163,7 +163,7 @@ public function getShipObjectByMachineName(string $machine_name): ShipObject * @param int $object_id * @return GameObject */ - public function getObjectById(int $object_id): GameObject + public static function getObjectById(int $object_id): GameObject { // Loop through all buildings and return the one with the matching UID $allObjects = array_merge(BuildingObjects::get(), StationObjects::get(), ResearchObjects::get(), MilitaryShipObjects::get(), CivilShipObjects::get(), DefenseObjects::get()); @@ -182,7 +182,7 @@ public function getObjectById(int $object_id): GameObject * @param string $machine_name * @return GameObject */ - public function getObjectByMachineName(string $machine_name): GameObject + public static function getObjectByMachineName(string $machine_name): GameObject { // Loop through all buildings and return the one with the matching UID $allObjects = array_merge(BuildingObjects::get(), StationObjects::get(), ResearchObjects::get(), MilitaryShipObjects::get(), CivilShipObjects::get(), DefenseObjects::get()); @@ -201,7 +201,7 @@ public function getObjectByMachineName(string $machine_name): GameObject * @param string $machine_name * @return ResearchObject */ - public function getResearchObjectByMachineName(string $machine_name): ResearchObject + public static function getResearchObjectByMachineName(string $machine_name): ResearchObject { // Loop through all buildings and return the one with the matching UID $allObjects = ResearchObjects::get(); @@ -220,7 +220,7 @@ public function getResearchObjectByMachineName(string $machine_name): ResearchOb * @param int $object_id * @return ResearchObject */ - public function getResearchObjectById(int $object_id): ResearchObject + public static function getResearchObjectById(int $object_id): ResearchObject { // Loop through all buildings and return the one with the matching UID $allObjects = ResearchObjects::get(); @@ -239,7 +239,7 @@ public function getResearchObjectById(int $object_id): ResearchObject * @param int $object_id * @return UnitObject */ - public function getUnitObjectById(int $object_id): UnitObject + public static function getUnitObjectById(int $object_id): UnitObject { $allObjects = array_merge(MilitaryShipObjects::get(), CivilShipObjects::get(), DefenseObjects::get()); foreach ($allObjects as $object) { @@ -257,7 +257,7 @@ public function getUnitObjectById(int $object_id): UnitObject * @param string $machine_name * @return UnitObject */ - public function getUnitObjectByMachineName(string $machine_name): UnitObject + public static function getUnitObjectByMachineName(string $machine_name): UnitObject { // Loop through all buildings and return the one with the matching UID $allObjects = array_merge(MilitaryShipObjects::get(), CivilShipObjects::get(), DefenseObjects::get()); @@ -275,11 +275,11 @@ public function getUnitObjectByMachineName(string $machine_name): UnitObject * * @return array */ - public function getGameObjectsWithProduction(): array + public static function getGameObjectsWithProduction(): array { $return = array(); - foreach ($this->getObjects() as $value) { + foreach (self::getObjects() as $value) { if (!empty(($value->production))) { $return[] = $value; } @@ -294,9 +294,9 @@ public function getGameObjectsWithProduction(): array * @param string $machine_name * @return GameObject */ - public function getGameObjectsWithProductionByMachineName(string $machine_name): GameObject + public static function getGameObjectsWithProductionByMachineName(string $machine_name): GameObject { - foreach ($this->getObjects() as $object) { + foreach (self::getObjects() as $object) { if ($object->machine_name === $machine_name && !empty(($object->production))) { return $object; } @@ -310,7 +310,7 @@ public function getGameObjectsWithProductionByMachineName(string $machine_name): * * @return array */ - public function getBuildingObjectsWithStorage(): array + public static function getBuildingObjectsWithStorage(): array { $return = array(); @@ -333,21 +333,21 @@ public function getBuildingObjectsWithStorage(): array * @param bool $queued * @return bool */ - public function objectRequirementsMet(string $machine_name, PlanetService $planet, PlayerService $player, int $level = 0, bool $queued = true): bool + public static function objectRequirementsMet(string $machine_name, PlanetService $planet, PlayerService $player, int $level = 0, bool $queued = true): bool { try { - $object = $this->getObjectByMachineName($machine_name); + $object = self::getObjectByMachineName($machine_name); // Check required prior levels if ($level) { - if (!$this->objectLevelsMet($object, $planet, $player, $level, $queued)) { + if (!self::objectLevelsMet($object, $planet, $player, $level, $queued)) { return false; } } foreach ($object->requirements as $requirement) { // Load required object and check if requirements are met. - $object_required = $this->getObjectByMachineName($requirement->object_machine_name); + $object_required = self::getObjectByMachineName($requirement->object_machine_name); $check_queue = $queued; // Skip queue check for research lab as it must be present for research objects @@ -385,7 +385,7 @@ public function objectRequirementsMet(string $machine_name, PlanetService $plane * @return int * @throws Exception */ - public function getObjectMaxBuildAmount(string $machine_name, PlanetService $planet, bool $requirements_met): int + public static function getObjectMaxBuildAmount(string $machine_name, PlanetService $planet, bool $requirements_met): int { // If requirements are false, the max build amount is 0 if (!$requirements_met) { @@ -397,7 +397,7 @@ public function getObjectMaxBuildAmount(string $machine_name, PlanetService $pla return $planet->getObjectAmount($machine_name) ? 0 : 1; } - $price = $this->getObjectPrice($machine_name, $planet); + $price = self::getObjectPrice($machine_name, $planet); // Calculate max build amount based on price $max_build_amount = []; @@ -430,9 +430,9 @@ public function getObjectMaxBuildAmount(string $machine_name, PlanetService $pla * @return Resources * @throws Exception */ - public function getObjectPrice(string $machine_name, PlanetService $planet): Resources + public static function getObjectPrice(string $machine_name, PlanetService $planet): Resources { - $object = $this->getObjectByMachineName($machine_name); + $object = self::getObjectByMachineName($machine_name); $player = $planet->getPlayer(); // Price calculation for buildings or research (price depends on level) @@ -443,11 +443,11 @@ public function getObjectPrice(string $machine_name, PlanetService $planet): Res $current_level = $player?->getResearchLevel($object->machine_name); } - $price = $this->getObjectRawPrice($machine_name, $current_level + 1); + $price = self::getObjectRawPrice($machine_name, $current_level + 1); } // Price calculation for fleet or defense (regular price per unit) else { - $price = $this->getObjectRawPrice($machine_name); + $price = self::getObjectRawPrice($machine_name); } return $price; @@ -460,10 +460,10 @@ public function getObjectPrice(string $machine_name, PlanetService $planet): Res * @param int $level * @return Resources */ - public function getObjectRawPrice(string $machine_name, int $level = 0): Resources + public static function getObjectRawPrice(string $machine_name, int $level = 0): Resources { try { - $object = $this->getObjectByMachineName($machine_name); + $object = self::getObjectByMachineName($machine_name); } catch (Exception $e) { return new Resources(0, 0, 0, 0); } @@ -518,7 +518,7 @@ public function getObjectRawPrice(string $machine_name, int $level = 0): Resourc * @param bool $queued * @return bool */ - private function objectLevelsMet(GameObject $object, PlanetService $planet, PlayerService $player, int $level, bool $queued): bool + private static function objectLevelsMet(GameObject $object, PlanetService $planet, PlayerService $player, int $level, bool $queued): bool { $current_level = 0; diff --git a/app/Services/PlanetService.php b/app/Services/PlanetService.php index c6464525..9f37bb16 100644 --- a/app/Services/PlanetService.php +++ b/app/Services/PlanetService.php @@ -26,13 +26,6 @@ */ class PlanetService { - /** - * Information about objects. - * - * @var ObjectService - */ - public ObjectService $objects; - /** * The planet object from the model. * @@ -62,7 +55,7 @@ class PlanetService * @param int $planet_id * If supplied the constructor will try to load the planet from the database. */ - public function __construct(ObjectService $objectService, PlayerServiceFactory $playerServiceFactory, SettingsService $settingsService, PlayerService|null $player = null, int $planet_id = 0) + public function __construct(PlayerServiceFactory $playerServiceFactory, SettingsService $settingsService, PlayerService|null $player = null, int $planet_id = 0) { // Load the planet object if a positive planet ID is given. // If no planet ID is given then planet context will not be available @@ -81,7 +74,6 @@ public function __construct(ObjectService $objectService, PlayerServiceFactory $ $this->player = $player; } - $this->objects = $objectService; $this->settingsService = $settingsService; } @@ -575,7 +567,7 @@ public function getFlightShipAmount(): int { $totalCount = 0; - $objects = $this->objects->getShipObjects(); + $objects = ObjectService::getShipObjects(); foreach ($objects as $object) { if ($object->machine_name === 'solar_satellite') { // Do not count solar satellite as ship. @@ -595,7 +587,7 @@ public function getFlightShipAmount(): int public function getShipUnits(): UnitCollection { $units = new UnitCollection(); - $objects = $this->objects->getShipObjects(); + $objects = ObjectService::getShipObjects(); foreach ($objects as $object) { if ($this->planet->{$object->machine_name} > 0) { $units->addUnit($object, $this->planet->{$object->machine_name}); @@ -613,7 +605,7 @@ public function getShipUnits(): UnitCollection public function getDefenseUnits(): UnitCollection { $units = new UnitCollection(); - $objects = $this->objects->getDefenseObjects(); + $objects = ObjectService::getDefenseObjects(); foreach ($objects as $object) { if ($this->planet->{$object->machine_name} > 0) { $units->addUnit($object, $this->planet->{$object->machine_name}); @@ -632,7 +624,7 @@ public function getBuildingArray(): array { // TODO: can this logic be moved to the EspionageReport class if its not used elsewehere? $array = []; - $objects = [...$this->objects->getBuildingObjects(), ...$this->objects->getStationObjects()]; + $objects = [...ObjectService::getBuildingObjects(), ...ObjectService::getStationObjects()]; foreach ($objects as $object) { if ($this->planet->{$object->machine_name} > 0) { $array[$object->machine_name] = $this->planet->{$object->machine_name}; @@ -653,7 +645,7 @@ public function getBuildingConstructionTime(string $machine_name): int { $current_level = $this->getObjectLevel($machine_name); $next_level = $current_level + 1; - $price = $this->objects->getObjectPrice($machine_name, $this); + $price = ObjectService::getObjectPrice($machine_name, $this); $robotfactory_level = $this->getObjectLevel('robot_factory'); $nanitefactory_level = $this->getObjectLevel('nano_factory'); @@ -687,7 +679,7 @@ public function getBuildingConstructionTime(string $machine_name): int */ public function getObjectLevel(string $machine_name): int { - $object = $this->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $level = $this->planet->{$object->machine_name}; // Required for unittests to work because db factories do not always set initial values. @@ -707,7 +699,7 @@ public function getObjectLevel(string $machine_name): int */ public function getUnitConstructionTime(string $machine_name): int { - $object = $this->objects->getUnitObjectByMachineName($machine_name); + $object = ObjectService::getUnitObjectByMachineName($machine_name); $shipyard_level = $this->getObjectLevel('shipyard'); $nanitefactory_level = $this->getObjectLevel('nano_factory'); @@ -740,9 +732,9 @@ public function getUnitConstructionTime(string $machine_name): int */ public function getTechnologyResearchTime(string $machine_name): float { - $price = $this->objects->getObjectPrice($machine_name, $this); - + $price = ObjectService::getObjectPrice($machine_name, $this); $research_lab_level = $this->getObjectLevel('research_lab'); + // Research speed is = (economy x research speed). $universe_speed = $this->settingsService->economySpeed() * $this->settingsService->researchSpeed(); @@ -774,7 +766,7 @@ public function getTechnologyResearchTime(string $machine_name): float */ public function setBuildingPercent(int $building_id, int $percentage): bool { - $building = $this->objects->getObjectById($building_id); + $building = ObjectService::getObjectById($building_id); // Sanity check: percentage inside allowed values. // Sanity check: model property exists. @@ -1084,7 +1076,7 @@ public function getPlanetId(): int */ public function setObjectLevel(int $object_id, int $level, bool $save_planet = true): void { - $object = $this->objects->getObjectById($object_id); + $object = ObjectService::getObjectById($object_id); $this->planet->{$object->machine_name} = $level; if ($save_planet) { $this->save(); @@ -1109,7 +1101,7 @@ public function updateUnitQueue(bool $save_planet = true): void // @TODO: add DB transaction wrapper foreach ($unit_queue as $item) { // Get object information. - $object = $this->objects->getUnitObjectById($item->object_id); + $object = ObjectService::getUnitObjectById($item->object_id); // Calculate if we can partially (or fully) complete this order // yet based on time per unit and amount of ordered units. @@ -1163,7 +1155,7 @@ public function updateUnitQueue(bool $save_planet = true): void */ public function addUnit(string $machine_name, int $amount, bool $save_planet = true): void { - $object = $this->objects->getUnitObjectByMachineName($machine_name); + $object = ObjectService::getUnitObjectByMachineName($machine_name); $this->planet->{$object->machine_name} += $amount; if ($save_planet) { @@ -1200,7 +1192,7 @@ public function addUnits(UnitCollection $units, bool $save_planet = true): void */ public function removeUnit(string $machine_name, int $amount, bool $save_planet = true): void { - $object = $this->objects->getUnitObjectByMachineName($machine_name); + $object = ObjectService::getUnitObjectByMachineName($machine_name); if ($this->planet->{$object->machine_name} < $amount) { throw new RuntimeException('Planet does not have enough units.'); } @@ -1293,7 +1285,7 @@ public function getPlanetBasicIncome(): Resources */ private function updateResourceProductionStatsInner(Resources $production_total, int|float $energy_production_total, int|float $energy_consumption_total, bool $save_planet = true): void { - foreach ($this->objects->getGameObjectsWithProduction() as $object) { + foreach (ObjectService::getGameObjectsWithProduction() as $object) { // Retrieve all game objects that have production values. $production = $this->getObjectProduction($object->machine_name); @@ -1336,7 +1328,7 @@ private function updateResourceProductionStatsInner(Resources $production_total, */ public function getObjectProduction(string $machine_name, int|null $object_level = null, bool $force_factor = false): Resources { - $gameObject = $this->objects->getGameObjectsWithProductionByMachineName($machine_name); + $gameObject = ObjectService::getGameObjectsWithProductionByMachineName($machine_name); $resource_production_factor = 100; // Set default to 100, only override // when the building level is not set (which means current output is @@ -1439,7 +1431,7 @@ public function energyConsumption(): Resource */ public function getBuildingPercent(string $machine_name): int { - $building = $this->objects->getObjectByMachineName($machine_name); + $building = ObjectService::getObjectByMachineName($machine_name); // Sanity check: model property exists. return $this->planet->{$building->machine_name . '_percent'} ?? 0; @@ -1466,7 +1458,7 @@ public function isBuilding(): bool */ public function isBuildingObject(string $machine_name, int $level): bool { - $object = $this->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); // Check only building queue objects if ($object->type !== GameObjectType::Building && $object->type !== GameObjectType::Station) { @@ -1536,7 +1528,7 @@ public function getPlanetTempMax(): int public function updateResourceStorageStats(bool $save_planet = true): void { $storage_sum = new Resources(0, 0, 0, 0); - foreach ($this->objects->getBuildingObjectsWithStorage() as $building) { + foreach (ObjectService::getBuildingObjectsWithStorage() as $building) { // Retrieve all buildings that have production values. $storage = $this->getBuildingMaxStorage($building->machine_name); @@ -1565,7 +1557,7 @@ public function updateResourceStorageStats(bool $save_planet = true): void */ public function getBuildingMaxStorage(string $machine_name, int|bool $object_level = false): Resources { - $building = $this->objects->getBuildingObjectByMachineName($machine_name); + $building = ObjectService::getBuildingObjectByMachineName($machine_name); // NOTE: $object_level is used by eval() function in the formula. if (!$object_level) { @@ -1594,17 +1586,17 @@ public function getPlanetScore(): int $resources_spent = new Resources(0, 0, 0, 0); // Create object array - $building_objects = $this->objects->getBuildingObjects() + $this->objects->getStationObjects(); + $building_objects = ObjectService::getBuildingObjects() + ObjectService::getStationObjects(); foreach ($building_objects as $object) { for ($i = 1; $i <= $this->getObjectLevel($object->machine_name); $i++) { // Concatenate price which is array of metal, crystal and deuterium. - $raw_price = $this->objects->getObjectRawPrice($object->machine_name, $i); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name, $i); $resources_spent->add($raw_price); } } - $unit_objects = $this->objects->getShipObjects() + $this->objects->getDefenseObjects(); + $unit_objects = ObjectService::getShipObjects() + ObjectService::getDefenseObjects(); foreach ($unit_objects as $object) { - $raw_price = $this->objects->getObjectRawPrice($object->machine_name); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name); // Multiply raw_price by the amount of units. $resources_spent->add($raw_price->multiply($this->getObjectAmount($object->machine_name))); } @@ -1624,7 +1616,7 @@ public function getPlanetScore(): int */ public function getObjectAmount(string $machine_name): int { - $object = $this->objects->getUnitObjectByMachineName($machine_name); + $object = ObjectService::getUnitObjectByMachineName($machine_name); if (!empty($this->planet->{$object->machine_name})) { return $this->planet->{$object->machine_name}; @@ -1654,26 +1646,26 @@ public function getPlanetScoreEconomy(): int $resources_spent = 0; // Buildings (100%) - $building_objects = [ ...$this->objects->getBuildingObjects(), ...$this->objects->getStationObjects() ]; + $building_objects = [ ...ObjectService::getBuildingObjects(), ...ObjectService::getStationObjects() ]; foreach ($building_objects as $object) { for ($i = 1; $i <= $this->getObjectLevel($object->machine_name); $i++) { // Concatenate price which is array of metal, crystal and deuterium. - $raw_price = $this->objects->getObjectRawPrice($object->machine_name, $i); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name, $i); $resources_spent += $raw_price->sum(); } } // Defense (100%) - $defense_objects = $this->objects->getDefenseObjects(); + $defense_objects = ObjectService::getDefenseObjects(); foreach ($defense_objects as $object) { - $raw_price = $this->objects->getObjectRawPrice($object->machine_name); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name); $resources_spent += $raw_price->multiply($this->getObjectAmount($object->machine_name))->sum(); } // Civil ships (50%) - $civil_ships = $this->objects->getCivilShipObjects(); + $civil_ships = ObjectService::getCivilShipObjects(); foreach ($civil_ships as $object) { - $raw_price = $this->objects->getObjectRawPrice($object->machine_name); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name); $resources_spent += $raw_price->multiply($this->getObjectAmount($object->machine_name))->sum() * 0.5; } @@ -1704,24 +1696,24 @@ public function getPlanetMilitaryScore(): int $resources_spent = 0; // Defense (100%) - $defense_objects = $this->objects->getDefenseObjects(); + $defense_objects = ObjectService::getDefenseObjects(); foreach ($defense_objects as $object) { - $raw_price = $this->objects->getObjectRawPrice($object->machine_name); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name); // Multiply raw_price by the amount of units. $resources_spent += $raw_price->multiply($this->getObjectAmount($object->machine_name))->sum(); } // Military ships (100%) - $military_ships = $this->objects->getMilitaryShipObjects(); + $military_ships = ObjectService::getMilitaryShipObjects(); foreach ($military_ships as $object) { - $raw_price = $this->objects->getObjectRawPrice($object->machine_name); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name); $resources_spent += $raw_price->multiply($this->getObjectAmount($object->machine_name))->sum(); } // Civil ships (50%) - $civil_ships = $this->objects->getCivilShipObjects(); + $civil_ships = ObjectService::getCivilShipObjects(); foreach ($civil_ships as $object) { - $raw_price = $this->objects->getObjectRawPrice($object->machine_name); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name); $resources_spent += $raw_price->multiply($this->getObjectAmount($object->machine_name))->sum() * 0.5; } diff --git a/app/Services/PlayerService.php b/app/Services/PlayerService.php index 200b2ef9..0f734296 100644 --- a/app/Services/PlayerService.php +++ b/app/Services/PlayerService.php @@ -26,7 +26,7 @@ class PlayerService { /** - * The planetlist object for this player. + * The planet list object for this player. * * @var PlanetListService */ @@ -46,26 +46,18 @@ class PlayerService */ private UserTech $user_tech; - /** - * @var ObjectService - */ - private ObjectService $objects; - /** * Player constructor. * * @param int $player_id - * @param ObjectService $objectService */ - public function __construct(int $player_id, ObjectService $objectService) + public function __construct(int $player_id) { // Load the player object if a positive player ID is given. // If no player ID is given then player context will not be available, but this can be fine for unittests. if ($player_id !== 0) { $this->load($player_id); } - - $this->objects = $objectService; } /** @@ -287,7 +279,7 @@ public function getEmail(): string */ public function getResearchLevel(string $machine_name): int { - $research = $this->objects->getResearchObjectByMachineName($machine_name); + $research = ObjectService::getResearchObjectByMachineName($machine_name); $research_level = $this->user_tech->{$research->machine_name}; if ($research_level) { @@ -307,7 +299,7 @@ public function getResearchLevel(string $machine_name): int */ public function setResearchLevel(string $machine_name, int $level, bool $save_to_db = true): void { - $research = $this->objects->getResearchObjectByMachineName($machine_name); + $research = ObjectService::getResearchObjectByMachineName($machine_name); $this->user_tech->{$research->machine_name} = $level; if ($save_to_db) { @@ -407,7 +399,7 @@ public function updateResearchQueue(bool $save_user = true): void // @TODO: add DB transaction wrapper foreach ($research_queue as $item) { // Get object information of research object. - $object = $this->objects->getResearchObjectById($item->object_id); + $object = ObjectService::getResearchObjectById($item->object_id); // Update planet and update level of the building that has been processed. $this->setResearchLevel($object->machine_name, $item->object_level_target); @@ -487,11 +479,11 @@ public function getResearchScore(): int $resources_spent = new Resources(0, 0, 0, 0); // Create object array - $research_objects = $this->objects->getResearchObjects(); + $research_objects = ObjectService::getResearchObjects(); foreach ($research_objects as $object) { for ($i = 1; $i <= $this->getResearchLevel($object->machine_name); $i++) { // Concatenate price which is array of metal, crystal and deuterium. - $raw_price = $this->objects->getObjectRawPrice($object->machine_name, $i); + $raw_price = ObjectService::getObjectRawPrice($object->machine_name, $i); $resources_spent->add($raw_price); } } @@ -509,7 +501,7 @@ public function getResearchScore(): int public function getResearchArray(): array { $array = []; - $objects = $this->objects->getResearchObjects(); + $objects = ObjectService::getResearchObjects(); foreach ($objects as $object) { if ($this->user_tech->{$object->machine_name} > 0) { $array[$object->machine_name] = $this->user_tech->{$object->machine_name}; @@ -527,7 +519,7 @@ public function getResearchArray(): array public function getMaxPlanetAmount(): int { $astrophyicsLevel = $this->getResearchLevel('astrophysics'); - $astrophysicsObject = $this->planets->current()->objects->getResearchObjectByMachineName('astrophysics'); + $astrophysicsObject = ObjectService::getResearchObjectByMachineName('astrophysics'); // +1 to max_colonies to get max_planets because the main planet is not included in the calculation above. return 1 + $astrophysicsObject->performCalculation(CalculationType::MAX_COLONIES, $astrophyicsLevel); diff --git a/app/Services/ResearchQueueService.php b/app/Services/ResearchQueueService.php index 2261676b..14bc1b17 100644 --- a/app/Services/ResearchQueueService.php +++ b/app/Services/ResearchQueueService.php @@ -19,13 +19,6 @@ */ class ResearchQueueService { - /** - * Information about objects. - * - * @var ObjectService - */ - private ObjectService $objects; - /** * The queue model where this class should get its data from. * @@ -34,14 +27,10 @@ class ResearchQueueService private ResearchQueue $model; /** - * BuildingQueue constructor. - * - * @param ObjectService $objects + * ResearchQueueService constructor. */ - public function __construct(ObjectService $objects) + public function __construct() { - $this->objects = $objects; - $this->model = new ResearchQueue(); } @@ -125,11 +114,11 @@ public function add(PlayerService $player, PlanetService $planet, int $research_ throw new Exception('Maximum number of items already in queue.'); } - $object = $this->objects->getResearchObjectById($research_object_id); + $object = ObjectService::getResearchObjectById($research_object_id); // Check if user satisifes requirements to research this object. // TODO: refactor throw exception into a more user-friendly message. - $requirements_met = $this->objects->objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer()); + $requirements_met = ObjectService::objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer()); if (!$requirements_met) { throw new Exception('Requirements not met to build this object.'); } @@ -180,7 +169,7 @@ public function retrieveQueue(PlanetService $planet): ResearchQueueListViewModel // Convert to ViewModel array $list = []; foreach ($queue_items as $item) { - $object = $this->objects->getResearchObjectById($item->object_id); + $object = ObjectService::getResearchObjectById($item->object_id); $planetService = $planet->getPlayer()->planets->childPlanetById($item['planet_id']); $time_countdown = $item->time_end - (int)Carbon::now()->timestamp; if ($time_countdown < 0) { @@ -259,10 +248,10 @@ public function start(PlayerService $player, int $time_start = 0): void foreach ($queue_items as $queue_item) { $planet = $player->planets->childPlanetById($queue_item->planet_id); - $object = $this->objects->getResearchObjectById($queue_item->object_id); + $object = ObjectService::getResearchObjectById($queue_item->object_id); // See if the planet has enough resources for this research attempt. - $price = $this->objects->getObjectPrice($object->machine_name, $planet); + $price = ObjectService::getObjectPrice($object->machine_name, $planet); $research_time = $player->planets->current()->getTechnologyResearchTime($object->machine_name); // Only start the queue item if there are no other queue items researching @@ -297,7 +286,7 @@ public function start(PlayerService $player, int $time_start = 0): void // Sanity check: check if the researching requirements are still met. If not, // then cancel research request. - if (!$this->objects->objectRequirementsMet($object->machine_name, $planet, $player, $queue_item->object_level_target, false)) { + if (!ObjectService::objectRequirementsMet($object->machine_name, $planet, $player, $queue_item->object_level_target, false)) { $this->cancel($player, $queue_item->id, $queue_item->object_id); continue; @@ -405,7 +394,7 @@ public function objectInResearchQueue(PlayerService $player, string $machine_nam ->get(); foreach ($queue_items as $item) { - $object = $this->objects->getObjectById($item->object_id); + $object = ObjectService::getObjectById($item->object_id); if ($object->machine_name === $machine_name && $item->object_level_target === $level) { return true; @@ -436,9 +425,9 @@ public function cancelItemMissingRequirements(PlayerService $player, PlanetServi ->get(); foreach ($research_queue_items as $research_queue_item) { - $object = $this->objects->getObjectById($research_queue_item->object_id); + $object = ObjectService::getObjectById($research_queue_item->object_id); - if (!$this->objects->objectRequirementsMet($object->machine_name, $planet, $player, $research_queue_item->object_level_target)) { + if (!ObjectService::objectRequirementsMet($object->machine_name, $planet, $player, $research_queue_item->object_level_target)) { $this->cancel($player, $research_queue_item->id, $object->id); break; } diff --git a/app/Services/UnitQueueService.php b/app/Services/UnitQueueService.php index 03c6d77d..b4dce52f 100644 --- a/app/Services/UnitQueueService.php +++ b/app/Services/UnitQueueService.php @@ -19,13 +19,6 @@ */ class UnitQueueService { - /** - * Information about objects. - * - * @var ObjectService - */ - private ObjectService $objects; - /** * The queue model where this class should get its data from. * @@ -36,10 +29,8 @@ class UnitQueueService /** * UnitQueueService constructor. */ - public function __construct(ObjectService $objects) + public function __construct() { - $this->objects = $objects; - $this->model = new UnitQueue(); } @@ -63,7 +54,7 @@ public function retrieveQueue(PlanetService $planet): UnitQueueListViewModel // Convert to ViewModel array $list = array(); foreach ($queue_items as $item) { - $object = $this->objects->getObjectById($item['object_id']); + $object = ObjectService::getObjectById($item['object_id']); $time_countdown = $item->time_end - (int)Carbon::now()->timestamp; if ($time_countdown < 0) { @@ -156,16 +147,16 @@ public function add(PlanetService $planet, int $object_id, int $requested_build_ return; } - $object = $this->objects->getUnitObjectById($object_id); + $object = ObjectService::getUnitObjectById($object_id); // Check if user satisifes requirements to build this object. - $requirements_met = $this->objects->objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer(), 0, false); + $requirements_met = ObjectService::objectRequirementsMet($object->machine_name, $planet, $planet->getPlayer(), 0, false); // Sanity check: check if the planet has enough resources to build // the amount requested. If not, then adjust the ordered amount. // E.g. if a player orders 100 units but can only afford 60 units, // 60 units will be added to the queue and resources will be deducted. - $max_build_amount = $this->objects->getObjectMaxBuildAmount($object->machine_name, $planet, $requirements_met); + $max_build_amount = ObjectService::getObjectMaxBuildAmount($object->machine_name, $planet, $requirements_met); if ($requested_build_amount > $max_build_amount) { $requested_build_amount = $max_build_amount; } @@ -177,7 +168,7 @@ public function add(PlanetService $planet, int $object_id, int $requested_build_ } // Get price per unit - $price_per_unit = $this->objects->getObjectPrice($object->machine_name, $planet); + $price_per_unit = ObjectService::getObjectPrice($object->machine_name, $planet); $total_price = $price_per_unit->multiply($requested_build_amount); // @TODO: add abstraction and unittest to see if multiplication diff --git a/tests/AccountTestCase.php b/tests/AccountTestCase.php index 5ecb9ba2..1ed6571f 100644 --- a/tests/AccountTestCase.php +++ b/tests/AccountTestCase.php @@ -13,9 +13,11 @@ use OGame\Models\Planet\Coordinate; use OGame\Models\Resources; use OGame\Models\User; +use OGame\Services\ObjectService; use OGame\Services\PlanetService; use OGame\Services\PlayerService; use OGame\Services\SettingsService; +use Carbon\Carbon; /** * Base class for tests that require account context. Common setup includes signup of new account and login. @@ -26,6 +28,7 @@ abstract class AccountTestCase extends TestCase protected string $currentUsername = ''; protected int $currentPlanetId = 0; protected PlanetService $secondPlanetService; + protected Carbon $defaultTestTime; /** * Set up common test components. @@ -35,6 +38,9 @@ protected function setUp(): void { parent::setUp(); + // Set default test time to 2024-01-01 00:00:00 to ensure all tests have the same starting point. + $this->travelTo(Carbon::create(2024, 1, 1, 0, 0, 0)); + // Set amount of planets to be created for the user to 2 because planet switching // is a part of the test suite. $settingsService = resolve(SettingsService::class); @@ -271,7 +277,7 @@ protected function planetDeductResources(Resources $resources): void protected function planetSetObjectLevel(string $machine_name, int $object_level): void { // Update the object level on the planet. - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $this->planetService->setObjectLevel($object->id, $object_level, true); } @@ -321,7 +327,7 @@ protected function assertObjectLevelOnPage(TestResponse $response, string $machi // Get object name from machine name. try { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); } catch (Exception $e) { $this->fail('Failed to get object by machine name: ' . $machine_name . '. Error: ' . $e->getMessage()); } @@ -388,7 +394,7 @@ protected function assertObjectInQueue(TestResponse $response, string $machine_n { // Get object name from machine name. try { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); } catch (Exception $e) { $this->fail('Failed to get object by machine name: ' . $machine_name . '. Error: ' . $e->getMessage()); } @@ -415,7 +421,7 @@ protected function assertObjectNotInQueue(TestResponse $response, string $machin { // Get object name from machine name. try { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); } catch (Exception $e) { $this->fail('Failed to get object by machine name: ' . $machine_name . '. Error: ' . $e->getMessage()); } @@ -474,7 +480,7 @@ protected function assertRequirementsNotMet(TestResponse $response, string $mach { // Get object name from machine name. try { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); } catch (Exception $e) { $this->fail('Failed to get object by machine name: ' . $machine_name . '. Error: ' . $e->getMessage()); } @@ -505,7 +511,7 @@ protected function assertRequirementsNotMet(TestResponse $response, string $mach */ protected function addResourceBuildRequest(string $machine_name, bool $ignoreErrors = false): void { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $response = $this->post('/resources/add-buildrequest', [ '_token' => csrf_token(), @@ -547,7 +553,7 @@ protected function cancelResourceBuildRequest(int $objectId, int $buildQueueId): */ protected function addFacilitiesBuildRequest(string $machine_name): void { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $response = $this->post('/facilities/add-buildrequest', [ '_token' => csrf_token(), @@ -583,7 +589,7 @@ protected function cancelFacilitiesBuildRequest(int $objectId, int $buildQueueId */ protected function addResearchBuildRequest(string $machine_name): void { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $response = $this->post('/research/add-buildrequest', [ '_token' => csrf_token(), @@ -622,7 +628,7 @@ protected function cancelResearchBuildRequest(int $objectId, int $buildQueueId): */ protected function addShipyardBuildRequest(string $machine_name, int $amount): void { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $response = $this->post('/shipyard/add-buildrequest', [ '_token' => csrf_token(), @@ -643,7 +649,7 @@ protected function addShipyardBuildRequest(string $machine_name, int $amount): v */ protected function addDefenseBuildRequest(string $machine_name, int $amount): void { - $object = $this->planetService->objects->getObjectByMachineName($machine_name); + $object = ObjectService::getObjectByMachineName($machine_name); $response = $this->post('/defense/add-buildrequest', [ '_token' => csrf_token(), @@ -754,4 +760,13 @@ protected function switchToSecondPlanet(): void $response = $this->get('/overview?cp=' . $this->secondPlanetService->getPlanetId()); $response->assertStatus(200); } + + /** + * Add helper method to reset time to default + * @return void + */ + protected function resetTestTime(): void + { + Carbon::setTestNow($this->defaultTestTime); + } } diff --git a/tests/Feature/AdminTest.php b/tests/Feature/AdminTest.php index 9d6dfef7..5ceed702 100644 --- a/tests/Feature/AdminTest.php +++ b/tests/Feature/AdminTest.php @@ -1,6 +1,6 @@ travel(1)->seconds(); $response = $this->get('/resources'); $this->assertObjectInQueue($response, 'metal_mine', 3, 'Metal mine level 3 is expected in build queue but cannot be found.'); @@ -68,8 +62,7 @@ public function testBuildQueueCancelMultiple(): void $this->assertObjectNotInQueue($response, 'metal_mine', 'Metal mine is in build queue but should have been canceled.'); // Advance time by 30 minutes - $testTime = Carbon::create(2024, 1, 1, 12, 30, 0); - Carbon::setTestNow($testTime); + $this->travel(30)->minutes(); // Verify that Metal Mine is still at level 0 $response = $this->get('/resources'); @@ -83,10 +76,6 @@ public function testBuildQueueCancelMultiple(): void */ public function testBuildQueueCancelRefundResources(): void { - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Verify that we begin the test with 500 metal and 500 crystal $response = $this->get('/resources'); $response->assertStatus(200); @@ -131,10 +120,6 @@ public function testBuildQueueCancelRefundResources(): void */ public function testBuildQueueCancelSecondEntry(): void { - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Verify that we begin the test with 500 metal and 500 crystal $response = $this->get('/resources'); $response->assertStatus(200); diff --git a/tests/Feature/BuildQueueTest.php b/tests/Feature/BuildQueueTest.php index 2d59b788..2ad1286f 100644 --- a/tests/Feature/BuildQueueTest.php +++ b/tests/Feature/BuildQueueTest.php @@ -1,9 +1,8 @@ set('economy_speed', 8); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build a metal mine // --- @@ -42,8 +37,7 @@ public function testBuildQueueResourcesMetalMine(): void // --- // Step 3: Verify the building is still in the build queue 2 seconds later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 0, 2); - Carbon::setTestNow($testTime); + $this->travel(2)->seconds(); // Check if the building is still in the queue and is still level 0. $response = $this->get('/resources'); @@ -52,8 +46,7 @@ public function testBuildQueueResourcesMetalMine(): void // --- // Step 4: Verify the building is finished 1 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 1, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->minutes(); // Check if the building is finished and is now level 1. $response = $this->get('/resources'); @@ -73,10 +66,6 @@ public function testBuildQueueFacilitiesRoboticsFactory(): void // Add resources to planet that test requires. $this->planetAddResources(new Resources(400, 120, 200, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build a robotics factory. // --- @@ -92,8 +81,7 @@ public function testBuildQueueFacilitiesRoboticsFactory(): void // --- // Step 3: Verify the building is still in the build queue 2 seconds later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 0, 2); - Carbon::setTestNow($testTime); + $this->travel(2)->seconds(); // Check if the building is still in the queue and is still level 0. $response = $this->get('/facilities'); @@ -102,8 +90,7 @@ public function testBuildQueueFacilitiesRoboticsFactory(): void // --- // Step 4: Verify the building is finished 10 minutes later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 10, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); // Check if the building is finished and is now level 1. $response = $this->get('/facilities'); @@ -123,10 +110,6 @@ public function testBuildQueueFacilitiesRoboticsFactoryMultiQueue(): void // Add resources to planet that test requires. $this->planetAddResources(new Resources(5000, 5000, 5000, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build two robotics factory upgrades. // --- @@ -143,8 +126,7 @@ public function testBuildQueueFacilitiesRoboticsFactoryMultiQueue(): void // --- // Step 3: Verify that one building is finished 30s later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 0, 30); - Carbon::setTestNow($testTime); + $this->travel(30)->seconds(); // Check if the building is finished and is now level 1. $response = $this->get('/facilities'); @@ -153,8 +135,7 @@ public function testBuildQueueFacilitiesRoboticsFactoryMultiQueue(): void // --- // Step 3: Verify that both building upgrades are finished 5 minutes later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 5, 0); - Carbon::setTestNow($testTime); + $this->travel(5)->minutes(); // Check if the building is finished and is now level 2. $response = $this->get('/facilities'); @@ -169,10 +150,6 @@ public function testBuildQueueFailInsufficientResources(): void { $this->planetDeductResources(new Resources(500, 500, 0, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build a metal mine. // --- @@ -181,8 +158,7 @@ public function testBuildQueueFailInsufficientResources(): void // --- // Step 2: Verify that nothing has been built as there were not enough resources. // --- - $testTime = Carbon::create(2024, 1, 1, 13, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->hours(); $response = $this->get('/resources'); $response->assertStatus(200); @@ -201,10 +177,6 @@ public function testBuildQueueFailUnfulfilledRequirements(): void $this->planetAddResources(new Resources(1000, 1000, 1000, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build a fusion reactor. // --- @@ -213,8 +185,7 @@ public function testBuildQueueFailUnfulfilledRequirements(): void // --- // Step 2: Verify that nothing has been built as the user does not have the required technology. // --- - $testTime = Carbon::create(2024, 1, 1, 13, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->hours(); $response = $this->get('/resources'); $response->assertStatus(200); @@ -227,10 +198,6 @@ public function testBuildQueueFailUnfulfilledRequirements(): void */ public function testBuildQueueFacilitiesShipyardQueuedRequirements(): void { - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Add resource to build required facilities to planet $this->planetAddResources(new Resources(5000, 5000, 5000, 0)); @@ -247,8 +214,7 @@ public function testBuildQueueFacilitiesShipyardQueuedRequirements(): void $this->addFacilitiesBuildRequest('shipyard'); // Verify the research is finished 10 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 10, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); $response = $this->get('/facilities'); $response->assertStatus(200); diff --git a/tests/Feature/FleetDispatch/FleetDispatchAttackTest.php b/tests/Feature/FleetDispatch/FleetDispatchAttackTest.php index 0b1e9a09..8d2c2381 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchAttackTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchAttackTest.php @@ -11,6 +11,7 @@ use OGame\Models\Message; use OGame\Models\Resources; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use OGame\Services\SettingsService; use Tests\FleetDispatchTestCase; use OGame\Services\DebrisFieldService; @@ -34,14 +35,14 @@ class FleetDispatchAttackTest extends FleetDispatchTestCase * Prepare the planet for the test, so it has the required buildings and research. * * @return void - * @throws BindingResolutionException */ protected function basicSetup(): void { $this->planetAddUnit('light_fighter', 5); - // Set the fleet speed to 5x for this test. + // Set the fleet speed to 1x for this test. $settingsService = resolve(SettingsService::class); + $settingsService->set('economy_speed', 8); $settingsService->set('fleet_speed', 1); } @@ -69,7 +70,7 @@ public function testFleetCheckToOwnPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $this->fleetCheckToSecondPlanet($unitCollection, false); } @@ -80,7 +81,7 @@ public function testFleetCheckToForeignPlanetSuccess(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $this->fleetCheckToOtherPlayer($unitCollection, true); } @@ -91,7 +92,7 @@ public function testFleetCheckToEmptyPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $this->fleetCheckToEmptyPosition($unitCollection, false); } @@ -103,20 +104,16 @@ public function testDispatchFleetCombatReport(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -151,17 +148,13 @@ public function testDispatchFleetReturnTrip(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 light fighter ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'light_fighter', 5, 'Light fighter are not at 5 units at beginning of test.'); // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 5); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Clear any units from foreign planet to ensure we win the battle. @@ -177,8 +170,7 @@ public function testDispatchFleetReturnTrip(): void $fleetMissionDuration = $fleetMissionService->calculateFleetMissionDuration($this->planetService, $foreignPlanet->getPlanetCoordinates(), $unitCollection); // Set time to fleet mission duration + 1 second. - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 1); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 1)->seconds(); // Reload application to make sure the defender planet is not cached as we modified it above during test. $this->reloadApplication(); @@ -203,7 +195,7 @@ public function testDispatchFleetReturnTrip(): void $this->assertCount(1, $activeMissions, 'No return trip launched after fleet with deployment mission has arrived at destination.'); // Advance time by amount of minutes it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($activeMissions->first()->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($activeMissions->first()->time_arrival)); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -230,13 +222,9 @@ public function testDispatchFleetReturnShown(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // The eventbox should only show 1 mission (the parent). @@ -268,17 +256,13 @@ public function testDispatchFleetRecallMission(): void // Add resources for test. $this->planetAddResources(new Resources(5000, 5000, 0, 0)); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'light_fighter', 5, 'Light fighter not at 5 units at beginning of test.'); // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -287,8 +271,8 @@ public function testDispatchFleetRecallMission(): void $fleetMissionId = $fleetMission->id; // Advance time by 5 seconds. - $fleetParentTime = $startTime->copy()->addSeconds(5); - Carbon::setTestNow($fleetParentTime); + $this->travel(5)->seconds(); + $fleetParentTime = Carbon::getTestNow(); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -321,7 +305,7 @@ public function testDispatchFleetRecallMission(): void $this->playerSetAllMessagesRead(); // Advance time by amount of minutes it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($fleetMission->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($fleetMission->time_arrival)); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -347,17 +331,13 @@ public function testDispatchFleetRecallMissionTwiceError(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'light_fighter', 5, 'Light fighter not at 5 units at beginning of test.'); // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -366,8 +346,7 @@ public function testDispatchFleetRecallMissionTwiceError(): void $fleetMissionId = $fleetMission->id; // Advance time by 10 seconds - $fleetParentTime = $startTime->copy()->addSeconds(5); - Carbon::setTestNow($fleetParentTime); + $this->travel(10)->seconds(); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -398,17 +377,13 @@ public function testDispatchFleetRecallMissionTwiceError(): void */ public function testDispatchFleetCombatUnitsLostAndResourceGained(): void { - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. - // Attack with 150 light fighters, defend with 100 rocket launchers. + // Attack with 200 light fighters, defend with 100 rocket launchers. // We expect attacker to win in +/- 4 rounds, while losing 10-50 light fighters. $this->planetAddUnit('light_fighter', 200); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 200); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 200); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Clear existing units from foreign planet. @@ -421,8 +396,8 @@ public function testDispatchFleetCombatUnitsLostAndResourceGained(): void // Reload application to make sure the planet is not cached. $this->reloadApplication(); - // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + // Increase time by 2 hours to ensure the mission is done. + $this->travel(2)->hours(); // Get amount of resources of the foreign planet before the battle. $attackerResourcesBefore = $this->planetService->getResources(); @@ -457,17 +432,13 @@ public function testDispatchFleetCombatUnitsLostAndResourceGained(): void */ public function testDispatchFleetAttackerLossNoReturnMission(): void { - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. // Attack with 50 light fighters, defend with 100 rocket launchers. // We expect defender to win in +/- 3 rounds. Attacker will lose all units. $this->planetAddUnit('light_fighter', 50); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 50); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 50); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Give the foreign planet some units to defend itself. @@ -482,8 +453,7 @@ public function testDispatchFleetAttackerLossNoReturnMission(): void $fleetMissionDuration = $fleetMissionService->calculateFleetMissionDuration($this->planetService, $foreignPlanet->getPlanetCoordinates(), $unitCollection); // Set time to fleet mission duration + 1 second. - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 1); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 1)->seconds(); // Reload application to make sure the planet is not cached. $this->reloadApplication(); @@ -524,7 +494,7 @@ public function testDispatchFleetUnderAttackWarning(): void // Add units to foreign planet. $foreignPlanet->addUnit('light_fighter', 1); $unitsToSend = new UnitCollection(); - $unitsToSend->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitsToSend->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); $fleetMissionService = resolve(FleetMissionService::class, ['player' => $foreignPlanet->getPlayer()]); $fleetMissionService->createNewFromPlanet($foreignPlanet, $this->planetService->getPlanetCoordinates(), PlanetType::Planet, $this->missionType, $unitsToSend, new Resources(0, 0, 0, 0)); @@ -552,14 +522,14 @@ public function testDispatchFleetMissionProcessedNotActivePlanet(): void // Add units to foreign planet. $foreignPlanet->addUnit('light_fighter', 1); $unitsToSend = new UnitCollection(); - $unitsToSend->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 1); + $unitsToSend->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 1); // Launch attack from foreign planet to the current players second planet. $fleetMissionService = resolve(FleetMissionService::class, ['player' => $foreignPlanet->getPlayer()]); $fleetMission = $fleetMissionService->createNewFromPlanet($foreignPlanet, $this->secondPlanetService->getPlanetCoordinates(), PlanetType::Planet, $this->missionType, $unitsToSend, new Resources(0, 0, 0, 0)); // Advance time by 24 hours to ensure the mission is done. - Carbon::setTestNow(Carbon::now()->addHours(24)); + $this->travel(24)->hours(); // Load overview page to trigger the update logic which should process all fleet missions associated with user, // not just the current planet. @@ -576,17 +546,13 @@ public function testDispatchFleetMissionProcessedNotActivePlanet(): void */ public function testDispatchFleetAttackerLossDebrisFieldCreated(): void { - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. // Attack with 50 light fighters, defend with 200 rocket launchers. // We expect defender to win in +/- 3 rounds. Attacker will lose all units. $this->planetAddUnit('light_fighter', 50); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('light_fighter'), 50); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('light_fighter'), 50); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Ensure that there is no debris field on the foreign planet. @@ -607,8 +573,7 @@ public function testDispatchFleetAttackerLossDebrisFieldCreated(): void $fleetMissionDuration = $fleetMissionService->calculateFleetMissionDuration($this->planetService, $foreignPlanet->getPlanetCoordinates(), $unitCollection); // Set time to fleet mission duration + 1 second. - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 1); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 1)->seconds(); // Reload application to make sure the planet is not cached. $this->reloadApplication(); @@ -645,17 +610,13 @@ public function testDispatchFleetAttackerLossDebrisFieldCreated(): void */ public function testLargeScaleAttackWithDebrisField(): void { - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Prepare attacker fleet $this->planetAddUnit('cruiser', 700000); $this->planetAddUnit('battle_ship', 100000); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('cruiser'), 700000); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('battle_ship'), 100000); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('cruiser'), 700000); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('battle_ship'), 100000); // Send fleet to a nearby foreign planet $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); @@ -679,8 +640,7 @@ public function testLargeScaleAttackWithDebrisField(): void $fleetMissionDuration = $fleetMissionService->calculateFleetMissionDuration($this->planetService, $foreignPlanet->getPlanetCoordinates(), $unitCollection); // Set time to fleet mission duration + 1 second - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 1); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 1)->seconds(); // Reload application to make sure the planet is not cached $this->reloadApplication(); diff --git a/tests/Feature/FleetDispatch/FleetDispatchColoniseTest.php b/tests/Feature/FleetDispatch/FleetDispatchColoniseTest.php index e047f683..af4c4fab 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchColoniseTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchColoniseTest.php @@ -2,12 +2,12 @@ namespace Tests\Feature\FleetDispatch; -use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Support\Carbon; use OGame\Factories\PlanetServiceFactory; use OGame\GameObjects\Models\Units\UnitCollection; use OGame\Models\Resources; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use Tests\FleetDispatchTestCase; /** @@ -51,7 +51,7 @@ public function testFleetCheckWithColonyShipSuccess(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); $this->fleetCheckToEmptyPosition($unitCollection, true); } @@ -62,7 +62,7 @@ public function testFleetCheckWithoutColonyShipError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToEmptyPosition($unitCollection, false); } @@ -73,7 +73,7 @@ public function testDispatchFleetToNotEmptyPositionFails(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); // Expecting 500 error. $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0), 500); } @@ -85,7 +85,7 @@ public function testDispatchFleetWithoutColonyShipFails(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); // Expecting 500 error. $this->sendMissionToEmptyPosition($unitCollection, new Resources(0, 0, 0, 0), 500); } @@ -97,28 +97,21 @@ public function testDispatchFleetColonizeEmptyPlanet(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to an empty planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); $newPlanetCoordinates = $this->sendMissionToEmptyPosition($unitCollection, new Resources(100, 0, 0, 0)); // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/overview'); $response->assertStatus(200); // Assert that the new planet has been created. - try { - $planetServiceFactory = resolve(PlanetServiceFactory::class); - } catch (BindingResolutionException) { - $this->fail('PlanetServiceFactory cannot be resolved from the container.'); - } + $planetServiceFactory = resolve(PlanetServiceFactory::class); + $newPlanet = $planetServiceFactory->makeForCoordinate($newPlanetCoordinates); $this->assertNotNull($newPlanet, 'New planet cannot be loaded while it should have been created.'); @@ -143,31 +136,23 @@ public function testDispatchFleetColonizeAstrophysics(): void $this->playerSetResearchLevel('astrophysics', 5); $this->planetAddUnit('colony_ship', 5); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - $created_planets = []; // Send 5 colony ships to empty planets with colonization mission. Only 2 should be created. for ($i = 0; $i < 5; $i++) { // Send fleet to an empty planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); $newPlanetCoordinates = $this->sendMissionToEmptyPosition($unitCollection, new Resources(10, 0, 0, 0)); // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/overview'); $response->assertStatus(200); // Assert that the new planet has been created. - try { - $planetServiceFactory = resolve(PlanetServiceFactory::class); - } catch (BindingResolutionException) { - $this->fail('PlanetServiceFactory cannot be resolved from the container.'); - } + $planetServiceFactory = resolve(PlanetServiceFactory::class); $newPlanet = $planetServiceFactory->makeForCoordinate($newPlanetCoordinates); if ($newPlanet !== null) { $created_planets[] = $newPlanet; @@ -198,20 +183,16 @@ public function testDispatchFleetColonizeAstroResearchInProgress(): void $this->playerSetResearchLevel('astrophysics', 2); $this->planetAddUnit('colony_ship', 5); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to an empty planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); $newPlanetCoordinates = $this->sendMissionToEmptyPosition($unitCollection, new Resources(10, 0, 0, 0)); // Upgrade astrophysics research to level 3 via research page. $this->addResearchBuildRequest('astrophysics'); // Increase time by 10 hours to ensure the mission and research should both be done. - Carbon::setTestNow($startTime->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/research'); @@ -221,11 +202,7 @@ public function testDispatchFleetColonizeAstroResearchInProgress(): void $this->assertObjectLevelOnPage($response, 'astrophysics', 3, 'Astrophysics research is not at level 3 after 10 hours of research.'); // Assert that the new planet has been created. - try { - $planetServiceFactory = resolve(PlanetServiceFactory::class); - } catch (BindingResolutionException) { - $this->fail('PlanetServiceFactory cannot be resolved from the container.'); - } + $planetServiceFactory = resolve(PlanetServiceFactory::class); $newPlanet = $planetServiceFactory->makeForCoordinate($newPlanetCoordinates); $this->assertNotNull($newPlanet, 'New planet cannot be loaded while it should have been created.'); @@ -239,10 +216,6 @@ public function testDispatchFleetColonizeReturnTripCargo(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 1 colony ship and 5 small cargos. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'colony_ship', 1); @@ -250,8 +223,8 @@ public function testDispatchFleetColonizeReturnTripCargo(): void // Send fleet to an empty planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 3); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 3); $newPlanetCoordinates = $this->sendMissionToEmptyPosition($unitCollection, new Resources(400, 400, 0, 0)); // Assert that the cargo ships have been sent. @@ -260,7 +233,7 @@ public function testDispatchFleetColonizeReturnTripCargo(): void $this->assertObjectLevelOnPage($response, 'small_cargo', 2); // Increase time by 10 hours to ensure the arrival and return missions are done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. // Note: we only make one request here, as the arrival and return missions should be processed in the same request @@ -269,11 +242,7 @@ public function testDispatchFleetColonizeReturnTripCargo(): void $response->assertStatus(200); // Assert that the new planet has been created. - try { - $planetServiceFactory = resolve(PlanetServiceFactory::class); - } catch (BindingResolutionException) { - $this->fail('PlanetServiceFactory cannot be resolved from the container.'); - } + $planetServiceFactory = resolve(PlanetServiceFactory::class); $newPlanet = $planetServiceFactory->makeForCoordinate($newPlanetCoordinates); $this->assertNotNull($newPlanet, 'New planet cannot be loaded while it should have been created.'); @@ -291,10 +260,6 @@ public function testDispatchFleetColonizeReturnTripProcessSingleRequest(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 1 colony ship and 5 small cargos. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'colony_ship', 1); @@ -302,12 +267,12 @@ public function testDispatchFleetColonizeReturnTripProcessSingleRequest(): void // Send fleet to an empty planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 3); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 3); $this->sendMissionToEmptyPosition($unitCollection, new Resources(400, 400, 0, 0)); // Increase time by 10 hours to ensure the arrival and return missions are done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Reload the application to ensure all caches are cleared and changed units are reflected. $this->reloadApplication(); @@ -334,18 +299,14 @@ public function testDispatchFleetRecallMission(): void // Add resources for test. $this->planetAddResources(new Resources(5000, 5000, 0, 0)); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships and 1 colony ship on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'colony_ship', 1); $this->assertObjectLevelOnPage($response, 'small_cargo', 5); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 5); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('colony_ship'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('colony_ship'), 1); $emptyPositionCoordinate = $this->sendMissionToEmptyPosition($unitCollection, new Resources(5000, 5000, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -354,8 +315,8 @@ public function testDispatchFleetRecallMission(): void $fleetMissionId = $fleetMission->id; // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + $fleetParentTime = Carbon::getTestNow()->addMinute(); + $this->travelTo($fleetParentTime); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -380,12 +341,12 @@ public function testDispatchFleetRecallMission(): void $fleetMissionId = $fleetMission->id; $fleetMission = $fleetMissionService->getFleetMissionById($fleetMissionId, false); - // Assert that the return trip arrival time is exactly 1 minute after the cancelation time. + // Assert that the return trip arrival time is exactly 1 minute after the cancellation time. // Because the return trip should take exactly as long as the original trip has traveled until it was canceled. $this->assertTrue($fleetMission->time_arrival == $fleetParentTime->addSeconds(60)->timestamp, 'Return trip duration is not the same as the original mission has been active.'); // Advance time by amount it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($fleetMission->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($fleetMission->time_arrival)); // Do a request to trigger the update logic. $this->get('/overview'); diff --git a/tests/Feature/FleetDispatch/FleetDispatchDeployTest.php b/tests/Feature/FleetDispatch/FleetDispatchDeployTest.php index 141cc538..e7ce7d3f 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchDeployTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchDeployTest.php @@ -6,6 +6,7 @@ use OGame\GameObjects\Models\Units\UnitCollection; use OGame\Models\Resources; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use OGame\Services\SettingsService; use Tests\FleetDispatchTestCase; @@ -73,7 +74,7 @@ public function testFleetCheckToOwnPlanetSuccess(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToSecondPlanet($unitCollection, true); } @@ -84,7 +85,7 @@ public function testFleetCheckToForeignPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToOtherPlayer($unitCollection, false); } @@ -95,7 +96,7 @@ public function testFleetCheckToEmptyPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToEmptyPosition($unitCollection, false); } @@ -103,20 +104,16 @@ public function testDispatchFleetWithoutResources(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to the second planet of the test user WITHOUT resources. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(0, 0, 0, 0)); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -149,7 +146,7 @@ public function testDispatchFleetDeductUnits(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); $response = $this->get('/shipyard'); @@ -170,7 +167,7 @@ public function testDispatchFleetDeductResources(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); $response = $this->get('/shipyard'); @@ -190,7 +187,7 @@ public function testDispatchFleetDeductTooMuchResources(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(4500, 100, 0, 0), 500); } @@ -204,7 +201,7 @@ public function testDispatchFleetDeductTooMuchUnits(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 10); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 10); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0), 500); } @@ -215,17 +212,13 @@ public function testDispatchFleetNoReturnTrip(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'small_cargo', 5, 'Small Cargo ships are not at 5 units at beginning of test.'); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -238,8 +231,7 @@ public function testDispatchFleetNoReturnTrip(): void // Set time to fleet mission duration + 30 seconds (we do 30 instead of 1 second to test later if the return trip start and endtime work as expected // and are calculated based on the arrival time instead of the time the job got processed). - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 30); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 30)->seconds(); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); @@ -268,13 +260,9 @@ public function testDispatchFleetReturnNotShown(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); // The eventbox should only show 1 mission (the parent). @@ -304,17 +292,13 @@ public function testDispatchFleetRecallMission(): void // Add resources for test. $this->planetAddResources(new Resources(5000, 5000, 0, 0)); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'small_cargo', 5, 'Small Cargo ships are not at 5 units at beginning of test.'); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 5); $this->sendMissionToSecondPlanet($unitCollection, new Resources(5000, 5000, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -322,9 +306,9 @@ public function testDispatchFleetRecallMission(): void $fleetMission = $fleetMissionService->getActiveFleetMissionsForCurrentPlayer()->first(); $fleetMissionId = $fleetMission->id; - // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + // Advance time by 1 minute. + $fleetParentTime = Carbon::getTestNow()->addSeconds(60); + $this->travelTo($fleetParentTime); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -349,7 +333,7 @@ public function testDispatchFleetRecallMission(): void $fleetMissionId = $fleetMission->id; $fleetMission = $fleetMissionService->getFleetMissionById($fleetMissionId, false); - // Assert that the return trip arrival time is exactly 1 minute after the cancelation time. + // Assert that the return trip arrival time is exactly 1 minute after the cancellation time. // Because the return trip should take exactly as long as the original trip has traveled until it was canceled. $this->assertTrue($fleetMission->time_arrival == $fleetParentTime->addSeconds(60)->timestamp, 'Return trip duration is not the same as the original mission has been active.'); @@ -357,7 +341,7 @@ public function testDispatchFleetRecallMission(): void $this->playerSetAllMessagesRead(); // Advance time by amount of minutes it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($fleetMission->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($fleetMission->time_arrival)); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -384,17 +368,13 @@ public function testDispatchFleetRecallMissionTwiceError(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'small_cargo', 5, 'Small Cargo ships are not at 5 units at beginning of test.'); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -403,8 +383,7 @@ public function testDispatchFleetRecallMissionTwiceError(): void $fleetMissionId = $fleetMission->id; // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + $this->travel(1)->minutes(); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ diff --git a/tests/Feature/FleetDispatch/FleetDispatchEspionageTest.php b/tests/Feature/FleetDispatch/FleetDispatchEspionageTest.php index c6bfe78f..7a7c1845 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchEspionageTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchEspionageTest.php @@ -6,9 +6,11 @@ use Illuminate\Support\Carbon; use OGame\GameObjects\Models\Units\UnitCollection; use OGame\Models\EspionageReport; +use OGame\Models\Planet; use OGame\Models\Resources; use OGame\Services\DebrisFieldService; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use Tests\FleetDispatchTestCase; /** @@ -57,7 +59,7 @@ public function testFleetCheckToOwnPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $this->fleetCheckToSecondPlanet($unitCollection, false); } @@ -68,7 +70,7 @@ public function testFleetCheckToForeignPlanetSuccess(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $this->fleetCheckToOtherPlayer($unitCollection, true); } @@ -79,7 +81,7 @@ public function testFleetCheckToEmptyPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $this->fleetCheckToEmptyPosition($unitCollection, false); } @@ -87,20 +89,16 @@ public function testDispatchFleetEspionageReport(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -123,17 +121,17 @@ public function testDispatchFleetUpdatePlanet(): void // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Get current updated timestamp of the target planet. - $foreignPlanetUpdatedAt = $foreignPlanet->getUpdatedAt(); + $foreignPlanetUpdatedAtBefore = $foreignPlanet->getUpdatedAt(); // Increase time by 10 hours from the foreign planet's last update time to ensure the mission is done // and time has passed since the last update. This regardless of whether other tests have affected the // foreign planet before and potentially mutated time themselves as well. - $missionCompletionTime = $foreignPlanetUpdatedAt->copy()->addHours(10); - Carbon::setTestNow($missionCompletionTime); + $missionCompletionTime = $foreignPlanetUpdatedAtBefore->copy()->addHours(10); + $this->travelTo($missionCompletionTime); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -144,7 +142,7 @@ public function testDispatchFleetUpdatePlanet(): void $foreignPlanet->reloadPlanet(); // Assert that target planet has been updated. - $this->assertNotEquals($foreignPlanet->getUpdatedAt()->timestamp, $foreignPlanetUpdatedAt->timestamp, 'Target planet was not updated after espionage mission has arrived. Check target planet update logic on mission arrival.'); + $this->assertNotEquals($foreignPlanet->getUpdatedAt()->timestamp, $foreignPlanetUpdatedAtBefore->timestamp, 'Target planet was not updated after espionage mission has arrived. Check target planet update logic on mission arrival.'); // Assert that the updated resources are visible in the espionage report. // Get the latest espionage report message from the database. @@ -159,9 +157,13 @@ public function testDispatchFleetDebrisEspionageReport(): void { $this->basicSetup(); + // Mutate all planet time_last_update to 1st jan via Eloquent query + // to simulate error with this test. + Planet::query()->update(['time_last_update' => '1704103200']); + // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Add debris field to the foreign planet. @@ -179,13 +181,13 @@ public function testDispatchFleetDebrisEspionageReport(): void $debrisField->save(); // Get current updated timestamp of the target planet. - $foreignPlanetUpdatedAt = $foreignPlanet->getUpdatedAt(); + $foreignPlanetUpdatedAtBefore = $foreignPlanet->getUpdatedAt(); // Increase time by 10 hours from the foreign planet's last update time to ensure the mission is done // and time has passed since the last update. This regardless of whether other tests have affected the // foreign planet before and potentially mutated time themselves as well. - $missionCompletionTime = $foreignPlanetUpdatedAt->copy()->addHours(10); - Carbon::setTestNow($missionCompletionTime); + $missionCompletionTime = $foreignPlanetUpdatedAtBefore->copy()->addHours(10); + $this->travelTo($missionCompletionTime); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -196,7 +198,7 @@ public function testDispatchFleetDebrisEspionageReport(): void $foreignPlanet->reloadPlanet(); // Assert that target planet has been updated. - $this->assertNotEquals($foreignPlanet->getUpdatedAt()->timestamp, $foreignPlanetUpdatedAt->timestamp, 'Target planet was not updated after espionage mission has arrived. Check target planet update logic on mission arrival.'); + $this->assertNotEquals($foreignPlanet->getUpdatedAt()->timestamp, $foreignPlanetUpdatedAtBefore->timestamp, 'Target planet was not updated after espionage mission has arrived. Check target planet update logic on mission arrival.'); // Assert that the updated resources are visible in the espionage report. // Get the latest espionage report message from the database. @@ -216,17 +218,13 @@ public function testDispatchFleetReturnTrip(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'espionage_probe', 5, 'Espionage probe are not at 5 units at beginning of test.'); // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -238,8 +236,7 @@ public function testDispatchFleetReturnTrip(): void $fleetMissionDuration = $fleetMissionService->calculateFleetMissionDuration($this->planetService, $foreignPlanet->getPlanetCoordinates(), $unitCollection); // Set time to fleet mission duration + 1 second. - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 1); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 1)->seconds(); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); @@ -269,13 +266,9 @@ public function testDispatchFleetReturnShown(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // The eventbox should only show 1 mission (the parent). @@ -311,17 +304,13 @@ public function testDispatchFleetRecallMission(): void // Add resources for test. $this->planetAddResources(new Resources(5000, 5000, 0, 0)); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'espionage_probe', 5, 'Espionage probes are not at 5 units at beginning of test.'); // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -330,8 +319,8 @@ public function testDispatchFleetRecallMission(): void $fleetMissionId = $fleetMission->id; // Advance time by 5 seconds. - $fleetParentTime = $startTime->copy()->addSeconds(5); - Carbon::setTestNow($fleetParentTime); + $fleetParentTime = Carbon::getTestNow()->addSeconds(5); + $this->travelTo($fleetParentTime); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -364,7 +353,7 @@ public function testDispatchFleetRecallMission(): void $this->playerSetAllMessagesRead(); // Advance time by amount of minutes it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($fleetMission->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($fleetMission->time_arrival)); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -389,17 +378,13 @@ public function testDispatchFleetRecallMissionTwiceError(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'espionage_probe', 5, 'Espionage probe ships are not at 5 units at beginning of test.'); // Send fleet to a nearby foreign planet. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('espionage_probe'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('espionage_probe'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -407,9 +392,8 @@ public function testDispatchFleetRecallMissionTwiceError(): void $fleetMission = $fleetMissionService->getActiveFleetMissionsForCurrentPlayer()->first(); $fleetMissionId = $fleetMission->id; - // Advance time by 10 seconds - $fleetParentTime = $startTime->copy()->addSeconds(5); - Carbon::setTestNow($fleetParentTime); + // Advance time by 5 seconds + $this->travel(5)->seconds(); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ diff --git a/tests/Feature/FleetDispatch/FleetDispatchGenericTest.php b/tests/Feature/FleetDispatch/FleetDispatchGenericTest.php index 22866194..fb1a7a92 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchGenericTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchGenericTest.php @@ -6,6 +6,7 @@ use OGame\GameObjects\Models\Units\UnitCollection; use OGame\Models\Resources; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use OGame\Services\SettingsService; use Tests\FleetDispatchTestCase; @@ -98,7 +99,7 @@ public function testFleetDurationCalculation(): void // Create a unit collection with 5 small cargos. $units = new UnitCollection(); - $units->addUnit($this->planetService->objects->getShipObjectByMachineName('small_cargo'), 5); + $units->addUnit(ObjectService::getShipObjectByMachineName('small_cargo'), 5); // Should take 2h:18m:05s to travel to the target planet 1 system away with base speed of 5000. $this->assertEquals(8285, $fleetMissionService->calculateFleetMissionDuration($this->planetService, $targetPlanetCoords, $units)); diff --git a/tests/Feature/FleetDispatch/FleetDispatchRecycleTest.php b/tests/Feature/FleetDispatch/FleetDispatchRecycleTest.php index f69e674c..b90037ff 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchRecycleTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchRecycleTest.php @@ -7,6 +7,7 @@ use OGame\Models\Resources; use OGame\Services\DebrisFieldService; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use Tests\FleetDispatchTestCase; /** @@ -70,7 +71,7 @@ public function testFleetCheckToSecondPlanetSuccess(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 1); $this->fleetCheckToSecondPlanetDebrisField($unitCollection, true); } @@ -81,7 +82,7 @@ public function testFleetCheckToSecondPlanetWithoutRecyclerError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToSecondPlanetDebrisField($unitCollection, false); } @@ -92,7 +93,7 @@ public function testFleetCheckToFirstPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 1); $this->fleetCheckToFirstPlanetDebrisField($unitCollection, false); } @@ -109,7 +110,7 @@ public function testDispatchFleetDeductUnits(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 1); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(0, 0, 0, 0)); $response = $this->get('/shipyard'); @@ -123,17 +124,13 @@ public function testDispatchFleetReturnTrip(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 recyclers. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'recycler', 5, 'Recycler ships are not at 5 units at beginning of test.'); // Send fleet to the debris field located at second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 1); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -146,8 +143,7 @@ public function testDispatchFleetReturnTrip(): void // Set time to fleet mission duration + 30 seconds (we do 30 instead of 1 second to test later if the return trip start and endtime work as expected // and are calculated based on the arrival time instead of the time the job got processed). - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration)->seconds(); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); @@ -181,8 +177,7 @@ public function testDispatchFleetReturnTrip(): void // Advance time to the return trip arrival. $returnTripDuration = $returnMission->time_arrival - $returnMission->time_departure; - $fleetReturnTime = $fleetParentTime->copy()->addSeconds($returnTripDuration + 1); - Carbon::setTestNow($fleetReturnTime); + $this->travel($returnTripDuration + 1)->seconds(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -206,13 +201,9 @@ public function testDispatchFleetReturnShown(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 1); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(100, 100, 0, 0)); // The eventbox should only show 1 mission (the parent). @@ -240,10 +231,6 @@ public function testDispatchFleetLargeDebrisField(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Make sure the debris field has a lot of resources. $debrisFieldService = resolve(DebrisFieldService::class); $debrisFieldService->loadForCoordinates($this->secondPlanetService->getPlanetCoordinates()); @@ -254,7 +241,7 @@ public function testDispatchFleetLargeDebrisField(): void // Send fleet to the debris field located at second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 5); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -267,8 +254,7 @@ public function testDispatchFleetLargeDebrisField(): void // Set time to fleet mission duration + 30 seconds (we do 30 instead of 1 second to test later if the return trip start and endtime work as expected // and are calculated based on the arrival time instead of the time the job got processed). - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration)->seconds(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -306,10 +292,6 @@ public function testDispatchFleetEmptiedDebrisField(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Make sure the debris field contains resources when sending the fleet. $debrisFieldService = resolve(DebrisFieldService::class); $debrisFieldService->loadOrCreateForCoordinates($this->secondPlanetService->getPlanetCoordinates()); @@ -318,7 +300,7 @@ public function testDispatchFleetEmptiedDebrisField(): void // Send fleet to the debris field located at second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 5); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(0, 0, 0, 0)); // Now delete the resources from the debris field to simulate another mission that has harvested it. @@ -334,8 +316,7 @@ public function testDispatchFleetEmptiedDebrisField(): void // Set time to fleet mission duration + 30 seconds (we do 30 instead of 1 second to test later if the return trip start and endtime work as expected // and are calculated based on the arrival time instead of the time the job got processed). - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 30)->seconds(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -366,13 +347,9 @@ public function testDispatchFleetRecallMission(): void // Add resources for test. $this->planetAddResources(new Resources(5000, 5000, 0, 0)); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to the second planet debris field of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 5); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(0, 0, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -382,8 +359,8 @@ public function testDispatchFleetRecallMission(): void $fleetMissionId = $fleetMission->id; // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + $fleetParentTime = Carbon::getTestNow()->addMinute(); + $this->travelTo($fleetParentTime); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -415,7 +392,7 @@ public function testDispatchFleetRecallMission(): void $this->assertTrue($fleetMission->time_arrival == $fleetParentTime->addSeconds(60)->timestamp, 'Return trip duration is not the same as the original mission has been active.'); // Advance time by amount of minutes it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($fleetMission->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($fleetMission->time_arrival)); // Do a request to trigger the update logic. $this->get('/overview'); @@ -436,13 +413,9 @@ public function testDispatchFleetRecallMissionTwiceError(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('recycler'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('recycler'), 1); $this->sendMissionToSecondPlanetDebrisField($unitCollection, new Resources(100, 100, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -452,8 +425,7 @@ public function testDispatchFleetRecallMissionTwiceError(): void $fleetMissionId = $fleetMission->id; // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + $this->travel(1)->minutes(); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ diff --git a/tests/Feature/FleetDispatch/FleetDispatchTransportTest.php b/tests/Feature/FleetDispatch/FleetDispatchTransportTest.php index 236c45fe..19ed9b09 100644 --- a/tests/Feature/FleetDispatch/FleetDispatchTransportTest.php +++ b/tests/Feature/FleetDispatch/FleetDispatchTransportTest.php @@ -2,11 +2,11 @@ namespace Tests\Feature\FleetDispatch; -use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Support\Carbon; use OGame\GameObjects\Models\Units\UnitCollection; use OGame\Models\Resources; use OGame\Services\FleetMissionService; +use OGame\Services\ObjectService; use Tests\FleetDispatchTestCase; /** @@ -69,7 +69,7 @@ public function testFleetCheckToOwnPlanetSuccess(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToSecondPlanet($unitCollection, true); } @@ -80,7 +80,7 @@ public function testFleetCheckToForeignPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToOtherPlayer($unitCollection, false); } @@ -91,7 +91,7 @@ public function testFleetCheckToEmptyPlanetError(): void { $this->basicSetup(); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->fleetCheckToEmptyPosition($unitCollection, false); } @@ -99,17 +99,13 @@ public function testDispatchFleetToOtherPlayer(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to a planet of another player. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $foreignPlanet = $this->sendMissionToOtherPlayer($unitCollection, new Resources(100, 0, 0, 0)); // Increase time by 10 hours to ensure the mission is done. - Carbon::setTestNow($startTime->copy()->addHours(10)); + $this->travel(10)->hours(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -135,7 +131,7 @@ public function testDispatchFleetDeductUnits(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); $response = $this->get('/shipyard'); @@ -156,7 +152,7 @@ public function testDispatchFleetDeductResources(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); $response = $this->get('/shipyard'); @@ -176,7 +172,7 @@ public function testDispatchFleetDeductTooMuchResources(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(4500, 100, 0, 0), 500); } @@ -190,7 +186,7 @@ public function testDispatchFleetDeductTooMuchUnits(): void // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 10); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 10); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0), 500); } @@ -201,17 +197,13 @@ public function testDispatchFleetReturnTrip(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'small_cargo', 5, 'Small Cargo ships are not at 5 units at beginning of test.'); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); // Get just dispatched fleet mission ID from database. @@ -224,8 +216,7 @@ public function testDispatchFleetReturnTrip(): void // Set time to fleet mission duration + 30 seconds (we do 30 instead of 1 second to test later if the return trip start and endtime work as expected // and are calculated based on the arrival time instead of the time the job got processed). - $fleetParentTime = $startTime->copy()->addSeconds($fleetMissionDuration + 30); - Carbon::setTestNow($fleetParentTime); + $this->travel($fleetMissionDuration + 30)->seconds(); // Set all messages as read to avoid unread messages count in the overview. $this->playerSetAllMessagesRead(); @@ -248,9 +239,7 @@ public function testDispatchFleetReturnTrip(): void // Advance time to the return trip arrival. $returnTripDuration = $activeMissions->first()->time_arrival - $activeMissions->first()->time_departure; - - $fleetReturnTime = $fleetParentTime->copy()->addSeconds($returnTripDuration + 1); - Carbon::setTestNow($fleetReturnTime); + $this->travel($returnTripDuration + 1)->seconds(); // Do a request to trigger the update logic. $response = $this->get('/overview'); @@ -274,13 +263,9 @@ public function testDispatchFleetReturnShown(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); // The eventbox should only show 1 mission (the parent). @@ -310,32 +295,24 @@ public function testDispatchFleetRecallMission(): void // Add resources for test. $this->planetAddResources(new Resources(5000, 5000, 0, 0)); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'small_cargo', 5, 'Small Cargo ships are not at 5 units at beginning of test.'); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 5); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 5); $this->sendMissionToSecondPlanet($unitCollection, new Resources(5000, 5000, 0, 0)); // Get just dispatched fleet mission ID from database. - try { - $fleetMissionService = resolve(FleetMissionService::class, ['player' => $this->planetService->getPlayer()]); - } catch (BindingResolutionException $e) { - $this->fail('Failed to resolve FleetMissionService in testDispatchFleetRecallMission.'); - } + $fleetMissionService = resolve(FleetMissionService::class, ['player' => $this->planetService->getPlayer()]); $fleetMission = $fleetMissionService->getActiveFleetMissionsForCurrentPlayer()->first(); $fleetMissionId = $fleetMission->id; // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + $fleetParentTime = Carbon::getTestNow()->addMinute(); + $this->travelTo($fleetParentTime); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ @@ -356,11 +333,7 @@ public function testDispatchFleetRecallMission(): void $response->assertJsonFragment(['friendly' => 1]); $response->assertJsonFragment(['eventText' => $this->missionName . ' (R)']); - try { - $fleetMissionService = resolve(FleetMissionService::class, ['player' => $this->planetService->getPlayer()]); - } catch (BindingResolutionException $e) { - $this->fail('Failed to resolve FleetMissionService in testDispatchFleetRecallMission.'); - } + $fleetMissionService = resolve(FleetMissionService::class, ['player' => $this->planetService->getPlayer()]); $fleetMission = $fleetMissionService->getActiveFleetMissionsForCurrentPlayer()->first(); $fleetMissionId = $fleetMission->id; @@ -371,7 +344,7 @@ public function testDispatchFleetRecallMission(): void $this->assertTrue($fleetMission->time_arrival == $fleetParentTime->addSeconds(60)->timestamp, 'Return trip duration is not the same as the original mission has been active.'); // Advance time by amount of minutes it takes for the return trip to arrive. - Carbon::setTestNow(Carbon::createFromTimestamp($fleetMission->time_arrival)); + $this->travelTo(Carbon::createFromTimestamp($fleetMission->time_arrival)); // Do a request to trigger the update logic. $this->get('/overview'); @@ -395,32 +368,23 @@ public function testDispatchFleetRecallMissionTwiceError(): void { $this->basicSetup(); - // Set time to static time 2024-01-01 - $startTime = Carbon::create(2024, 1, 1, 0, 0, 0); - Carbon::setTestNow($startTime); - // Assert that we begin with 5 small cargo ships on planet. $response = $this->get('/shipyard'); $this->assertObjectLevelOnPage($response, 'small_cargo', 5, 'Small Cargo ships are not at 5 units at beginning of test.'); // Send fleet to the second planet of the test user. $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getUnitObjectByMachineName('small_cargo'), 1); + $unitCollection->addUnit(ObjectService::getUnitObjectByMachineName('small_cargo'), 1); $this->sendMissionToSecondPlanet($unitCollection, new Resources(100, 100, 0, 0)); // Get just dispatched fleet mission ID from database. - try { - $fleetMissionService = resolve(FleetMissionService::class, ['player' => $this->planetService->getPlayer()]); - } catch (BindingResolutionException $e) { - $this->fail('Failed to resolve FleetMissionService in testDispatchFleetRecallMission.'); - } + $fleetMissionService = resolve(FleetMissionService::class, ['player' => $this->planetService->getPlayer()]); $fleetMission = $fleetMissionService->getActiveFleetMissionsForCurrentPlayer()->first(); $fleetMissionId = $fleetMission->id; // Advance time by 1 minute - $fleetParentTime = $startTime->copy()->addMinutes(1); - Carbon::setTestNow($fleetParentTime); + $this->travel(1)->minutes(); // Cancel the mission $response = $this->post('/ajax/fleet/dispatch/recall-fleet', [ diff --git a/tests/Feature/GlobalGameTest.php b/tests/Feature/GlobalGameTest.php index 65e52946..d54f333f 100644 --- a/tests/Feature/GlobalGameTest.php +++ b/tests/Feature/GlobalGameTest.php @@ -16,9 +16,9 @@ public function testPageLoadOnlyUpdatesCurrentPlanet(): void $startPlanetCount = $this->planetService->getPlayer()->planets->count(); $this->assertGreaterThanOrEqual(2, $startPlanetCount); - // Set time to +1 hour so we can verify that only the current planet will be updated with the new time. + // Set time to +1 hour, so we can verify that only the current planet will be updated with the new time. $testTime = Carbon::now()->addHour(); - Carbon::setTestNow($testTime); + $this->travelTo($testTime); // Request overview page. $response = $this->get('/overview'); diff --git a/tests/Feature/Http200Test.php b/tests/Feature/Http200Test.php index 6777a612..1bbd614f 100644 --- a/tests/Feature/Http200Test.php +++ b/tests/Feature/Http200Test.php @@ -59,10 +59,7 @@ public function testMainPages(): void */ public function testAjaxResources(): void { - // Get all resource objects - $objectService = new ObjectService(); - - foreach ($objectService->getBuildingObjects() as $object) { + foreach (ObjectService::getBuildingObjects() as $object) { $response = $this->get('ajax/resources?technology=' . $object->id); try { @@ -81,10 +78,7 @@ public function testAjaxResources(): void */ public function testAjaxFacilities(): void { - // Get all resource objects - $objectService = new ObjectService(); - - foreach ($objectService->getStationObjects() as $object) { + foreach (ObjectService::getStationObjects() as $object) { $response = $this->get('ajax/facilities?technology=' . $object->id); try { @@ -102,10 +96,7 @@ public function testAjaxFacilities(): void */ public function testAjaxResearch(): void { - // Get all resource objects - $objectService = new ObjectService(); - - foreach ($objectService->getResearchObjects() as $object) { + foreach (ObjectService::getResearchObjects() as $object) { $response = $this->get('ajax/research?technology=' . $object->id); try { @@ -123,10 +114,7 @@ public function testAjaxResearch(): void */ public function testAjaxShipyard(): void { - // Get all resource objects - $objectService = new ObjectService(); - - foreach ($objectService->getShipObjects() as $object) { + foreach (ObjectService::getShipObjects() as $object) { $response = $this->get('ajax/shipyard?technology=' . $object->id); try { @@ -144,10 +132,7 @@ public function testAjaxShipyard(): void */ public function testAjaxDefense(): void { - // Get all resource objects - $objectService = new ObjectService(); - - foreach ($objectService->getDefenseObjects() as $object) { + foreach (ObjectService::getDefenseObjects() as $object) { $response = $this->get('ajax/defense?technology=' . $object->id); try { diff --git a/tests/Feature/PlanetAbandonTest.php b/tests/Feature/PlanetAbandonTest.php index f2ec2080..2c58e595 100644 --- a/tests/Feature/PlanetAbandonTest.php +++ b/tests/Feature/PlanetAbandonTest.php @@ -1,6 +1,6 @@ planetAddResources(new Resources(0, 10000, 5000, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build three levels of energy technology // --- @@ -36,8 +30,7 @@ public function testResearchQueueCancelMultiple(): void } // Access the build queue page to verify the buildings are in the queue - $testTime = Carbon::create(2024, 1, 1, 12, 0, 1); - Carbon::setTestNow($testTime); + $this->travel(1)->seconds(); $response = $this->get('/research'); $this->assertObjectInQueue($response, 'energy_technology', 3, 'Energy Technology level 3 is expected in build queue but cannot be found.'); @@ -50,8 +43,7 @@ public function testResearchQueueCancelMultiple(): void $this->assertObjectNotInQueue($response, 'energy_technology', 'Energy Technology is in build queue but should have been canceled.'); // Advance time by 30 minutes - $testTime = Carbon::create(2024, 1, 1, 12, 30, 0); - Carbon::setTestNow($testTime); + $this->travel(30)->minutes(); // Verify that Energy Technology is still at level 0 $response = $this->get('/research'); @@ -69,10 +61,6 @@ public function testResearchQueueCancelRefundResources(): void $this->planetAddResources(new Resources(0, 800, 400, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Verify that we begin the test with 500 metal and 500 crystal $response = $this->get('/research'); $response->assertStatus(200); @@ -102,10 +90,6 @@ public function testBuildQueueCancelSecondEntry(): void $this->planetAddResources(new Resources(0, 1600, 1600, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - $response = $this->get('/research'); $response->assertStatus(200); @@ -156,10 +140,6 @@ public function testBuildQueueCancelDifferentPlanet(): void $this->planetAddResources(new Resources(0, 1600, 1600, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - $response = $this->get('/research'); $response->assertStatus(200); @@ -241,10 +221,9 @@ public function testCancelResearchMissingRequirements(): void $number1 = (int)$cancelProductionCall[0]; $number2 = (int)$cancelProductionCall[1]; - // Check if both numbers are integers. If not, throw an exception. - if (empty($number1) || empty($number2)) { - throw new BindingResolutionException('Could not extract the building queue ID from the page.'); - } + // Assert that both numbers are integers. + $this->assertIsInt($number1); + $this->assertIsInt($number2); // Cancel Energy technology level 1, this will cancel also Impulse Drive level 1 $this->cancelResearchBuildRequest($number1, $number2); diff --git a/tests/Feature/ResearchQueueTest.php b/tests/Feature/ResearchQueueTest.php index 61a866fb..1abaab37 100644 --- a/tests/Feature/ResearchQueueTest.php +++ b/tests/Feature/ResearchQueueTest.php @@ -4,7 +4,6 @@ use Exception; use Illuminate\Contracts\Container\BindingResolutionException; -use Illuminate\Support\Carbon; use OGame\Models\Resources; use OGame\Services\SettingsService; use Tests\AccountTestCase; @@ -16,7 +15,6 @@ class ResearchQueueTest extends AccountTestCase { /** * Verify that researching energy technology works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testResearchQueueEnergyTechnology(): void @@ -29,10 +27,6 @@ public function testResearchQueueEnergyTechnology(): void $this->planetAddResources(new Resources(0, 800, 400, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to research energy technology // --- @@ -41,37 +35,36 @@ public function testResearchQueueEnergyTechnology(): void // --- // Step 2: Verify the technology is in the research queue // --- + $this->travel(1)->seconds(); + // Check if the research is in the queue and is still level 0. $response = $this->get('/research'); $response->assertStatus(200); - $this->assertObjectLevelOnPage($response, 'energy_technology', 0, 'Energy technology is not still at level 0 two seconds after build request issued.'); + $this->assertObjectLevelOnPage($response, 'energy_technology', 0, 'Energy technology is not still at level 0 immediately after build request issued.'); // --- // Step 3: Verify the research is still in the build queue 1 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 1, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->minutes(); // Check if the technology is still in the queue and is still level 0. $response = $this->get('/research'); $response->assertStatus(200); - $this->assertObjectLevelOnPage($response, 'energy_technology', 0, 'Energy technology is not still at level 0 two seconds after build request issued.'); + $this->assertObjectLevelOnPage($response, 'energy_technology', 0, 'Energy technology is not still at level 0 one minute after build request issued.'); // --- - // Step 4: Verify the research is finished 10 minute later. + // Step 4: Verify the research is finished 5 minutes later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 10, 0); - Carbon::setTestNow($testTime); + $this->travel(5)->minutes(); // Check if the technology research is finished and is now level 1. $response = $this->get('/research'); $response->assertStatus(200); - $this->assertObjectLevelOnPage($response, 'energy_technology', 1, 'Energy technology is not at level one 10 minutes after build request issued.'); + $this->assertObjectLevelOnPage($response, 'energy_technology', 1, 'Energy technology is not at level 1 ten minutes after build request issued.'); } /** * Verify that researching multiple technologies works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testResearchQueueMultiQueue(): void @@ -84,10 +77,6 @@ public function testResearchQueueMultiQueue(): void $this->planetAddResources(new Resources(0, 2400, 1200, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to research energy technology // --- @@ -105,8 +94,7 @@ public function testResearchQueueMultiQueue(): void // --- // Step 3: Verify that 1 research queue item is finished 2 minutes later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 2, 0); - Carbon::setTestNow($testTime); + $this->travel(2)->minutes(); // Check if one of the research items is finished and is now level 1. $this->planetService->getPlayer()->updateResearchQueue(); @@ -117,8 +105,7 @@ public function testResearchQueueMultiQueue(): void // --- // Step 3: Verify that both research queue items are finished 30 minutes later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 30, 0); - Carbon::setTestNow($testTime); + $this->travel(30)->minutes(); // Check if the research is finished and is now level 1. $response = $this->get('/research'); @@ -136,12 +123,6 @@ public function testResearchQueueCancelRefundResources(): void $this->planetAddResources(new Resources(0, 800, 400, 0)); $this->planetSetObjectLevel('research_lab', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - - // --------- - // Verify that we begin the test with expected resources. $response = $this->get('/research'); $response->assertStatus(200); @@ -205,10 +186,6 @@ public function testResearchProductionTime(): void */ public function testResearchLabRequirement(): void { - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Add required resources for research to planet $this->planetAddResources(new Resources(5000, 5000, 5000, 0)); @@ -226,14 +203,11 @@ public function testResearchLabRequirement(): void $this->assertRequirementsNotMet($response, 'energy_technology', 'Energy Technology research requirements not met.'); // Verify that Energy Technology can be added to research queue 2 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 2, 0); - Carbon::setTestNow($testTime); - + $this->travel(2)->minutes(); $this->addResearchBuildRequest('energy_technology'); // Verify the research is finished 2 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 4, 0); - Carbon::setTestNow($testTime); + $this->travel(2)->minutes(); $response = $this->get('/research'); $response->assertStatus(200); diff --git a/tests/Feature/TechtreeTest.php b/tests/Feature/TechtreeTest.php index 8580f6c3..71bd4537 100644 --- a/tests/Feature/TechtreeTest.php +++ b/tests/Feature/TechtreeTest.php @@ -1,6 +1,6 @@ getObjects() as $object) { + foreach (ObjectService::getObjects() as $object) { $response = $this->get('ajax/techtree?tab=2&object_id=' . $object->id); try { @@ -37,7 +35,7 @@ public function testTechtreeApplicationsPopupsHttp200(): void // Get all objects $objectService = new ObjectService(); - foreach ($objectService->getObjects() as $object) { + foreach (ObjectService::getObjects() as $object) { $response = $this->get('ajax/techtree?tab=4&object_id=' . $object->id); try { @@ -54,8 +52,7 @@ public function testTechtreeApplicationsPopupsHttp200(): void public function testTechtreeApplicationsPopupsLogic(): void { // User/planet without any levels/prerequisites. - $objectService = new ObjectService(); - $object = $objectService->getObjectByMachineName('laser_technology'); + $object = ObjectService::getObjectByMachineName('laser_technology'); $response = $this->get('ajax/techtree?tab=4&object_id=' . $object->id); // Assert that no prerequisites are met for any of the applications. @@ -99,9 +96,7 @@ public function testTechinfoPropertiesDefenseHiddenProperties(): void { // Get defense specific objects to test. - $objectService = new ObjectService(); - - $defenseObjects = $objectService->getDefenseObjects(); + $defenseObjects = ObjectService::getDefenseObjects(); foreach ($defenseObjects as $defenseObject) { $response = $this->get('ajax/techtree?tab=2&object_id=' . $defenseObject->id); @@ -121,10 +116,8 @@ public function testTechinfoPropertiesDefenseHiddenProperties(): void */ public function testTechinfoPropertiesNoneDefenseShowsHiddenDefenseProperties(): void { - // Get non defence specific objects to test. - $objectService = new ObjectService(); - - $civilShipObjects = $objectService->getCivilShipObjects(); + // Get non defense specific objects to test. + $civilShipObjects = ObjectService::getCivilShipObjects(); foreach ($civilShipObjects as $nonDefenseObject) { $response = $this->get('ajax/techtree?tab=2&object_id=' . $nonDefenseObject->id); diff --git a/tests/Feature/UnitQueueTest.php b/tests/Feature/UnitQueueTest.php index bdb07bab..9d9c8ef5 100644 --- a/tests/Feature/UnitQueueTest.php +++ b/tests/Feature/UnitQueueTest.php @@ -3,8 +3,6 @@ namespace Tests\Feature; use Exception; -use Illuminate\Contracts\Container\BindingResolutionException; -use Illuminate\Support\Carbon; use OGame\Models\Resources; use OGame\Services\SettingsService; use Tests\AccountTestCase; @@ -18,7 +16,6 @@ class UnitQueueTest extends AccountTestCase * Prepare the planet for the test, so it has the required buildings and research. * * @return void - * @throws BindingResolutionException */ private function basicSetup(): void { @@ -35,7 +32,6 @@ private function basicSetup(): void /** * Verify that building more than one of a ship works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueShips(): void @@ -44,10 +40,6 @@ public function testUnitQueueShips(): void // Add resources to planet that test requires. $this->planetAddResources(new Resources(30000, 10000, 0, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 10 light fighters // --- @@ -63,28 +55,25 @@ public function testUnitQueueShips(): void // --- // Step 3: Verify the ships are still in the build queue 1 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 1, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); $this->assertObjectLevelOnPage($response, 'light_fighter', 0, 'Light Fighter is not at 0 units 1m after build request issued.'); // --- - // Step 4: Verify that some ships are finished 30 minute later. + // Step 4: Verify that some ships are finished 20 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 20, 0); - Carbon::setTestNow($testTime); + $this->travel(20)->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); $this->assertObjectLevelOnPage($response, 'light_fighter', 3, 'Light Fighter build job has not completed exactly 3 units 15m after build request issued.'); // --- - // Step 5: Verify that ALL ships are finished 15 minute later. + // Step 5: Verify that ALL ships are finished 14 hours later. // --- - $testTime = Carbon::create(2024, 1, 1, 14, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(14)->hours(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -93,7 +82,6 @@ public function testUnitQueueShips(): void /** * Verify that building large amount of ships with default shipyard level works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueLargeAmountLowShipyardLevel(): void @@ -103,10 +91,6 @@ public function testUnitQueueLargeAmountLowShipyardLevel(): void // Add resources to planet that test requires. $this->planetAddResources(new Resources(30000000, 10000000, 0, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 1k light fighters // --- @@ -120,10 +104,8 @@ public function testUnitQueueLargeAmountLowShipyardLevel(): void $this->assertObjectLevelOnPage($response, 'light_fighter', 0, 'Light Fighter is not at 0 units directly after build request issued.'); // Increase time by random 1-15 minute intervals 20 times in total to simulate partial updates. - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); for ($i = 0; $i < 50; $i++) { - $testTime = $testTime->addMinutes(rand(1, 15)); - Carbon::setTestNow($testTime); + $this->travel(rand(1, 15))->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -132,8 +114,7 @@ public function testUnitQueueLargeAmountLowShipyardLevel(): void // --- // Step 4: Verify that all ships are finished 2 weeks later. // --- - $testTime = Carbon::create(2024, 1, 14, 0, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(2)->weeks(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -142,7 +123,6 @@ public function testUnitQueueLargeAmountLowShipyardLevel(): void /** * Verify that building large amount of ships with high shipyard level works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueLargeAmountHighShipyardLevel(): void @@ -156,10 +136,6 @@ public function testUnitQueueLargeAmountHighShipyardLevel(): void // Add resources to planet that test requires. $this->planetAddResources(new Resources(30000000, 10000000, 0, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 10k light fighters // --- @@ -174,7 +150,7 @@ public function testUnitQueueLargeAmountHighShipyardLevel(): void // Increase time by random 1-15 second intervals 20 times in total to simulate partial updates. for ($i = 0; $i < 20; $i++) { - Carbon::setTestNow($testTime->addSeconds(rand(1, 15))); + $this->travel(rand(1, 15))->seconds(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -182,14 +158,14 @@ public function testUnitQueueLargeAmountHighShipyardLevel(): void // Do it again but now with just millisecond differences. for ($i = 0; $i < 20; $i++) { - Carbon::setTestNow($testTime->addMilliseconds(rand(400, 999))); + $this->travel(rand(400, 999))->milliseconds(); $response = $this->get('/shipyard'); $response->assertStatus(200); } // Increase time by 10 hours to simulate the final update. - Carbon::setTestNow($testTime->addHours(10)); + $this->travel(10)->hours(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -198,7 +174,6 @@ public function testUnitQueueLargeAmountHighShipyardLevel(): void /** * Verify that adding three different build jobs and waiting for them all to complete works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueShipsMultiQueues(): void @@ -211,10 +186,6 @@ public function testUnitQueueShipsMultiQueues(): void // For 10 solar satellites $this->planetAddResources(new Resources(0, 20000, 50000, 0)); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 3 light fighters, 10 solar sats, and then 2 light fighters // --- @@ -231,10 +202,9 @@ public function testUnitQueueShipsMultiQueues(): void $this->assertObjectLevelOnPage($response, 'solar_satellite', 0, 'Solar Satellite is not at 0 units directly after build request issued.'); // --- - // Step 3: Verify that the light fighters and partial solar satellites are finished 30 minute later. + // Step 3: Verify that the light fighters and partial solar satellites are finished 25 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 25, 0); - Carbon::setTestNow($testTime); + $this->travel(25)->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -242,10 +212,9 @@ public function testUnitQueueShipsMultiQueues(): void $this->assertObjectLevelOnPage($response, 'solar_satellite', 2, 'Solar Satellite is not at 2 units 25m after build request issued.'); // --- - // Step 5: Verify that ALL ships are finished 30 minute later. + // Step 5: Verify that ALL ships are finished 35 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 14, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(35)->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -255,7 +224,6 @@ public function testUnitQueueShipsMultiQueues(): void /** * Verify that building more than one of a defense unit works as expected. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueDefense(): void @@ -266,10 +234,6 @@ public function testUnitQueueDefense(): void $this->planetSetObjectLevel('robot_factory', 2); $this->planetSetObjectLevel('shipyard', 1); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 10 light fighters // --- @@ -285,8 +249,7 @@ public function testUnitQueueDefense(): void // --- // Step 3: Verify the defense units are still in the build queue 1 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 1, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->minutes(); $response = $this->get('/defense'); $response->assertStatus(200); @@ -295,8 +258,7 @@ public function testUnitQueueDefense(): void // --- // Step 4: Verify that some defense units are finished 10 minute later. // --- - $testTime = Carbon::create(2024, 1, 1, 12, 10, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); $response = $this->get('/defense'); $response->assertStatus(200); @@ -305,8 +267,7 @@ public function testUnitQueueDefense(): void // --- // Step 5: Verify that ALL defense units are finished 1h later. // --- - $testTime = Carbon::create(2024, 1, 1, 13, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->hours(); $response = $this->get('/defense'); $response->assertStatus(200); @@ -315,17 +276,12 @@ public function testUnitQueueDefense(): void /** * Verify that building ships deducts correct amount of resources from planet. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueDeductResources(): void { $this->basicSetup(); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 10 light fighters // --- @@ -334,8 +290,7 @@ public function testUnitQueueDeductResources(): void // --- // Step 2: Verify that nothing has been built as there were not enough resources. // --- - $testTime = Carbon::create(2024, 1, 1, 13, 0, 0); - Carbon::setTestNow($testTime); + $this->travel(1)->hours(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -344,17 +299,11 @@ public function testUnitQueueDeductResources(): void /** * Verify that building ships without resources fails. - * @throws BindingResolutionException * @throws Exception */ public function testUnitQueueInsufficientResources(): void { $this->basicSetup(); - - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - $this->planetAddResources(new Resources(30000, 10000, 0, 0)); // Assert that we begin with 30500 metal and 10500 crystal. @@ -380,10 +329,6 @@ public function testUnitQueueInsufficientResources(): void */ public function testUnitQueueShipyardRequirement(): void { - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Add required resources to planet $this->planetAddResources(new Resources(5000, 5000, 5000, 0)); @@ -403,14 +348,11 @@ public function testUnitQueueShipyardRequirement(): void $this->assertRequirementsNotMet($response, 'solar_satellite', 'Solar Satellite build requirements are met.'); // Verify that Solar Satellite can be added to unit queue 10 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 10, 0); - Carbon::setTestNow($testTime); - + $this->travel(10)->minutes(); $this->addShipyardBuildRequest('solar_satellite', 1); // Verify the building is finished 10 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 20, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -423,10 +365,6 @@ public function testUnitQueueShipyardRequirement(): void */ public function testUnitQueueResearchRequirement(): void { - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // Add required resources to planet $this->planetAddResources(new Resources(5000, 5000, 5000, 0)); @@ -442,8 +380,7 @@ public function testUnitQueueResearchRequirement(): void $this->addFacilitiesBuildRequest('research_lab'); // Verify the building is finished 10 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 10, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); $response = $this->get('/facilities'); $response->assertStatus(200); @@ -464,8 +401,7 @@ public function testUnitQueueResearchRequirement(): void $this->assertRequirementsNotMet($response, 'light_fighter', 'Light Fighter build requirements are met.'); // Verify the research is finished 10 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 20, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); $this->planetService->getPlayer()->updateResearchQueue(); $response = $this->get('/research'); @@ -475,8 +411,7 @@ public function testUnitQueueResearchRequirement(): void $this->addShipyardBuildRequest('light_fighter', 1); // Verify the building is finished 10 minute later. - $testTime = Carbon::create(2024, 1, 1, 12, 30, 0); - Carbon::setTestNow($testTime); + $this->travel(10)->minutes(); $response = $this->get('/shipyard'); $response->assertStatus(200); @@ -485,7 +420,6 @@ public function testUnitQueueResearchRequirement(): void /** * Verify that unit construction time is calculated correctly (higher than 0) - * @throws BindingResolutionException * @throws Exception */ public function testUnitProductionTime(): void @@ -498,7 +432,6 @@ public function testUnitProductionTime(): void /** * Verify that unit construction time is calculated correctly (higher than 0) - * @throws BindingResolutionException * @throws Exception */ public function testUnitProductionTimeHighShipyardLevel(): void @@ -510,10 +443,6 @@ public function testUnitProductionTimeHighShipyardLevel(): void $this->planetSetObjectLevel('shipyard', 10); $this->planetSetObjectLevel('nano_factory', 10); - // Set the current time to a specific moment for testing - $testTime = Carbon::create(2024, 1, 1, 12, 0, 0); - Carbon::setTestNow($testTime); - // --- // Step 1: Issue a request to build 100 rocket launchers. // --- @@ -530,8 +459,7 @@ public function testUnitProductionTimeHighShipyardLevel(): void // --- // Step 3: Verify that after 50 seconds, exactly 50 units are built. (Minimum time per unit is always 1 second) // --- - $testTime = Carbon::create(2024, 1, 1, 12, 0, 50); - Carbon::setTestNow($testTime); + $this->travel(50)->seconds(); $response = $this->get('/defense'); $response->assertStatus(200); diff --git a/tests/Unit/BattleEngineTest.php b/tests/Unit/BattleEngineTest.php index c2737a65..c52fa5fd 100644 --- a/tests/Unit/BattleEngineTest.php +++ b/tests/Unit/BattleEngineTest.php @@ -2,16 +2,15 @@ namespace Tests\Unit; -use Illuminate\Contracts\Container\BindingResolutionException; use OGame\GameMissions\BattleEngine\BattleEngine; use OGame\GameObjects\Models\Units\UnitCollection; +use OGame\Services\ObjectService; use Tests\UnitTestCase; class BattleEngineTest extends UnitTestCase { /** * Set up common test components. - * @throws BindingResolutionException */ protected function setUp(): void { @@ -37,7 +36,7 @@ public function testLootGained(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); // Simulate battle. @@ -64,7 +63,7 @@ public function testLootGainedCapacityConstraintMetalCrystal(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); // Simulate battle. @@ -93,7 +92,7 @@ public function testLootGainedCapacityConstraintMetalCrystalDeuterium(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); // Simulate battle. @@ -122,9 +121,9 @@ public function testAttackerDefenderFleet(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); - $lightFighter = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($lightFighter, 75); // Simulate battle. @@ -170,7 +169,7 @@ public function testAttackerDefenderResearchLevels(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); // Simulate battle. @@ -201,7 +200,7 @@ public function testBattleEngineBasicRounds(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); // Simulate battle. @@ -248,7 +247,7 @@ public function testBattleEngineNoRoundsWithZeroDefense(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $smallCargo = $this->planetService->objects->getUnitObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getUnitObjectByMachineName('small_cargo'); $attackerFleet->addUnit($smallCargo, 5); // Simulate battle. @@ -271,7 +270,7 @@ public function testBattleEngineSimulationCorrect1(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $lightFighter = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($lightFighter, 150); // Simulate battle. @@ -318,9 +317,9 @@ public function testBattleEngineSimulationCorrect2(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $deathStar = $this->planetService->objects->getUnitObjectByMachineName('deathstar'); + $deathStar = ObjectService::getUnitObjectByMachineName('deathstar'); $attackerFleet->addUnit($deathStar, 1); - $lightFighter = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($lightFighter, 1000); // Simulate battle. @@ -351,7 +350,7 @@ public function testBattleEngineStatistics(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $lightFighter = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($lightFighter, 30); // Simulate battle. @@ -380,7 +379,7 @@ public function testBattleEngineRapidfire(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $cruiser = $this->planetService->objects->getUnitObjectByMachineName('cruiser'); + $cruiser = ObjectService::getUnitObjectByMachineName('cruiser'); $attackerFleet->addUnit($cruiser, 30); // Simulate battle. @@ -417,7 +416,7 @@ public function testBattleEngineBounce(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $cruiser = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $cruiser = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($cruiser, 5000); // Simulate battle. @@ -457,7 +456,7 @@ public function testBattleEngineNoBounceHighTechLevel(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $cruiser = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $cruiser = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($cruiser, 5000); // Simulate battle. @@ -488,7 +487,7 @@ public function testBattleEngineSimulationDebris(): void // Create fleet of attacker player. $attackerFleet = new UnitCollection(); - $lightFighter = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($lightFighter, 50); $this->settingsService->set('debris_field_from_ships', 30); @@ -539,7 +538,7 @@ public function testBattleEngineSimulationDebrisDifferentSettings(): void // Create fleet of attacker player. // Expected total losses of attacker player: 150k metal and 50k crystal. $attackerFleet = new UnitCollection(); - $lightFighter = $this->planetService->objects->getUnitObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getUnitObjectByMachineName('light_fighter'); $attackerFleet->addUnit($lightFighter, 50); // Simulate battle @@ -568,7 +567,7 @@ public function testBattleEngineSimulationDebrisDifferentSettings(): void // Create fleet of attacker player. // Expected total losses of defender player: 300k metal and 100k crystal. $attackerFleet = new UnitCollection(); - $bomber = $this->planetService->objects->getUnitObjectByMachineName('bomber'); + $bomber = ObjectService::getUnitObjectByMachineName('bomber'); $attackerFleet->addUnit($bomber, 500); // Simulate battle. @@ -598,7 +597,7 @@ public function testBattleEngineSimulationDebrisDifferentSettings(): void // Create fleet of attacker player. // Expected total losses of attacker player: 1M metal and 350k crystal, 100k deuterium. $attackerFleet = new UnitCollection(); - $cruiser = $this->planetService->objects->getUnitObjectByMachineName('cruiser'); + $cruiser = ObjectService::getUnitObjectByMachineName('cruiser'); $attackerFleet->addUnit($cruiser, 50); // Simulate battle diff --git a/tests/Unit/ObjectLogicTest.php b/tests/Unit/ObjectLogicTest.php index a5bff8ad..eb63000f 100644 --- a/tests/Unit/ObjectLogicTest.php +++ b/tests/Unit/ObjectLogicTest.php @@ -12,17 +12,15 @@ class ObjectLogicTest extends UnitTestCase */ public function testObjectServiceContents(): void { - $objectService = new ObjectService(); - - $this->assertTrue(count($objectService->getObjects()) > 1); - $this->assertTrue(count($objectService->getBuildingObjects()) > 1); - $this->assertTrue(count($objectService->getStationObjects()) > 1); - $this->assertTrue(count($objectService->getResearchObjects()) > 1); - $this->assertTrue(count($objectService->getUnitObjects()) > 1); - $this->assertTrue(count($objectService->getShipObjects()) > 1); - $this->assertTrue(count($objectService->getMilitaryShipObjects()) > 1); - $this->assertTrue(count($objectService->getCivilShipObjects()) > 1); - $this->assertTrue(count($objectService->getDefenseObjects()) > 1); + $this->assertTrue(count(ObjectService::getObjects()) > 1); + $this->assertTrue(count(ObjectService::getBuildingObjects()) > 1); + $this->assertTrue(count(ObjectService::getStationObjects()) > 1); + $this->assertTrue(count(ObjectService::getResearchObjects()) > 1); + $this->assertTrue(count(ObjectService::getUnitObjects()) > 1); + $this->assertTrue(count(ObjectService::getShipObjects()) > 1); + $this->assertTrue(count(ObjectService::getMilitaryShipObjects()) > 1); + $this->assertTrue(count(ObjectService::getCivilShipObjects()) > 1); + $this->assertTrue(count(ObjectService::getDefenseObjects()) > 1); } /** @@ -30,9 +28,7 @@ public function testObjectServiceContents(): void */ public function testShipProperties(): void { - $objectService = new ObjectService(); - - $ships = $objectService->getShipObjects(); + $ships = ObjectService::getShipObjects(); foreach ($ships as $ship) { $this->assertNotNull($ship->properties->structural_integrity); $this->assertNotNull($ship->properties->shield); @@ -46,11 +42,9 @@ public function testShipProperties(): void /** * Test that all defense objects have properties such as structural integrity, shield etc. defined. */ - public function testDefenceProperties(): void + public function testDefenseProperties(): void { - $objectService = new ObjectService(); - - $objects = $objectService->getDefenseObjects(); + $objects = ObjectService::getDefenseObjects(); foreach ($objects as $object) { $this->assertNotNull($object->properties->structural_integrity); $this->assertNotNull($object->properties->shield); diff --git a/tests/Unit/ObjectPropertiesTest.php b/tests/Unit/ObjectPropertiesTest.php index b9ccd468..e2ef4f3d 100644 --- a/tests/Unit/ObjectPropertiesTest.php +++ b/tests/Unit/ObjectPropertiesTest.php @@ -3,6 +3,7 @@ namespace Tests\Unit; use Exception; +use OGame\Services\ObjectService; use Tests\UnitTestCase; class ObjectPropertiesTest extends UnitTestCase @@ -26,7 +27,7 @@ public function testStructuralIntegrityPropertyCalculation(): void 'armor_technology' => 1, ]); - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(4000, $lightFighter->properties->structural_integrity->rawValue); $this->assertEquals(4400, $lightFighter->properties->structural_integrity->calculate($this->playerService)->totalValue); } @@ -42,7 +43,7 @@ public function testShieldPropertyCalculation(): void 'shielding_technology' => 3, ]); - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(10, $lightFighter->properties->shield->rawValue); $this->assertEquals(13, $lightFighter->properties->shield->calculate($this->playerService)->totalValue); } @@ -58,7 +59,7 @@ public function testAttackPropertyCalculation(): void 'weapon_technology' => 2, ]); - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(50, $lightFighter->properties->attack->rawValue); $this->assertEquals(60, $lightFighter->properties->attack->calculate($this->playerService)->totalValue); } @@ -78,31 +79,31 @@ public function testSpeedBasePropertyCalculation(): void // Light fighter // Base 12.500 + 5*10% = 18.750 - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(12500, $lightFighter->properties->speed->rawValue); $this->assertEquals(18750, $lightFighter->properties->speed->calculate($this->playerService)->totalValue); // Small cargo with combustion drive 5 // Base 5.000 + 5*10% = 7.500 - $smallCargo = $this->planetService->objects->getShipObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getShipObjectByMachineName('small_cargo'); $this->assertEquals(5000, $smallCargo->properties->speed->rawValue); $this->assertEquals(7500, $smallCargo->properties->speed->calculate($this->playerService)->totalValue); // Recycler with combustion drive 5 // Base 2.000 + 5*10% = 3.000 - $recycler = $this->planetService->objects->getShipObjectByMachineName('recycler'); + $recycler = ObjectService::getShipObjectByMachineName('recycler'); $this->assertEquals(2000, $recycler->properties->speed->rawValue); $this->assertEquals(3000, $recycler->properties->speed->calculate($this->playerService)->totalValue); // Cruiser with impulse drive level 3 // Base 15.000 + 3*20% = 24.000 - $cruiser = $this->planetService->objects->getShipObjectByMachineName('cruiser'); + $cruiser = ObjectService::getShipObjectByMachineName('cruiser'); $this->assertEquals(15000, $cruiser->properties->speed->rawValue); $this->assertEquals(24000, $cruiser->properties->speed->calculate($this->playerService)->totalValue); // Battleship with hyperspace drive level 4 // Base 10.000 + 4*30% = 22.000 - $battleship = $this->planetService->objects->getShipObjectByMachineName('battle_ship'); + $battleship = ObjectService::getShipObjectByMachineName('battle_ship'); $this->assertEquals(10000, $battleship->properties->speed->rawValue); $this->assertEquals(22000, $battleship->properties->speed->calculate($this->playerService)->totalValue); } @@ -122,17 +123,17 @@ public function testSpeedUpgradePropertyCalculation(): void // Small cargo with impulse drive level 5 (upgrade) // Base 5.000 + 5*20% = 10.000 // TODO: with upgraded drive the base speed of small cargo should be 10.000 instead of default 5.000. - $smallCargo = $this->planetService->objects->getShipObjectByMachineName('small_cargo'); + $smallCargo = ObjectService::getShipObjectByMachineName('small_cargo'); $this->assertEquals(10000, $smallCargo->properties->speed->calculate($this->playerService)->totalValue); // Recycler with hyperspace drive level 15 // Base 2.000 + 15*30% = 11.000 - $recycler = $this->planetService->objects->getShipObjectByMachineName('recycler'); + $recycler = ObjectService::getShipObjectByMachineName('recycler'); $this->assertEquals(11000, $recycler->properties->speed->calculate($this->playerService)->totalValue); // Bomber with hyperspace drive level 15 // Base 4.000 + 15*30% = 22.000 - $recycler = $this->planetService->objects->getShipObjectByMachineName('bomber'); + $recycler = ObjectService::getShipObjectByMachineName('bomber'); $this->assertEquals(22000, $recycler->properties->speed->calculate($this->playerService)->totalValue); } @@ -150,7 +151,7 @@ public function testCapacityPropertyCalculation(): void ]); // TODO: Implement capacity property calculation per object id if it exists? - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(50, $lightFighter->properties->capacity->calculate($this->playerService)->totalValue); } @@ -168,7 +169,7 @@ public function testFuelPropertyCalculation(): void ]); // TODO: Implement fuel property calculation per object id if it exists? - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(20, $lightFighter->properties->fuel->calculate($this->playerService)->totalValue); } @@ -182,7 +183,7 @@ public function testPropertyRetrieval(): void $this->createAndSetUserTechModel([]); // Light fighter check - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $this->assertEquals(4000, $lightFighter->properties->structural_integrity->rawValue); $this->assertEquals(10, $lightFighter->properties->shield->rawValue); $this->assertEquals(50, $lightFighter->properties->attack->rawValue); @@ -204,7 +205,7 @@ public function testPropertyBonusRetrieval(): void ]); // Light fighter check - $lightFighter = $this->planetService->objects->getShipObjectByMachineName('light_fighter'); + $lightFighter = ObjectService::getShipObjectByMachineName('light_fighter'); $calculated = $lightFighter->properties->structural_integrity->calculate($this->playerService); $this->assertEquals(4000, $calculated->rawValue); diff --git a/tests/Unit/ObjectServiceTest.php b/tests/Unit/ObjectServiceTest.php index 575f6040..7506ca78 100644 --- a/tests/Unit/ObjectServiceTest.php +++ b/tests/Unit/ObjectServiceTest.php @@ -12,15 +12,14 @@ class ObjectServiceTest extends UnitTestCase */ public function testGetObjectMaxBuildAmount(): void { - $object_service = new ObjectService(); $this->createAndSetPlanetModel([]); // Test with requirements not met - $max_build_amount = $object_service->getObjectMaxBuildAmount('plasma_turret', $this->planetService, false); + $max_build_amount = ObjectService::getObjectMaxBuildAmount('plasma_turret', $this->planetService, false); $this->assertEquals(0, $max_build_amount); // Test with object limited to one instance per user - $max_build_amount = $object_service->getObjectMaxBuildAmount('small_shield_dome', $this->planetService, true); + $max_build_amount = ObjectService::getObjectMaxBuildAmount('small_shield_dome', $this->planetService, true); $this->assertEquals(1, $max_build_amount); $this->createAndSetPlanetModel([ @@ -28,8 +27,8 @@ public function testGetObjectMaxBuildAmount(): void ]); // Test with object limited to one instance which already exists - $max_build_amount = $object_service->getObjectMaxBuildAmount('small_shield_dome', $this->planetService, true); - $this->assertEquals(0, $max_build_amount); + $maxBuildAmount = ObjectService::getObjectMaxBuildAmount('small_shield_dome', $this->planetService, true); + $this->assertEquals(0, $maxBuildAmount); $this->createAndSetPlanetModel([ 'metal' => 24000, @@ -37,7 +36,7 @@ public function testGetObjectMaxBuildAmount(): void ]); // Test it calculates max amount correctly - $max_build_amount = $object_service->getObjectMaxBuildAmount('anti_ballistic_missile', $this->planetService, true); - $this->assertEquals(3, $max_build_amount); + $maxBuildAmount = ObjectService::getObjectMaxBuildAmount('anti_ballistic_missile', $this->planetService, true); + $this->assertEquals(3, $maxBuildAmount); } } diff --git a/tests/Unit/PlanetServiceTest.php b/tests/Unit/PlanetServiceTest.php index 5c143fda..7c9b0234 100644 --- a/tests/Unit/PlanetServiceTest.php +++ b/tests/Unit/PlanetServiceTest.php @@ -2,7 +2,6 @@ namespace Tests\Unit; -use Illuminate\Contracts\Container\BindingResolutionException; use OGame\Models\BuildingQueue; use OGame\Models\Enums\ResourceType; use OGame\Models\Resources; @@ -12,8 +11,6 @@ class PlanetServiceTest extends UnitTestCase { /** * Set up common test components. - * - * @throws BindingResolutionException */ protected function setUp(): void { @@ -39,7 +36,7 @@ public function testGetResources(): void /** * Test for espionage report getXXXArray() methods. */ - public function testGetObjectarrays(): void + public function testGetObjectArrays(): void { $this->createAndSetPlanetModel([ 'metal_mine' => 1, diff --git a/tests/Unit/ResourceProductionTest.php b/tests/Unit/ResourceProductionTest.php index 9892c082..7ad7f9c2 100644 --- a/tests/Unit/ResourceProductionTest.php +++ b/tests/Unit/ResourceProductionTest.php @@ -2,7 +2,6 @@ namespace Tests\Unit; -use Illuminate\Contracts\Container\BindingResolutionException; use OGame\Services\SettingsService; use Tests\UnitTestCase; @@ -10,7 +9,6 @@ class ResourceProductionTest extends UnitTestCase { /** * Set up common test components. - * @throws BindingResolutionException */ protected function setUp(): void { diff --git a/tests/Unit/UnitCollectionTest.php b/tests/Unit/UnitCollectionTest.php index 98944349..6401adb3 100644 --- a/tests/Unit/UnitCollectionTest.php +++ b/tests/Unit/UnitCollectionTest.php @@ -2,8 +2,9 @@ namespace Tests\Unit; -use Illuminate\Contracts\Container\BindingResolutionException; +use Exception; use OGame\GameObjects\Models\Units\UnitCollection; +use OGame\Services\ObjectService; use Tests\UnitTestCase; /** @@ -16,7 +17,6 @@ class UnitCollectionTest extends UnitTestCase { /** * Set up common test components. - * @throws BindingResolutionException */ protected function setUp(): void { @@ -26,6 +26,7 @@ protected function setUp(): void /** * Test that the slowest unit speed is calculated correctly. + * @throws Exception */ public function testSlowestFleetSpeed(): void { @@ -40,8 +41,8 @@ public function testSlowestFleetSpeed(): void ]); $unitCollection = new UnitCollection(); - $unitCollection->addUnit($this->planetService->objects->getShipObjectByMachineName('small_cargo'), 10); - $unitCollection->addUnit($this->planetService->objects->getShipObjectByMachineName('destroyer'), 3); + $unitCollection->addUnit(ObjectService::getShipObjectByMachineName('small_cargo'), 10); + $unitCollection->addUnit(ObjectService::getShipObjectByMachineName('destroyer'), 3); // Slowest ship should be the destroyer. // - 5.000 = destroyer base speed diff --git a/tests/UnitTestCase.php b/tests/UnitTestCase.php index 460f8068..da750907 100644 --- a/tests/UnitTestCase.php +++ b/tests/UnitTestCase.php @@ -2,7 +2,7 @@ namespace Tests; -use Illuminate\Contracts\Container\BindingResolutionException; +use Exception; use OGame\Factories\PlanetServiceFactory; use OGame\Models\Planet; use OGame\Models\UserTech; @@ -18,7 +18,6 @@ abstract class UnitTestCase extends TestCase /** * Set up common test components. - * @throws BindingResolutionException */ protected function setUp(): void { @@ -32,17 +31,20 @@ protected function setUp(): void * Helper method to create a planet model and configure it. * * @param array $attributes + * @throws Exception */ protected function createAndSetPlanetModel(array $attributes): void { // Create fake planet eloquent model with additional attributes try { $planetModelFake = Planet::factory()->make($attributes); - } catch (\Exception $e) { + } catch (Exception $e) { $this->fail('Failed to create fake planet model: ' . $e->getMessage()); } + // Set the fake model to the planet service $this->planetService->setPlanet($planetModelFake); + // Update resource production stats $this->planetService->updateResourceProductionStats(false); } @@ -56,6 +58,7 @@ protected function createAndSetUserTechModel(array $attributes): void { // Create fake user tech eloquent model with additional attributes $userTechModelFake = UserTech::factory()->make($attributes); + // Set the fake model to the planet service $this->playerService->setUserTech($userTechModelFake); } @@ -64,7 +67,6 @@ protected function createAndSetUserTechModel(array $attributes): void * Set up the planet service for testing. * * @return void - * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function setUpPlanetService(): void { @@ -77,7 +79,6 @@ protected function setUpPlanetService(): void * Set up the player service for testing. * * @return void - * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function setUpPlayerService(): void { @@ -90,7 +91,6 @@ protected function setUpPlayerService(): void * Set up the settings service for testing. * * @return void - * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function setUpSettingsService(): void {