GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

OrbitalBaseManager::uRecycling()   F
last analyzed

Complexity

Conditions 22
Paths 385

Size

Total Lines 183
Code Lines 124

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 124
nc 385
nop 1
dl 0
loc 183
rs 3.5977
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Orbital Base Manager
5
 *
6
 * @author Jacky Casas
7
 * @copyright Expansion - le jeu
8
 *
9
 * @package Athena
10
 * @update 02.01.14
11
*/
12
namespace Asylamba\Modules\Athena\Manager;
13
14
use Asylamba\Classes\Library\Session\SessionWrapper;
15
use Asylamba\Classes\Library\Utils;
16
use Asylamba\Classes\Library\Game;
17
use Asylamba\Classes\Library\Format;
18
use Asylamba\Classes\Worker\CTC;
19
use Asylamba\Classes\Exception\ErrorException;
20
use Asylamba\Classes\Entity\EntityManager;
21
22
use Asylamba\Modules\Athena\Model\Transaction;
23
use Asylamba\Modules\Ares\Model\Commander;
24
use Asylamba\Modules\Athena\Model\OrbitalBase;
25
use Asylamba\Modules\Gaia\Model\System;
26
use Asylamba\Modules\Athena\Manager\BuildingQueueManager;
27
use Asylamba\Modules\Athena\Manager\ShipQueueManager;
28
use Asylamba\Modules\Promethee\Manager\TechnologyQueueManager;
29
use Asylamba\Modules\Promethee\Manager\TechnologyManager;
30
use Asylamba\Modules\Athena\Manager\CommercialShippingManager;
31
use Asylamba\Modules\Athena\Manager\CommercialRouteManager;
32
use Asylamba\Modules\Zeus\Manager\PlayerManager;
33
use Asylamba\Modules\Zeus\Manager\PlayerBonusManager;
34
use Asylamba\Modules\Athena\Manager\RecyclingMissionManager;
35
use Asylamba\Modules\Athena\Manager\RecyclingLogManager;
36
use Asylamba\Modules\Gaia\Manager\PlaceManager;
37
use Asylamba\Modules\Ares\Manager\CommanderManager;
38
use Asylamba\Modules\Hermes\Manager\NotificationManager;
39
use Asylamba\Modules\Athena\Helper\OrbitalBaseHelper;
40
use Asylamba\Modules\Demeter\Resource\ColorResource;
41
42
use Asylamba\Modules\Athena\Model\RecyclingMission;
43
use Asylamba\Modules\Athena\Model\RecyclingLog;
44
use Asylamba\Modules\Zeus\Model\PlayerBonus;
45
use Asylamba\Modules\Gaia\Model\Place;
46
use Asylamba\Modules\Zeus\Model\Player;
47
use Asylamba\Modules\Athena\Model\CommercialShipping;
48
use Asylamba\Modules\Hermes\Model\Notification;
49
50
use Asylamba\Modules\Athena\Resource\OrbitalBaseResource;
51
use Asylamba\Modules\Promethee\Helper\TechnologyHelper;
52
use Asylamba\Modules\Athena\Resource\ShipResource;
53
use Asylamba\Classes\Library\Flashbag;
54
55
use Asylamba\Classes\Daemon\ClientManager;
56
use Asylamba\Classes\Scheduler\RealTimeActionScheduler;
57
58
class OrbitalBaseManager {
59
	/** @var EntityManager **/
60
	protected $entityManager;
61
	/** @var ClientManager **/
62
	protected $clientManager;
63
	/** @var RealTimeActionScheduler **/
64
	protected $realtimeActionScheduler;
65
	/** @var BuildingQueueManager **/
66
	protected $buildingQueueManager;
67
	/** @var ShipQueueManager **/
68
	protected $shipQueueManager;
69
	/** @var TechnologyQueueManager **/
70
	protected $technologyQueueManager;
71
	/** @var TechnologyManager **/
72
	protected $technologyManager;
73
	/** @var TechnologyHelper **/
74
	protected $technologyHelper;
75
	/** @var CommercialShippingManager **/
76
	protected $commercialShippingManager;
77
	/** @var CommercialRouteManager **/
78
	protected $commercialRouteManager;
79
	/** @var TransactionManager **/
80
	protected $transactionManager;
81
	/** @var PlayerManager **/
82
	protected $playerManager;
83
	/** @var PlayerBonusManager **/
84
	protected $playerBonusManager;
85
	/** @var RecyclingMissionManager **/
86
	protected $recyclingMissionManager;
87
	/** @var RecyclingLogManager **/
88
	protected $recyclingLogManager;
89
	/** @var PlaceManager **/
90
	protected $placeManager;
91
	/** @var CommanderManager **/
92
	protected $commanderManager;
93
	/** @var NotificationManager **/
94
	protected $notificationManager;
95
	/** @var OrbitalBaseHelper **/
96
	protected $orbitalBaseHelper;
97
	/** @var CTC **/
98
	protected $ctc;
99
	/** @var SessionWrapper **/
100
	protected $sessionWrapper;
101
	
102
	/**
103
	 * @param EntityManager $entityManager
104
	 * @param ClientManager $clientManager
105
	 * @param RealTimeActionScheduler $realtimeActionScheduler
106
	 * @param BuildingQueueManager $buildingQueueManager
107
	 * @param ShipQueueManager $shipQueueManager
108
	 * @param TechnologyQueueManager $technologyQueueManager
109
	 * @param TechnologyHelper $technologyHelper
110
	 * @param CommercialShippingManager $commercialShippingManager
111
	 * @param CommercialRouteManager $commercialRouteManager
112
	 * @param TransactionManager $transactionManager
113
	 * @param PlayerManager $playerManager
114
	 * @param PlayerBonusManager $playerBonusManager
115
	 * @param RecyclingMissionManager $recyclingMissionManager
116
	 * @param PlaceManager $placeManager
117
	 * @param CommanderManager $commanderManager
118
	 * @param NotificationManager $notificationManager
119
	 * @param OrbitalBaseHelper $orbitalBaseHelper
120
	 * @param CTC $ctc
121
	 * @param SessionWrapper $sessionWrapper
122
	 */
123
	public function __construct(
124
		EntityManager $entityManager,
125
		ClientManager $clientManager,
126
		RealTimeActionScheduler $realtimeActionScheduler,
127
		BuildingQueueManager $buildingQueueManager,
128
		ShipQueueManager $shipQueueManager,
129
		TechnologyQueueManager $technologyQueueManager,
130
		TechnologyManager $technologyManager,
131
		TechnologyHelper $technologyHelper,
132
		CommercialShippingManager $commercialShippingManager,
133
		CommercialRouteManager $commercialRouteManager,
134
		TransactionManager $transactionManager,
135
		PlayerManager $playerManager,
136
		PlayerBonusManager $playerBonusManager,
137
		RecyclingMissionManager $recyclingMissionManager,
138
		RecyclingLogManager $recyclingLogManager,
139
		PlaceManager $placeManager,
140
		CommanderManager $commanderManager,
141
		NotificationManager $notificationManager,
142
		OrbitalBaseHelper $orbitalBaseHelper,
143
		CTC $ctc,
144
		SessionWrapper $sessionWrapper
145
	) {
146
		$this->entityManager = $entityManager;
147
		$this->clientManager = $clientManager;
148
		$this->realtimeActionScheduler = $realtimeActionScheduler;
149
		$this->buildingQueueManager = $buildingQueueManager;
150
		$this->shipQueueManager = $shipQueueManager;
151
		$this->technologyQueueManager = $technologyQueueManager;
152
		$this->technologyManager = $technologyManager;
153
		$this->technologyHelper = $technologyHelper;
154
		$this->commercialShippingManager = $commercialShippingManager;
155
		$this->commercialRouteManager = $commercialRouteManager;
156
		$this->transactionManager = $transactionManager;
157
		$this->playerManager = $playerManager;
158
		$this->playerBonusManager = $playerBonusManager;
159
		$this->recyclingMissionManager = $recyclingMissionManager;
160
		$this->recyclingLogManager = $recyclingLogManager;
161
		$this->placeManager = $placeManager;
162
		$this->commanderManager = $commanderManager;
163
		$this->notificationManager = $notificationManager;
164
		$this->orbitalBaseHelper = $orbitalBaseHelper;
165
		$this->ctc = $ctc;
166
		$this->sessionWrapper = $sessionWrapper;
167
	}
168
	
169
	/**
170
	 * @param int $id
171
	 * @return OrbitalBase
172
	 */
173
	public function get($id)
174
	{
175
		if (($orbitalBase = $this->entityManager->getRepository(OrbitalBase::class)->get($id)) !== null) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method get() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Ares\Re...ory\CommanderRepository, Asylamba\Modules\Ares\Re...ry\LiveReportRepository, Asylamba\Modules\Ares\Repository\ReportRepository, Asylamba\Modules\Athena\...BuildingQueueRepository, Asylamba\Modules\Athena\...mmercialRouteRepository, Asylamba\Modules\Athena\...rcialShippingRepository, Asylamba\Modules\Athena\...y\OrbitalBaseRepository, Asylamba\Modules\Athena\...yclingMissionRepository, Asylamba\Modules\Athena\...ory\ShipQueueRepository, Asylamba\Modules\Athena\...y\TransactionRepository, Asylamba\Modules\Demeter...ository\ColorRepository, Asylamba\Modules\Demeter...ion\CandidateRepository, Asylamba\Modules\Demeter...tion\ElectionRepository, Asylamba\Modules\Demeter...m\FactionNewsRepository, Asylamba\Modules\Demeter...itory\Law\LawRepository, Asylamba\Modules\Gaia\Repository\PlaceRepository, Asylamba\Modules\Gaia\Repository\SectorRepository, Asylamba\Modules\Gaia\Repository\SystemRepository, Asylamba\Modules\Hermes\...\NotificationRepository, Asylamba\Modules\Prometh...chnologyQueueRepository, Asylamba\Modules\Zeus\Repository\PlayerRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
176
			$this->fill($orbitalBase);
177
		}
178
		return $orbitalBase;
179
	}
