Test Failed
Push — dev ( 83327d...238307 )
by Nico
51:35 queued 19:29
created

ShipTick::sendMessages()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 3
nop 1
dl 0
loc 21
ccs 0
cts 0
cp 0
crap 20
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Stu\Module\Tick\Ship;
4
5
use Override;
0 ignored issues
show
Bug introduced by
The type Override was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use RuntimeException;
7
use Stu\Component\Ship\AstronomicalMappingEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Component\Ship\AstronomicalMappingEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Stu\Component\Ship\Repair\RepairUtilInterface;
9
use Stu\Component\Ship\ShipAlertStateEnum;
10
use Stu\Component\Ship\ShipStateEnum;
11
use Stu\Component\Ship\Storage\ShipStorageManagerInterface;
12
use Stu\Component\Ship\System\Data\EpsSystemData;
13
use Stu\Component\Ship\System\ShipSystemManagerInterface;
14
use Stu\Component\Ship\System\ShipSystemTypeEnum;
15
use Stu\Component\Station\StationUtilityInterface;
16
use Stu\Module\Control\GameControllerInterface;
17
use Stu\Module\Database\Lib\CreateDatabaseEntryInterface;
18
use Stu\Module\Logging\LoggerUtilFactoryInterface;
19
use Stu\Module\Logging\LoggerUtilInterface;
20
use Stu\Module\Message\Lib\PrivateMessageFolderTypeEnum;
21
use Stu\Module\Message\Lib\PrivateMessageSenderInterface;
22
use Stu\Module\PlayerSetting\Lib\UserEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Module\PlayerSetting\Lib\UserEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
use Stu\Module\Ship\Lib\AstroEntryLibInterface;
24
use Stu\Module\Ship\Lib\Crew\ShipLeaverInterface;
25
use Stu\Module\Ship\Lib\Interaction\ShipTakeoverManagerInterface;
26
use Stu\Module\Ship\Lib\Interaction\TrackerDeviceManagerInterface;
27
use Stu\Module\Ship\Lib\ReactorWrapperInterface;
28
use Stu\Module\Ship\Lib\ShipWrapperFactoryInterface;
29
use Stu\Module\Ship\Lib\ShipWrapperInterface;
30
use Stu\Module\Ship\View\ShowShip\ShowShip;
0 ignored issues
show
Bug introduced by
The type Stu\Module\Ship\View\ShowShip\ShowShip was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use Stu\Module\Tick\Ship\ManagerComponent\ManagerComponentInterface;
32
use Stu\Orm\Entity\DatabaseEntryInterface;
33
use Stu\Orm\Entity\ShipInterface;
34
use Stu\Orm\Repository\DatabaseUserRepositoryInterface;
35
use Stu\Orm\Repository\ShipRepositoryInterface;
36
use Stu\Orm\Repository\LocationMiningRepositoryInterface;
37
38
final class ShipTick implements ShipTickInterface, ManagerComponentInterface
39
{
40
    private LoggerUtilInterface $loggerUtil;
41
42
    /**
43
     * @var array<string>
44
     */
45
    private array $msg = [];
46
47
    public function __construct(
48
        private ShipWrapperFactoryInterface $shipWrapperFactory,
49
        private PrivateMessageSenderInterface $privateMessageSender,
50
        private ShipRepositoryInterface $shipRepository,
51
        private ShipSystemManagerInterface $shipSystemManager,
52
        private ShipLeaverInterface $shipLeaver,
53
        private GameControllerInterface $game,
54
        private AstroEntryLibInterface $astroEntryLib,
55
        private DatabaseUserRepositoryInterface $databaseUserRepository,
56
        private CreateDatabaseEntryInterface $createDatabaseEntry,
57
        private StationUtilityInterface $stationUtility,
58
        private RepairUtilInterface $repairUtil,
59
        private ShipTakeoverManagerInterface $shipTakeoverManager,
60
        private TrackerDeviceManagerInterface $trackerDeviceManager,
61
        private ShipStorageManagerInterface $shipStorageManager,
62
        private LocationMiningRepositoryInterface $locationMiningRepository,
63
        LoggerUtilFactoryInterface $loggerUtilFactory
64
    ) {
65
        $this->loggerUtil = $loggerUtilFactory->getLoggerUtil(true);
66
    }
67
68
    #[Override]
69
    public function work(): void
70
    {
71
        foreach ($this->shipRepository->getPlayerShipsForTick() as $ship) {
72
            $this->workShip($this->shipWrapperFactory->wrapShip($ship));
73
        }
74
    }
75
76
    #[Override]
77
    public function workShip(ShipWrapperInterface $wrapper): void
78
    {
79
        $ship = $wrapper->get();
80
81
        $startTime = microtime(true);
82
83
        // do construction stuff
84
        if ($this->doConstructionStuff($ship)) {
85
            $this->shipRepository->save($ship);
86
            $this->sendMessages($ship);
87
            return;
88
        }
89
90
        $this->potentialLog($ship, "marker0", $startTime);
0 ignored issues
show
Bug introduced by
It seems like $startTime can also be of type string; however, parameter $startTime of Stu\Module\Tick\Ship\ShipTick::potentialLog() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

90
        $this->potentialLog($ship, "marker0", /** @scrutinizer ignore-type */ $startTime);
Loading history...
91
92
93
        $startTime = microtime(true);
94
        // repair station
95
        if ($ship->isBase() && $ship->getState() === ShipStateEnum::SHIP_STATE_REPAIR_PASSIVE) {
96
            $this->doRepairStation($wrapper);
97
        }
98
        $this->potentialLog($ship, "marker1", $startTime);
99
100
        $startTime = microtime(true);
101
        // leave ship
102
        if ($ship->getCrewCount() > 0 && !$ship->isSystemHealthy(ShipSystemTypeEnum::SYSTEM_LIFE_SUPPORT)) {
103
            $this->msg[] = _('Die Lebenserhaltung ist ausgefallen:');
104
            $this->msg[] = $this->shipLeaver->evacuate($wrapper);
105
            $this->sendMessages($ship);
106
            $this->potentialLog($ship, "marker2", $startTime);
107
            return;
108
        }
109
110
        $startTime = microtime(true);
111
        $eps = $wrapper->getEpsSystemData();
112
        $reactor = $wrapper->getReactorWrapper();
113
        if ($eps === null) {
114
            $this->potentialLog($ship, "marker3", $startTime);
115
            return;
116
        }
117
118
        $startTime = microtime(true);
119
        $hasEnoughCrew = $ship->hasEnoughCrew();
120
121
        // not enough crew
122
        if (!$hasEnoughCrew) {
123
            $this->msg[] = _('Zu wenig Crew an Bord, Schiff ist nicht voll funktionsfähig! Systeme werden deaktiviert!');
124
125
            //deactivate all systems except life support
126
            foreach ($this->shipSystemManager->getActiveSystems($ship) as $system) {
127
                if ($system->getSystemType() != ShipSystemTypeEnum::SYSTEM_LIFE_SUPPORT) {
128
                    $this->shipSystemManager->deactivate($wrapper, $system->getSystemType(), true);
129
                }
130
            }
131
        }
132
        $this->potentialLog($ship, "marker4", $startTime);
133
134
        $startTime = microtime(true);
135
        $reactorUsageForWarpdrive = $this->loadWarpdrive(
136
            $wrapper,
137
            $hasEnoughCrew
138
        );
139
        $this->potentialLog($ship, "marker5", $startTime);
140
141
        $startTime = microtime(true);
142
        $availableEps = $this->getAvailableEps(
143
            $wrapper,
144
            $eps,
145
            $reactor,
146
            $hasEnoughCrew,
147
            $reactorUsageForWarpdrive
148
        );
149
        $this->potentialLog($ship, "marker6", $startTime);
150
151
        $startTime = microtime(true);
152
        //try to save energy by reducing alert state
153
        if ($wrapper->getEpsUsage() > $availableEps) {
154
            $malus = $wrapper->getEpsUsage() - $availableEps;
155
            $alertUsage = $ship->getAlertState()->value - 1;
156
157
            if ($alertUsage > 0) {
158
                $preState = $ship->getAlertState();
159
                $reduce = (int)min($malus, $alertUsage);
160
161
                $ship->setAlertState(ShipAlertStateEnum::from($preState->value - $reduce));
162
                $this->msg[] = sprintf(
163
                    _('Wechsel von %s auf %s wegen Energiemangel'),
164
                    $preState->getDescription(),
165
                    $ship->getAlertState()->getDescription()
166
                );
167
            }
168
        }
169
        $this->potentialLog($ship, "marker7", $startTime);
170
171
        $startTime = microtime(true);
172
        //try to save energy by deactivating systems from low to high priority
173
        if ($wrapper->getEpsUsage() > $availableEps) {
174
            $activeSystems = $this->shipSystemManager->getActiveSystems($ship, true);
175
176
            foreach ($activeSystems as $system) {
177
                $energyConsumption = $this->shipSystemManager->getEnergyConsumption($system->getSystemType());
178
                if ($energyConsumption < 1) {
179
                    continue;
180
                }
181
182
                //echo "- eps: ".$eps." - usage: ".$wrapper->getEpsUsage()."\n";
183
                if ($availableEps - $wrapper->getEpsUsage() - $energyConsumption < 0) {
184
                    //echo "-- hit system: ".$system->getDescription()."\n";
185
186
                    $this->shipSystemManager->deactivate($wrapper, $system->getSystemType(), true);
187
188
                    $wrapper->lowerEpsUsage($energyConsumption);
189
                    $this->msg[] = $system->getSystemType()->getDescription() . ' deaktiviert wegen Energiemangel';
190
191
                    if ($ship->getCrewCount() > 0 && $system->getSystemType() == ShipSystemTypeEnum::SYSTEM_LIFE_SUPPORT) {
192
                        $this->msg[] = _('Die Lebenserhaltung ist ausgefallen:');
193
                        $this->msg[] = $this->shipLeaver->evacuate($wrapper);
194
                        $this->sendMessages($ship);
195
                        return;
196
                    }
197
                }
198
                if ($wrapper->getEpsUsage() <= $availableEps) {
199
                    break;
200
                }
201
            }
202
        }
203
204
        $this->potentialLog($ship, "marker8", $startTime);
205
        $startTime = microtime(true);
206
207
        $newEps = $availableEps - $wrapper->getEpsUsage();
208
        $batteryReload = $ship->isBase()
209
            && $eps->reloadBattery()
210
            && $newEps > $eps->getEps()
211
            ? min(
212
                (int) ceil($eps->getMaxBattery() / 10),
213
                $newEps - $eps->getEps(),
214
                $eps->getMaxBattery() - $eps->getBattery()
215
            ) : 0;
216
217
        $newEps -= $batteryReload;
218
        if ($newEps > $eps->getMaxEps()) {
219
            $newEps = $eps->getMaxEps();
220
        }
221
222
223
        $usedEnergy = $wrapper->getEpsUsage() + $batteryReload + ($newEps - $eps->getEps()) + $reactorUsageForWarpdrive;
224
225
        //echo "--- Generated Id ".$ship->getId()." - eps: ".$eps." - usage: ".$wrapper->getEpsUsage()." - old eps: ".$ship->getEps()." - wk: ".$wkuse."\n";
226
        $eps->setEps($newEps)
227
            ->setBattery($eps->getBattery() + $batteryReload)
228
            ->update();
229
230
        if ($usedEnergy > 0 && $reactor !== null) {
231
            $reactor->changeLoad(-$usedEnergy);
232
        }
233
234
        $this->potentialLog($ship, "marker9", $startTime);
235
236
        $startTime = microtime(true);
237
        $this->checkForFinishedTakeover($ship);
238
        $this->potentialLog($ship, "marker10", $startTime);
239
240
        $startTime = microtime(true);
241
        $this->checkForFinishedAstroMapping($wrapper);
242
        $this->potentialLog($ship, "marker11", $startTime);
243
244
        //update tracker status
245
        $startTime = microtime(true);
246
        $this->doTrackerDeviceStuff($wrapper);
247
        $this->potentialLog($ship, "marker12", $startTime);
248
249
        $startTime = microtime(true);
250
        $this->shipRepository->save($ship);
251
        $this->potentialLog($ship, "marker13", $startTime);
252
253
        $startTime = microtime(true);
254
        $this->sendMessages($ship);
255
        $this->potentialLog($ship, "marker14", $startTime);
256
257
        $starTime = microtime(true);
0 ignored issues
show
Unused Code introduced by
The assignment to $starTime is dead and can be removed.
Loading history...
258
        $this->doBussardCollectorStuff($wrapper);
259
        $this->potentialLog($ship, "marker15", $startTime);
260
    }
261
262
    private function potentialLog(ShipInterface $ship, string $marker, float $startTime): void
263
    {
264
        $endTime = microtime(true);
265
266
        if (
267
            $endTime - $startTime > 0.01
268
        ) {
269
            $this->loggerUtil->log(sprintf(
270
                "\t\t\t%s of %d, seconds: %F",
271
                $marker,
272
                $ship->getId(),
273
                $endTime - $startTime
274
            ));
275
        }
276
    }
277
278
    private function getAvailableEps(
279
        ShipWrapperInterface $wrapper,
280
        EpsSystemData $eps,
281
        ?ReactorWrapperInterface $reactor,
282
        bool $hasEnoughCrew,
283
        int $reactorUsageForWarpdrive
284
    ): int {
285
        if ($hasEnoughCrew && $reactor !== null) {
286
287
            return $eps->getEps() + $reactor->getEpsProduction() +  $this->getCarryOver(
288
                $wrapper,
289
                $reactor,
290
                $reactorUsageForWarpdrive
291
            );
292
        }
293
294
        return $eps->getEps();
295
    }
296
297
    private function getCarryOver(
298
        ShipWrapperInterface $wrapper,
299
        ReactorWrapperInterface $reactor,
300
        int $reactorUsageForWarpdrive
301
    ): int {
302
        $warpdrive = $wrapper->getWarpDriveSystemData();
303
        if ($warpdrive === null || !$warpdrive->getAutoCarryOver()) {
304
            return 0;
305
        }
306
307
        return $reactor->getOutputCappedByLoad() - $reactor->getEpsProduction() - $reactorUsageForWarpdrive;
308
    }
309
310
    private function loadWarpdrive(ShipWrapperInterface $wrapper, bool $hasEnoughCrew): int
311
    {
312
        if (!$hasEnoughCrew) {
313
            return 0;
314
        }
315
316
        $reactor = $wrapper->getReactorWrapper();
317
        $warpdrive = $wrapper->getWarpDriveSystemData();
318
        if ($warpdrive === null || $reactor === null) {
319
            return 0;
320
        }
321
322
        $effectiveWarpdriveProduction = $reactor->getEffectiveWarpDriveProduction();
323
        if ($effectiveWarpdriveProduction === 0) {
324
            return 0;
325
        }
326
327
        $currentLoad = $warpdrive->getWarpDrive();
328
329
        $warpdrive->setWarpDrive($currentLoad + $effectiveWarpdriveProduction)->update();
330
331
        return $effectiveWarpdriveProduction * $wrapper->get()->getRump()->getFlightECost();
332
    }
333
334
    private function doConstructionStuff(ShipInterface $ship): bool
335
    {
336
        $progress =  $this->stationUtility->getConstructionProgress($ship);
337
338
        if ($progress === null) {
339
            return false;
340
        }
341
342
        if ($progress->getRemainingTicks() === 0) {
343
            return false;
344
        }
345
346
        $isUnderConstruction = $ship->getState() === ShipStateEnum::SHIP_STATE_UNDER_CONSTRUCTION;
347
348
        if (!$this->stationUtility->hasEnoughDockedWorkbees($ship, $ship->getRump())) {
349
            $neededWorkbees = $isUnderConstruction ? $ship->getRump()->getNeededWorkbees() :
350
                (int)ceil($ship->getRump()->getNeededWorkbees() / 2);
351
352
            $this->msg[] = sprintf(
353
                _('Nicht genügend Workbees (%d/%d) angedockt um %s weiterführen zu können'),
354
                $this->stationUtility->getDockedWorkbeeCount($ship),
355
                $neededWorkbees,
356
                $isUnderConstruction ? 'den Bau' : 'die Demontage'
357
            );
358
            return true;
359
        }
360
361
        if ($progress->getRemainingTicks() === 1) {
362
            if ($isUnderConstruction) {
363
                $this->stationUtility->finishStation($ship, $progress);
364
            } else {
365
                $this->stationUtility->finishScrapping($ship, $progress);
366
            }
367
368
            $this->msg[] = sprintf(
369
                _('%s: %s bei %s fertiggestellt'),
370
                $ship->getRump()->getName(),
371
                $isUnderConstruction ? 'Bau' : 'Demontage',
372
                $ship->getSectorString()
373
            );
374
        } else {
375
            $this->stationUtility->reduceRemainingTicks($progress);
376
377
            if ($isUnderConstruction) {
378
                // raise hull
379
                $increase = intdiv($ship->getMaxHull(), 2 * $ship->getRump()->getBuildtime());
380
                $ship->setHuell($ship->getHull() + $increase);
381
            }
382
        }
383
384
        return true;
385
    }
386
387
    private function doRepairStation(ShipWrapperInterface $wrapper): void
388
    {
389
        $station = $wrapper->get();
390
391
        if (!$this->stationUtility->hasEnoughDockedWorkbees($station, $station->getRump())) {
392
            $neededWorkbees = (int)ceil($station->getRump()->getNeededWorkbees() / 5);
393
394
            $this->msg[] = sprintf(
395
                _('Nicht genügend Workbees (%d/%d) angedockt um die Reparatur weiterführen zu können'),
396
                $this->stationUtility->getDockedWorkbeeCount($station),
397
                $neededWorkbees
398
            );
399
            return;
400
        }
401
402
        $neededParts = $this->repairUtil->determineSpareParts($wrapper, true);
403
404
        // parts stored?
405
        if (!$this->repairUtil->enoughSparePartsOnEntity($neededParts, $station, $station)) {
406
            return;
407
        }
408
409
        //repair hull
410
        $station->setHuell($station->getHull() + $station->getRepairRate());
411
        if ($station->getHull() > $station->getMaxHull()) {
412
            $station->setHuell($station->getMaxHull());
413
        }
414
415
        //repair station systems
416
        $damagedSystems = $wrapper->getDamagedSystems();
417
        if ($damagedSystems !== []) {
418
            $firstSystem = $damagedSystems[0];
419
            $firstSystem->setStatus(100);
420
421
            if ($station->getCrewCount() > 0) {
422
                $firstSystem->setMode($this->shipSystemManager->lookupSystem($firstSystem->getSystemType())->getDefaultMode());
423
            }
424
425
            // maximum of two systems get repaired
426
            if (count($damagedSystems) > 1) {
427
                $secondSystem = $damagedSystems[1];
428
                $secondSystem->setStatus(100);
429
430
                if ($station->getCrewCount() > 0) {
431
                    $secondSystem->setMode($this->shipSystemManager->lookupSystem($secondSystem->getSystemType())->getDefaultMode());
432
                }
433
            }
434
        }
435
436
        // consume spare parts
437
        $this->repairUtil->consumeSpareParts($neededParts, $station);
438
439
        if (!$wrapper->canBeRepaired()) {
440
            $station->setHuell($station->getMaxHull());
441
            $station->setState(ShipStateEnum::SHIP_STATE_NONE);
442
443
            $shipOwnerMessage = sprintf(
444
                "Die Reparatur der %s wurde in Sektor %s fertiggestellt",
445
                $station->getName(),
446
                $station->getSectorString()
447
            );
448
449
            $this->privateMessageSender->send(
450
                UserEnum::USER_NOONE,
451
                $station->getUser()->getId(),
452
                $shipOwnerMessage,
453
                PrivateMessageFolderTypeEnum::SPECIAL_STATION
454
            );
455
        }
456
        $this->shipRepository->save($station);
457
    }
458
459
    private function checkForFinishedTakeover(ShipInterface $ship): void
460
    {
461
        $startTime = microtime(true);
462
        $takeover = $ship->getTakeoverActive();
463
        if ($takeover === null) {
464
            return;
465
        }
466
        $this->potentialLog($ship, "marker10.1", $startTime);
0 ignored issues
show
Bug introduced by
It seems like $startTime can also be of type string; however, parameter $startTime of Stu\Module\Tick\Ship\ShipTick::potentialLog() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

466
        $this->potentialLog($ship, "marker10.1", /** @scrutinizer ignore-type */ $startTime);
Loading history...
467
468
        $startTime = microtime(true);
469
        $isTakeoverReady = $this->shipTakeoverManager->isTakeoverReady($takeover);
470
        $this->potentialLog($ship, "marker10.2", $startTime);
471
472
        if ($isTakeoverReady) {
473
            $startTime = microtime(true);
474
            $this->shipTakeoverManager->finishTakeover($takeover);
475
            $this->potentialLog($ship, "marker10.3", $startTime);
476
        }
477
    }
478
479
    private function checkForFinishedAstroMapping(ShipWrapperInterface $wrapper): void
480
    {
481
        $ship = $wrapper->get();
482
483
        /** @var null|DatabaseEntryInterface $databaseEntry */
484
        [$message, $databaseEntry] = $this->getDatabaseEntryForShipLocation($ship);
485
486
        $astroLab = $wrapper->getAstroLaboratorySystemData();
487
488
        if (
489
            $ship->getState() === ShipStateEnum::SHIP_STATE_ASTRO_FINALIZING
490
            && $databaseEntry !== null
491
            && $astroLab !== null
492
            && $this->game->getCurrentRound()->getTurn() >= ($astroLab->getAstroStartTurn() + AstronomicalMappingEnum::TURNS_TO_FINISH)
493
        ) {
494
            $this->astroEntryLib->finish($wrapper);
495
496
            $this->msg[] = sprintf(
497
                _('Die Kartographierung %s wurde vollendet'),
498
                $message
499
            );
500
501
            $userId = $ship->getUser()->getId();
502
            $databaseEntryId = $databaseEntry->getId();
503
504
            if (!$this->databaseUserRepository->exists($userId, $databaseEntryId)) {
505
                $entry = $this->createDatabaseEntry->createDatabaseEntryForUser($ship->getUser(), $databaseEntryId);
506
507
                if ($entry !== null) {
508
                    $this->msg[] = sprintf(
509
                        _('Neuer Datenbankeintrag: %s (+%d Punkte)'),
510
                        $entry->getDescription(),
511
                        $entry->getCategory()->getPoints()
512
                    );
513
                }
514
            }
515
        }
516
    }
517
518
    /**
519
     * @return array{0: string|null, 1: DatabaseEntryInterface|null}
520
     */
521
    private function getDatabaseEntryForShipLocation(ShipInterface $ship): array
522
    {
523
        $system = $ship->getSystem();
524
        if ($system !== null) {
525
            return [
526
                'des Systems ' . $system->getName(),
527
                $system->getDatabaseEntry()
528
            ];
529
        }
530
531
        $mapRegion = $ship->getMapRegion();
532
        if ($mapRegion !== null) {
533
            return [
534
                'der Region ' . $mapRegion->getDescription(),
535
                $mapRegion->getDatabaseEntry()
536
            ];
537
        }
538
539
        return [null, null];
540
    }
541
542
    private function doTrackerDeviceStuff(ShipWrapperInterface $wrapper): void
543
    {
544
        $ship = $wrapper->get();
545
        $tracker = $wrapper->getTrackerSystemData();
546
547
        if ($tracker === null || $tracker->targetId === null) {
548
            return;
549
        }
550
551
        $targetWrapper = $tracker->getTargetWrapper();
552
        if ($targetWrapper === null) {
553
            throw new RuntimeException('should not happen');
554
        }
555
556
        $target = $targetWrapper->get();
557
        $shipLocation = $ship->getLocation();
558
        $targetLocation = $target->getLocation();
559
        $remainingTicks = $tracker->getRemainingTicks();
560
561
        $reduceByTicks = max(1, (int)ceil((abs($shipLocation->getCx() - $targetLocation->getCx())
562
            +  abs($shipLocation->getCy() - $targetLocation->getCy())) / 50));
563
564
        //reduce remaining ticks
565
        if ($remainingTicks > $reduceByTicks) {
566
            $tracker->setRemainingTicks($remainingTicks - $reduceByTicks)->update();
567
        } else {
568
            $this->trackerDeviceManager->deactivateTrackerIfActive($wrapper, true);
569
        }
570
    }
571
572
    private function doBussardCollectorStuff(ShipWrapperInterface $wrapper): void
573
    {
574
        $ship = $wrapper->get();
575
        $bussard = $wrapper->getBussardCollectorSystemData();
576
        $miningqueue = $ship->getMiningQueue();
577
578
        if ($bussard === null) {
579
            return;
580
        }
581
582
        if ($miningqueue == null) {
583
            return;
584
        } else {
585
            $locationmining = $miningqueue->getLocationMining();
586
            $actualAmount = $locationmining->getActualAmount();
587
            $freeStorage = $ship->getMaxStorage() - $ship->getStorageSum();
588
            $module = $ship->getShipSystem(ShipSystemTypeEnum::SYSTEM_BUSSARD_COLLECTOR)->getModule();
589
            $gathercount = 0;
590
591
            if ($module) {
592
                if ($module->getFactionId() == null) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $module->getFactionId() of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison === instead.
Loading history...
593
                    $gathercount =  (int) min(min(round(mt_rand(95, 105)), $actualAmount), $freeStorage);
594
                } else {
595
                    $gathercount = (int) min(min(round(mt_rand(190, 220)), $actualAmount), $freeStorage);
596
                }
597
            }
598
599
            $newAmount = $actualAmount - $gathercount;
600
            if ($gathercount > 0 && $locationmining->getDepletedAt() !== null) {
601
                $locationmining->setDepletedAt(null);
602
            }
603
            if ($newAmount == 0 && $actualAmount > 0) {
604
                $locationmining->setDepletedAt(time());
605
            }
606
            $locationmining->setActualAmount($newAmount);
607
608
            $this->locationMiningRepository->save($locationmining);
609
610
            $this->shipStorageManager->upperStorage(
611
                $ship,
612
                $locationmining->getCommodity(),
613
                $gathercount
614
            );
615
        }
616
    }
617
618
619
    private function sendMessages(ShipInterface $ship): void
620
    {
621
        if ($this->msg === []) {
622
            return;
623
        }
624
        $text = "Tickreport der " . $ship->getName() . "\n";
625
        foreach ($this->msg as $msg) {
626
            $text .= $msg . "\n";
627
        }
628
629
        $href = sprintf('ship.php?%s=1&id=%d', ShowShip::VIEW_IDENTIFIER, $ship->getId());
630
631
        $this->privateMessageSender->send(
632
            UserEnum::USER_NOONE,
633
            $ship->getUser()->getId(),
634
            $text,
635
            $ship->isBase() ? PrivateMessageFolderTypeEnum::SPECIAL_STATION : PrivateMessageFolderTypeEnum::SPECIAL_SHIP,
636
            $href
637
        );
638
639
        $this->msg = [];
640
    }
641
}
642