180
	
181
	/**
182
	 * @param int $baseId
183
	 * @param int $playerId
184
	 * @return OrbitalBase
185
	 */
186
	public function getPlayerBase($baseId, $playerId)
187
	{
188
		$orbitalBase = $this->entityManager->getRepository(OrbitalBase::class)->getPlayerBase($baseId, $playerId);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method getPlayerBase() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
189
		$this->fill($orbitalBase);
190
		return $orbitalBase;
191
	}
192
	
193
	/**
194
	 * @param int $playerId
195
	 * @return array
196
	 */
197
	public function getPlayerBases($playerId)
198
	{
199
		$bases = $this->entityManager->getRepository(OrbitalBase::class)->getPlayerBases($playerId);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method getPlayerBases() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
200
		foreach($bases as $base) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
201
			$this->fill($base);
202
		}
203
		return $bases;
204
	}
205
	
206
	/**
207
	 * @param int $sectorId
208
	 * @return array
209
	 */
210
	public function getSectorBases($sectorId)
211
	{
212
		$bases = $this->entityManager->getRepository(OrbitalBase::class)->getSectorBases($sectorId);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method getSectorBases() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
213
		foreach($bases as $base) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
214
			$this->fill($base);
215
		}
216
		return $bases;
217
	}
218
	
219
	/**
220
	 * @param System $system
221
	 * @return array
222
	 */
223
	public function getSystemBases(System $system)
224
	{
225
		$bases = $this->entityManager->getRepository(OrbitalBase::class)->getSystemBases($system->getId());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method getSystemBases() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
226
		foreach($bases as $base) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
227
			$this->fill($base);
228
		}
229
		return $bases;
230
	}
231
232
	public function search($search, $order = array(), $limit = array()) {
233
		$search = '%' . $search . '%';
234
		
235
		$formatOrder = Utils::arrayToOrder($order);
236
		$formatLimit = Utils::arrayToLimit($limit);
237
238
		$qr = $this->database->prepare('SELECT 
0 ignored issues
show
Bug introduced by
The property database does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
239
			ob.*,
240
			p.position AS position,
241
			p.rSystem AS system,
242
			s.xPosition AS xSystem,
243
			s.yPosition AS ySystem,
244
			s.rSector AS sector,
245
			se.rColor AS sectorColor,
246
			se.tax AS tax,
247
			p.population AS planetPopulation,
248
			p.coefResources AS planetResources,
249
			p.coefHistory AS planetHistory,
250
			(SELECT
251
				MAX(bq.dEnd) 
252
				FROM orbitalBaseBuildingQueue AS bq 
253
				WHERE bq.rOrbitalBase = ob.rPlace)
254
				AS termDateGenerator,
255
			(SELECT 
256
				MAX(sq1.dEnd) 
257
				FROM orbitalBaseShipQueue AS sq1 
258
				WHERE sq1.rOrbitalBase = ob.rPlace AND sq1.dockType = 1) 
259
				AS termDateDock1,
260
			(SELECT 
261
				MAX(sq2.dEnd) 
262
				FROM orbitalBaseShipQueue AS sq2 
263
				WHERE sq2.rOrbitalBase = ob.rPlace AND sq2.dockType = 2) 
264
				AS termDateDock2,
265
			(SELECT 
266
				MAX(sq3.dEnd) 
267
				FROM orbitalBaseShipQueue AS sq3
268
				WHERE sq3.rOrbitalBase = ob.rPlace AND sq3.dockType = 3) 
269
				AS termDateDock3,
270
			(SELECT
271
				COUNT(cr.id)
272
				FROM commercialRoute AS cr
273
				WHERE (cr.rOrbitalBase = ob.rPlace OR cr.rOrbitalBaseLinked = ob.rPlace) AND cr.statement = 1)
274
				AS routesNumber
275
			FROM orbitalBase AS ob
276
			LEFT JOIN place AS p
277
				ON ob.rPlace = p.id
278
				LEFT JOIN system AS s
279
					ON p.rSystem = s.id
280
					LEFT JOIN sector AS se
281
						ON s.rSector = se.id
282
			WHERE LOWER(name) LIKE LOWER(?)
283
			' . $formatOrder . '
284
			' . $formatLimit
285
		);
286
287
		$qr->execute(array($search));
288
289
		$this->fill($qr);
290
	}
291
292
	/**
293
	 * 
294
	 * @param OrbitalBase $orbitalBase
295
	 * @throws ErrorException
296
	 */
297
	protected function fill(OrbitalBase $orbitalBase) {
298
		$buildingQueues = $this->buildingQueueManager->getBaseQueues($orbitalBase->getRPlace());
299
300
		$realGeneratorLevel = $orbitalBase->getLevelGenerator();
301
		$realRefineryLevel = $orbitalBase->getLevelRefinery();
302
		$realDock1Level = $orbitalBase->getLevelDock1();
303
		$realDock2Level = $orbitalBase->getLevelDock2();
304
		$realDock3Level = $orbitalBase->getLevelDock3();
305
		$realTechnosphereLevel = $orbitalBase->getLevelTechnosphere();
306
		$realCommercialPlateformeLevel = $orbitalBase->getLevelCommercialPlateforme();
307
		$realStorageLevel = $orbitalBase->getLevelStorage();
308
		$realRecyclingLevel = $orbitalBase->getLevelRecycling();
309
		$realSpatioportLevel = $orbitalBase->getLevelSpatioport();
310
311
		foreach ($buildingQueues as $buildingQueue) {
312
			switch ($buildingQueue->buildingNumber) {
313
				case 0 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
314
					$realGeneratorLevel++;
315
					break;
316
				case 1 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
317
					$realRefineryLevel++;
318
					break;
319
				case 2 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
320
					$realDock1Level++;
321
					break;
322
				case 3 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
323
					$realDock2Level++;
324
					break;
325
				case 4 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
326
					$realDock3Level++;
327
					break;
328
				case 5 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
329
					$realTechnosphereLevel++;
330
					break;
331
				case 6 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
332
					$realCommercialPlateformeLevel++;
333
					break;
334
				case 7 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
335
					$realStorageLevel++;
336
					break;
337
				case 8 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
338
					$realRecyclingLevel++;
339
					break;
340
				case 9 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
341
					$realSpatioportLevel++;
342
					break;
343
				default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
344
					throw new ErrorException('Erreur dans la base de données dans load() de OrbitalBaseManager');
345
			}
346
		}
347
348
		$orbitalBase->setRealGeneratorLevel($realGeneratorLevel);
349
		$orbitalBase->setRealRefineryLevel($realRefineryLevel);
350
		$orbitalBase->setRealDock1Level($realDock1Level);
351
		$orbitalBase->setRealDock2Level($realDock2Level);
352
		$orbitalBase->setRealDock3Level($realDock3Level);
353
		$orbitalBase->setRealTechnosphereLevel($realTechnosphereLevel);
354
		$orbitalBase->setRealCommercialPlateformeLevel($realCommercialPlateformeLevel);
355
		$orbitalBase->setRealStorageLevel($realStorageLevel);
356
		$orbitalBase->setRealRecyclingLevel($realRecyclingLevel);
357
		$orbitalBase->setRealSpatioportLevel($realSpatioportLevel);
358
359
		$orbitalBase->buildingQueues = $buildingQueues;
360
		$orbitalBase->technoQueues = $this->technologyQueueManager->getPlaceQueues($orbitalBase->getRPlace());
361
		$orbitalBase->commercialShippings = $this->commercialShippingManager->getByBase($orbitalBase->getRPlace());
0 ignored issues
show
Documentation introduced by
$orbitalBase->getRPlace() is of type integer, but the function expects a object<Asylamba\Modules\Athena\Manager\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
362
	}
363
364
	public function add(OrbitalBase $orbitalBase) {
365
		$this->entityManager->persist($orbitalBase);
366
		$this->entityManager->flush($orbitalBase);
367
	}
368
369
	public function changeOwnerById($id, $base, $newOwner, $baseCommanders) {
370
		if ($base->getId() == 0) {
371
			throw new ErrorException('Cette base orbitale n\'existe pas !');
372
		}
373
		# changement de possesseur des offres du marché
374
		$transactions = $this->transactionManager->getBasePropositions($base->rPlace);
375
376
		foreach ($transactions as $transaction) {
377
			# change owner of transaction
378
			$transaction->rPlayer = $newOwner;
379
380
			$commercialShipping = $this->commercialShippingManager->getByTransactionId($transaction->id);
381
			# change owner of commercial shipping
382
			$commercialShipping->rPlayer = $newOwner;
383
		}
384
385
		# attribuer le rPlayer à la Base
386
		$oldOwner = $base->rPlayer;
387
		$base->setRPlayer($newOwner);
388
389
		# suppression des routes commerciales
390
		$this->commercialRouteManager->removeBaseRoutes($base);
391
392
		# suppression des technologies en cours de développement
393
		foreach ($base->technoQueues as $queue) {
394
			$this->technologyQueueManager->remove($queue);
395
		}
396
397
		# suppression des missions de recyclages ainsi que des logs de recyclages
398
		$this->recyclingMissionManager->removeBaseMissions($base->getId());
399
400
		# mise des investissements à 0
401
		$base->iSchool = 0;
402
		$base->iAntiSpy = 0;
403
404
		# mise à jour de la date de création pour qu'elle soit dans l'ordre
405
		$base->dCreation = Utils::now();
406
407
		// If the new owner is connected, we add the base to his session
408
		if (($session = $this->clientManager->getSessionByPlayerId($newOwner)) !== null) {
409
			$session->addBase('ob', $base->getId(), $base->getName(), $base->getSector(), $base->getSystem(), '1-' . Game::getSizeOfPlanet($base->getPlanetPopulation()), $base->typeOfBase);
410
			$this->sessionWrapper->save($session);
411
		}
412
		// If the  previous owner is connected, we remove the base from his session
413
		if (($session = $this->clientManager->getSessionByPlayerId($oldOwner)) !== null) {
414
			$session->removeBase('ob', $base->getId());
415
			$this->sessionWrapper->save($session);
416
		}
417
418
		# rendre déserteuses les flottes en voyage
419
		foreach ($baseCommanders as $commander) {
420
			if (in_array($commander->statement, [Commander::INSCHOOL, Commander::ONSALE, Commander::RESERVE])) {
421
				$commander->rPlayer = $newOwner;
422
			} else if ($commander->statement == Commander::MOVING) {
423
                $this->commanderManager->endTravel($commander, Commander::RETIRED);
424
				$this->realtimeActionScheduler->cancel($commander, $commander->getArrivalDate());
425
			} else {
426
				$commander->statement = Commander::DEAD;		
427
			}
428
		}
429
430
		# vérifie si le joueur n'a plus de planète, si c'est le cas, il est mort, on lui redonne une planète
431
		$oldPlayerBases = $this->getPlayerBases($oldOwner);
432
		$nbOldPlayerBases = count($oldPlayerBases);
433
		if ($nbOldPlayerBases === 0 || ($nbOldPlayerBases === 1 && $oldPlayerBases[0]->rPlace === $id)) {
434
			$this->playerManager->reborn($oldOwner);
435
		}
436
        $this->entityManager->flush();
437
	}
438
	
439
	/**
440
	 * @param OrbitalBase $orbitalBase
441
	 * @return int
442
	 */
443
	public function updatePoints(OrbitalBase $orbitalBase) {
444
		$initialPoints = $orbitalBase->getPoints();
445
		$points = 0;
446
447
		for ($i = 0; $i < OrbitalBaseResource::BUILDING_QUANTITY; $i++) { 
448
			for ($j = 0; $j < $orbitalBase->getBuildingLevel($i); $j++) { 
449
				$points += $this->orbitalBaseHelper->getBuildingInfo($i, 'level', $j + 1, 'resourcePrice') / 1000;
450
			}
451
		}
452
453
		$points = round($points);
454
		$orbitalBase->setPoints($points);
455
		return $points - $initialPoints;
456
	}
457
	
458
	public function updateBases()
459
	{
460
		$repository = $this->entityManager->getRepository(OrbitalBase::class);
461
		$bases = $repository->getAll();
462
		$this->entityManager->beginTransaction();
463
		$now = Utils::now();
464
		
465
		foreach ($bases as $base) {
466
			# update time
467
			$hours = Utils::intervalDates($now, $base->uOrbitalBase);
468
469
			if (count($hours) === 0) {
470
				continue;
471
			}
472
			$player = $this->playerManager->get($base->rPlayer);
473
			$playerBonus = $this->playerBonusManager->getBonusByPlayer($player);
474
			$this->playerBonusManager->load($playerBonus);
475
			$base->setUpdatedAt($now);
476
			$initialResources = $base->resourcesStorage;
477
			$initialAntiSpyAverage = $base->antiSpyAverage;
478
			
479
			foreach ($hours as $hour) {
480
				$this->updateResources($base, $playerBonus);
481
				$this->updateAntiSpy($base);
482
			}
483
			
484
			$repository->updateBase(
0 ignored issues
show
Bug introduced by
The method updateBase() does not exist on Asylamba\Classes\Entity\AbstractRepository. Did you maybe mean update()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
485
				$base,
486
				$base->resourcesStorage - $initialResources,
487
				$base->antiSpyAverage - $initialAntiSpyAverage
488
			);
489
		}
490
		$this->entityManager->commit();
491
	}
492
	
493
	/**
494
	 * @param OrbitalBase $orbitalBase
495
	 * @param PlayerBonus $playerBonus
496
	 */
497
	protected function updateResources(OrbitalBase $orbitalBase, PlayerBonus $playerBonus)
498
	{
499
		$addResources = Game::resourceProduction($this->orbitalBaseHelper->getBuildingInfo(OrbitalBaseResource::REFINERY, 'level', $orbitalBase->levelRefinery, 'refiningCoefficient'), $orbitalBase->planetResources);
500
		$addResources += $addResources * $playerBonus->bonus->get(PlayerBonus::REFINERY_REFINING) / 100;
501
502
		$this->increaseResources($orbitalBase, (int) $addResources, false, false);
503
	}
504
	
505
	protected function updateAntiSpy(OrbitalBase $orbitalBase)
506
	{
507
		$orbitalBase->antiSpyAverage = round((($orbitalBase->antiSpyAverage * (24 - 1)) + ($orbitalBase->iAntiSpy)) / 24);
0 ignored issues
show
Documentation Bug introduced by
The property $antiSpyAverage was declared of type integer, but round(($orbitalBase->ant...alBase->iAntiSpy) / 24) is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
508
	}
509
	
510
	/**
511
	 * @param OrbitalBase $orbitalBase
512
	 * @param int $resources
513
	 * @param bool $offLimits
514
	 * @param bool $persist
515
	 */
516
	public function increaseResources(OrbitalBase $orbitalBase, $resources, $offLimits = false, $persist = true)
517
	{
518
		$playerBonus = $this->playerBonusManager->getBonusByPlayer($this->playerManager->get($orbitalBase->rPlayer));
519
		$this->playerBonusManager->load($playerBonus);
520
		$maxStorage = $this->orbitalBaseHelper->getBuildingInfo(OrbitalBaseResource::STORAGE, 'level', $orbitalBase->levelStorage, 'storageSpace');
521
		$maxStorage += $maxStorage * $playerBonus->bonus->get(PlayerBonus::REFINERY_STORAGE) / 100;
522
523
		if ($offLimits === true) {
524
			$maxStorage += OrbitalBase::EXTRA_STOCK;
525
		}
526
		$addedResources = 
527
			(($orbitalBase->resourcesStorage + $resources) > $maxStorage)
528
			? $maxStorage - $orbitalBase->resourcesStorage
529
			: $resources
530
		;
531
		$orbitalBase->resourcesStorage += $addedResources;
532
		if ($persist === true) {
533
			$this->entityManager->getRepository(OrbitalBase::class)->increaseResources(
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method increaseResources() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
534
				$orbitalBase,
535
				$addedResources
536
			);
537
		}
538
	}
539
	
540
	/**
541
	 * @param OrbitalBase $orbitalBase
542
	 * @param int $resources
543
	 */
544
	public function decreaseResources(OrbitalBase $orbitalBase, $resources)
545
	{
546
		$substractedResources = 
547
			(($orbitalBase->resourcesStorage - $resources) < 0)
548
			? abs(0 - $orbitalBase->resourcesStorage)
549
			: $resources
550
		;
551
		$orbitalBase->resourcesStorage -= $substractedResources;
552
		$this->entityManager->getRepository(OrbitalBase::class)->decreaseResources(
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method decreaseResources() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
553
			$orbitalBase,
554
			$substractedResources
555
		);
556
	}
557
558
	public function uBuildingQueue($queueId) {
559
		$queue = $this->buildingQueueManager->get($queueId);
560
		$orbitalBase = $this->get($queue->rOrbitalBase);
561
		$player = $this->playerManager->get($orbitalBase->rPlayer);
562
		# update builded building
563
		$orbitalBase->setBuildingLevel($queue->buildingNumber, ($orbitalBase->getBuildingLevel($queue->buildingNumber) + 1));
564
		# update the points of the orbitalBase
565
		$earnedPoints = $this->updatePoints($orbitalBase);
566
		$this->entityManager->getRepository(OrbitalBase::class)->increaseBuildingLevel(
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Asylamba\Classes\Entity\AbstractRepository as the method increaseBuildingLevel() does only exist in the following sub-classes of Asylamba\Classes\Entity\AbstractRepository: Asylamba\Modules\Athena\...y\OrbitalBaseRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
567
			$orbitalBase,
568
			$this->orbitalBaseHelper->getBuildingInfo($queue->buildingNumber, 'column'),
569
			$earnedPoints
570
		);
571
		# increase player experience
572
		$experience = $this->orbitalBaseHelper->getBuildingInfo($queue->buildingNumber, 'level', $queue->targetLevel, 'points');
573
		$this->playerManager->increaseExperience($player, $experience);
574
		
575
		# alert
576
		if (($session = $this->clientManager->getSessionByPlayerId($player->getId())) !== null) {
577
			$session->addFlashbag('Construction de votre <strong>' . $this->orbitalBaseHelper->getBuildingInfo($queue->buildingNumber, 'frenchName') . ' niveau ' . $queue->targetLevel . '</strong> sur <strong>' . $orbitalBase->name . '</strong> terminée. Vous gagnez ' . $experience . ' point' . Format::addPlural($experience) . ' d\'expérience.', Flashbag::TYPE_GENERATOR_SUCCESS);
578
			$this->sessionWrapper->save($session);
579
		}
580
		# delete queue in database
581
		$this->entityManager->remove($queue);
582
		$this->entityManager->flush($queue);
583
	}
584
585
	public function uShipQueue1($shipQueueId) {
586
		$queue = $this->shipQueueManager->get($shipQueueId);
587
		$orbitalBase = $this->get($queue->rOrbitalBase);
588
		$player = $this->playerManager->get($orbitalBase->rPlayer);
589
		# vaisseau construit
590
		$orbitalBase->setShipStorage($queue->shipNumber, $orbitalBase->getShipStorage($queue->shipNumber) + $queue->quantity);
591
		# increase player experience
592
		$experience = $queue->quantity * ShipResource::getInfo($queue->shipNumber, 'points');
593
		$this->playerManager->increaseExperience($player, $experience);
594
595
		# alert
596
		if (($session = $this->clientManager->getSessionByPlayerId($player->getId())) !== null) {
597
			$alt = 'Construction de ';
598
			if ($queue->quantity > 1) {
599
				$alt .= 'vos <strong>' . $queue->quantity . ' ' . ShipResource::getInfo($queue->shipNumber, 'codeName') . 's</strong>';
600
			} else {
601
				$alt .= 'votre <strong>' . ShipResource::getInfo($queue->shipNumber, 'codeName') . '</strong>';
602
			}
603
			$alt .= ' sur <strong>' . $orbitalBase->name . '</strong> terminée. Vous gagnez ' . $experience . ' point' . Format::addPlural($experience) . ' d\'expérience.';
604
			$session->addFlashbag($alt, Flashbag::TYPE_DOCK1_SUCCESS);
605
			$this->sessionWrapper->save($session);
606
		}
607
		$this->entityManager->remove($queue);
608
		$this->entityManager->flush();
609
	}
610
611
	public function uShipQueue2($shipQueueId) {
612
		$queue = $this->shipQueueManager->get($shipQueueId);
613
		$orbitalBase = $this->get($queue->rOrbitalBase);
614
		$player = $this->playerManager->get($orbitalBase->rPlayer);
615
		# vaisseau construit
616
		$orbitalBase->setShipStorage($queue->shipNumber, $orbitalBase->getShipStorage($queue->shipNumber) + 1);
617
		# increase player experience
618
		$experience = ShipResource::getInfo($queue->shipNumber, 'points');
619
		$this->playerManager->increaseExperience($player, $experience);
620
621
		# alert
622
		if (($session = $this->clientManager->getSessionByPlayerId($player->getId())) !== null) {
623
			$session->addFlashbag('Construction de votre ' . ShipResource::getInfo($queue->shipNumber, 'codeName') . ' sur ' . $orbitalBase->name . ' terminée. Vous gagnez ' . $experience . ' d\'expérience.', Flashbag::TYPE_DOCK2_SUCCESS);
624
			$this->sessionWrapper->save($session);
625
		}
626
		$this->entityManager->remove($queue);
627
		$this->entityManager->flush();
628
	}
629
630
	public function uTechnologyQueue($technologyQueueId) {
631
		$technologyQueue = $this->technologyQueueManager->get($technologyQueueId);
632
		$orbitalBase = $this->get($technologyQueue->getPlaceId());
0 ignored issues
show
Unused Code introduced by
$orbitalBase is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
633
		$player = $this->playerManager->get($technologyQueue->getPlayerId());
634
		# technologie construite
635
		$technology = $this->technologyManager->getPlayerTechnology($player->getId());
636
		$this->technologyManager->affectTechnology($technology, $technologyQueue->getTechnology(), $technologyQueue->getTargetLevel(), $player);
637
		# increase player experience
638
		$experience = $this->technologyHelper->getInfo($technologyQueue->getTechnology(), 'points', $technologyQueue->getTargetLevel());
639
		$this->playerManager->increaseExperience($player, $experience);
640
641
		# alert
642
		if (($session = $this->clientManager->getSessionByPlayerId($player->getId())) !== null) {
643
			$alt = 'Développement de votre technologie ' . $this->technologyHelper->getInfo($technologyQueue->getTechnology(), 'name');
644
			if ($technologyQueue->getTargetLevel() > 1) {
645
				$alt .= ' niveau ' . $technologyQueue->getTargetLevel();
646
			} 
647
			$alt .= ' terminée. Vous gagnez ' . $experience . ' d\'expérience.';
648
			$session->addFlashbag($alt, Flashbag::TYPE_TECHNOLOGY_SUCCESS);
649
			$this->sessionWrapper->save($session);
650
		}
651
		$this->entityManager->remove($technologyQueue);
652
		$this->entityManager->flush($technologyQueue);
653
	}
654
655
	public function uCommercialShipping($id) {
656
657
		$cs = $this->commercialShippingManager->get($id);
658
		$transaction = $this->transactionManager->get($cs->getTransactionId());
659
		$orbitalBase = $this->get($cs->getBaseId());
0 ignored issues
show
Unused Code introduced by
$orbitalBase is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
660
		$destOB = $this->get($cs->getDestinationBaseId());
661
		$commander =
662
			($transaction !== null && $transaction->type === Transaction::TYP_COMMANDER)
663
			? $this->commanderManager->get($transaction->identifier)
664
			: null
665
		;
666
667
		switch ($cs->statement) {
668
			case CommercialShipping::ST_GOING :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
669
				# shipping arrived, delivery of items to rBaseDestination
670
				$this->commercialShippingManager->deliver($cs, $transaction, $destOB, $commander);
671
				# prepare commercialShipping for moving back
672
				$cs->statement = CommercialShipping::ST_MOVING_BACK;
673
				$timeToTravel = strtotime($cs->dArrival) - strtotime($cs->dDeparture);
674
				$cs->dDeparture = $cs->dArrival;
675
				$cs->dArrival = Utils::addSecondsToDate($cs->dArrival, $timeToTravel);
676
				$this->realtimeActionScheduler->schedule('athena.orbital_base_manager', 'uCommercialShipping', $cs, $cs->dArrival);
0 ignored issues
show
Documentation introduced by
$cs is of type object<Asylamba\Modules\...del\CommercialShipping>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
677
				break;
678
			case CommercialShipping::ST_MOVING_BACK :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
679
				# shipping arrived, release of the commercial ships
680
				# send notification
681
				$n = new Notification();
682
				$n->setRPlayer($cs->rPlayer);
683
				$n->setTitle('Retour de livraison');
684
				if ($cs->shipQuantity == 1) {
685
					$n->addBeg()->addTxt('Votre vaisseau commercial est de retour sur votre ');
686
				} else {
687
					$n->addBeg()->addTxt('Vos vaisseaux commerciaux sont de retour sur votre ');
688
				}
689
				$n->addLnk('map/place-' . $cs->rBase, 'base orbitale')->addTxt(' après avoir livré du matériel sur une autre ');
690
				$n->addLnk('map/place-' . $cs->rBaseDestination, 'base')->addTxt(' . ');
691
				if ($cs->shipQuantity == 1) {
692
					$n->addSep()->addTxt('Votre vaisseau de commerce est à nouveau disponible pour faire d\'autres transactions ou routes commerciales.');
693
				} else {
694
					$n->addSep()->addTxt('Vos ' . $cs->shipQuantity . ' vaisseaux de commerce sont à nouveau disponibles pour faire d\'autres transactions ou routes commerciales.');
695
				}
696
				$n->addEnd();
697
				$this->notificationManager->add($n);
698
				# delete commercialShipping
699
				$this->entityManager->remove($cs);
700
				break;
701
			default :break;
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
702
		}
703
		$this->entityManager->flush();
704
	}
705
706
	public function uRecycling($missionId) {
707
		$mission = $this->recyclingMissionManager->get($missionId);
708
		$orbitalBase = $this->get($mission->rBase);
709
		$targetPlace = $this->placeManager->get($mission->rTarget);
710
		
711
		$player = $this->playerManager->get($orbitalBase->getRPlayer());
712
		if ($targetPlace->typeOfPlace != Place::EMPTYZONE) {
713
			# make the recycling : decrease resources on the target place
714
			$totalRecycled = $mission->recyclerQuantity * RecyclingMission::RECYCLER_CAPACTIY;
715
			$targetPlace->resources -= $totalRecycled;
716
			# if there is no more resource
717
			if ($targetPlace->resources <= 0) {
718
                // Avoid out of range errors
719
                $targetPlace->resources = 0;
720
				# the place become an empty place
721
				$this->placeManager->turnAsEmptyPlace($targetPlace);
722
723
				# stop the mission
724
				$mission->statement = RecyclingMission::ST_DELETED;
725
726
				# send notification to the player
727
				$n = new Notification();
728
				$n->setRPlayer($player->id);
729
				$n->setTitle('Arrêt de mission de recyclage');
730
				$n->addBeg()->addTxt('Un ');
731
				$n->addLnk('map/place-' . $mission->rTarget, 'lieu');
732
				$n->addTxt(' que vous recycliez est désormais totalement dépourvu de ressources et s\'est donc transformé en lieu vide.');
733
				$n->addSep()->addTxt('Vos recycleurs restent donc stationnés sur votre ');
734
				$n->addLnk('map/place-' . $orbitalBase->rPlace, 'base orbitale')->addTxt(' le temps que vous programmiez une autre mission.');
735
				$n->addEnd();
736
				$this->notificationManager->add($n);
737
			}
738
739
			# if the sector change its color between 2 recyclings
740
			if ($player->rColor != $targetPlace->sectorColor && $targetPlace->sectorColor != ColorResource::NO_FACTION) {
741
				# stop the mission
742
				$mission->statement = RecyclingMission::ST_DELETED;
743
744
				# send notification to the player
745
				$n = new Notification();
746
				$n->setRPlayer($player->id);
747
				$n->setTitle('Arrêt de mission de recyclage');
748
				$n->addBeg()->addTxt('Le secteur d\'un ');
749
				$n->addLnk('map/place-' . $mission->rTarget, 'lieu');
750
				$n->addTxt(' que vous recycliez est passé à l\'ennemi, vous ne pouvez donc plus y envoyer vos recycleurs. La mission est annulée.');
751
				$n->addSep()->addTxt('Vos recycleurs restent donc stationnés sur votre ');
752
				$n->addLnk('map/place-' . $orbitalBase->rPlace, 'base orbitale')->addTxt(' le temps que vous programmiez une autre mission.');
753
				$n->addEnd();
754
				$this->notificationManager->add($n);
755
			}
756
757
			$creditRecycled = round($targetPlace->population * $totalRecycled * 10 / 100);
758
			$resourceRecycled = round($targetPlace->coefResources * $totalRecycled / 100);
759
			$shipRecycled = round($targetPlace->coefHistory * $totalRecycled / 100);
760
761
			# diversify a little (resource and credit)
762
			$percent = rand(-5, 5);
763
			$diffAmountCredit = round($creditRecycled * $percent / 100);
764
			$diffAmountResource = round($resourceRecycled * $percent / 100);
765
			$creditRecycled += $diffAmountCredit;
766
			$resourceRecycled -= $diffAmountResource;
767
768
			if ($creditRecycled < 0) { $creditRecycled = 0; }
769
			if ($resourceRecycled < 0) { $resourceRecycled = 0; }
770
771
			# convert shipRecycled to real ships
772
			$pointsToRecycle = round($shipRecycled * RecyclingMission::COEF_SHIP);
773
			$shipsArray1 = array();
774
			$buyShip = array();
775
			for ($i = 0; $i < ShipResource::SHIP_QUANTITY; $i++) { 
776
				if (floor($pointsToRecycle / ShipResource::getInfo($i, 'resourcePrice')) > 0) {
777
					$shipsArray1[] = array(
778
						'ship' => $i,
779
						'price' => ShipResource::getInfo($i, 'resourcePrice'),
780
						'canBuild' => TRUE);
781
				}
782
				$buyShip[] = 0;
783
			}
784
785
			shuffle($shipsArray1);
786
			$shipsArray = array();
787
			$onlyThree = 0;
788
			foreach ($shipsArray1 as $key => $value) {
789
				$onlyThree++;
790
				$shipsArray[] = $value;
791
				if ($onlyThree == 3) {
792
					break;
793
				}
794
			}
795
			$continue = TRUE;
796
			if (count($shipsArray) > 0) {
797
				while($continue) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after WHILE keyword; 0 found
Loading history...
798
					foreach ($shipsArray as $key => $line) {
799
						if ($line['canBuild']) {
800
							$nbmax = floor($pointsToRecycle / $line['price']);
801
							if ($nbmax < 1) {
802
								$shipsArray[$key]['canBuild'] = FALSE;
803
							} else {
804
								$qty = rand(1, $nbmax);
805
								$pointsToRecycle -= $qty * $line['price'];
806
								$buyShip[$line['ship']] += $qty;
807
							}
808
						}
809
					}
810
811
					$canBuild = FALSE;
812
					# verify if we can build one more ship
813
					foreach ($shipsArray as $key => $line) {
814
						if ($line['canBuild']) {
815
							$canBuild = TRUE;
816
							break;
817
						}
818
					}
819
					if (!$canBuild) {
820
						# if the 3 types of ships can't be build anymore --> stop
821
						$continue = FALSE;
822
					}
823
				}
824
			}
825
826
			# create a RecyclingLog
827
			$rl = new RecyclingLog();
828
			$rl->rRecycling = $mission->id;
829
			$rl->resources = $resourceRecycled;
0 ignored issues
show
Documentation Bug introduced by
It seems like $resourceRecycled can also be of type double. However, the property $resources is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
830
			$rl->credits = $creditRecycled;
0 ignored issues
show
Documentation Bug introduced by
It seems like $creditRecycled can also be of type double. However, the property $credits is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
831
			$rl->ship0 = $buyShip[0];
832
			$rl->ship1 = $buyShip[1];
833
			$rl->ship2 = $buyShip[2];
834
			$rl->ship3 = $buyShip[3];
835
			$rl->ship4 = $buyShip[4];
836
			$rl->ship5 = $buyShip[5];
837
			$rl->ship6 = $buyShip[6];
838
			$rl->ship7 = $buyShip[7];
839
			$rl->ship8 = $buyShip[8];
840
			$rl->ship9 = $buyShip[9];
841
			$rl->ship10 = $buyShip[10];
842
			$rl->ship11 = $buyShip[11];
843
			$rl->dLog = Utils::addSecondsToDate($mission->uRecycling, $mission->cycleTime);
0 ignored issues
show
Documentation Bug introduced by
The property $dLog was declared of type integer, but \Asylamba\Classes\Librar...g, $mission->cycleTime) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
844
			$this->recyclingLogManager->add($rl);
845
846
			# give to the orbitalBase ($orbitalBase) and player what was recycled
847
			$this->increaseResources($orbitalBase, $resourceRecycled);
848
			for ($i = 0; $i < ShipResource::SHIP_QUANTITY; $i++) { 
849
				$this->addShipToDock($orbitalBase, $i, $buyShip[$i]);
850
			}
851
			$this->playerManager->increaseCredit($player, $creditRecycled);
852
853
			# add recyclers waiting to the mission
854
			$mission->recyclerQuantity += $mission->addToNextMission;
855
			$mission->addToNextMission = 0;
856
857
			# if a mission is stopped by the user, delete it
858
			if ($mission->statement == RecyclingMission::ST_BEING_DELETED) {
859
				$mission->statement = RecyclingMission::ST_DELETED;
860
			}
861
862
			# update u
863
			$mission->uRecycling = Utils::addSecondsToDate($mission->uRecycling, $mission->cycleTime);
864
			// Schedule the next mission if there is still resources
865
            if ($mission->getStatement() !== RecyclingMission::ST_DELETED) {
866
                $this->realtimeActionScheduler->schedule('athena.orbital_base_manager', 'uRecycling', $mission, $mission->uRecycling);
0 ignored issues
show
Documentation introduced by
$mission is of type object<Asylamba\Modules\...Model\RecyclingMission>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
867
            }
868
		} else {
869
			# the place become an empty place
870
			$targetPlace->resources = 0;
871
872
			# stop the mission
873
			$mission->statement = RecyclingMission::ST_DELETED;
874
875
			# send notification to the player
876
			$n = new Notification();
877
			$n->setRPlayer($player->id);
878
			$n->setTitle('Arrêt de mission de recyclage');
879
			$n->addBeg()->addTxt('Un ');
880
			$n->addLnk('map/place-' . $mission->rTarget, 'lieu');
881
			$n->addTxt(' que vous recycliez est désormais totalement dépourvu de ressources et s\'est donc transformé en lieu vide.');
882
			$n->addSep()->addTxt('Vos recycleurs restent donc stationnés sur votre ');
883
			$n->addLnk('map/place-' . $orbitalBase->rPlace, 'base orbitale')->addTxt(' le temps que vous programmiez une autre mission.');
884
			$n->addEnd();
885
			$this->notificationManager->add($n);
886
		}
887
		$this->entityManager->flush();
888
	}
889
890
	public function addShipToDock(OrbitalBase $orbitalBase, $shipId, $quantity) {
891
		if ($this->orbitalBaseHelper->isAShipFromDock1($shipId) OR $this->orbitalBaseHelper->isAShipFromDock2($shipId)) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected or, but found OR.
Loading history...
892
			$orbitalBase->setShipStorage($shipId, $orbitalBase->getShipStorage($shipId) + $quantity);
893
			$this->entityManager->flush($orbitalBase);
894
			return TRUE;
895
		} else {
896
			return FALSE;
897
		}
898
	}
899
900
	public function removeShipFromDock(OrbitalBase $orbitalBase, $shipId, $quantity) {
901
		if ($this->orbitalBaseHelper->isAShipFromDock1($shipId) OR $this->orbitalBaseHelper->isAShipFromDock2($shipId)) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected or, but found OR.
Loading history...
902
			if ($orbitalBase->getShipStorage($shipId) >= $quantity) {
903
				$orbitalBase->setShipStorage($shipId, $orbitalBase->getShipStorage($shipId) - $quantity);
904
				$this->entityManager->flush($orbitalBase);
905
				return TRUE;
906
			} else {
907
				return FALSE;
908
			}
909
		}
910
	}
911
}