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.
Completed
Push — master ( 11c0a1...856a6b )
by Jacky
34s
created

OrbitalBaseManager::uBuildingQueue()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 16
nc 2
nop 1
dl 0
loc 25
rs 8.8571
c 0
b 0
f 0
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\Gaia\Manager\GalaxyColorManager;
23
use Asylamba\Modules\Athena\Model\Transaction;
24
use Asylamba\Modules\Ares\Model\Commander;
25
use Asylamba\Modules\Athena\Model\OrbitalBase;
26
use Asylamba\Modules\Gaia\Model\System;
27
use Asylamba\Modules\Athena\Manager\BuildingQueueManager;
28
use Asylamba\Modules\Athena\Manager\ShipQueueManager;
29
use Asylamba\Modules\Promethee\Manager\TechnologyQueueManager;
30
use Asylamba\Modules\Promethee\Manager\TechnologyManager;
31
use Asylamba\Modules\Athena\Manager\CommercialShippingManager;
32
use Asylamba\Modules\Athena\Manager\CommercialRouteManager;
33
use Asylamba\Modules\Zeus\Manager\PlayerManager;
34
use Asylamba\Modules\Zeus\Manager\PlayerBonusManager;
35
use Asylamba\Modules\Athena\Manager\RecyclingMissionManager;
36
use Asylamba\Modules\Athena\Manager\RecyclingLogManager;
37
use Asylamba\Modules\Gaia\Manager\PlaceManager;
38
use Asylamba\Modules\Ares\Manager\CommanderManager;
39
use Asylamba\Modules\Hermes\Manager\NotificationManager;
40
use Asylamba\Modules\Athena\Helper\OrbitalBaseHelper;
41
use Asylamba\Modules\Demeter\Resource\ColorResource;
42
43
use Asylamba\Modules\Athena\Model\RecyclingMission;
44
use Asylamba\Modules\Athena\Model\RecyclingLog;
45
use Asylamba\Modules\Zeus\Model\PlayerBonus;
46
use Asylamba\Modules\Gaia\Model\Place;
47
use Asylamba\Modules\Zeus\Model\Player;
48
use Asylamba\Modules\Athena\Model\CommercialShipping;
49
use Asylamba\Modules\Hermes\Model\Notification;
50
51
use Asylamba\Modules\Athena\Resource\OrbitalBaseResource;
52
use Asylamba\Modules\Promethee\Helper\TechnologyHelper;
53
use Asylamba\Modules\Athena\Resource\ShipResource;
54
use Asylamba\Classes\Library\Flashbag;
55
56
use Asylamba\Classes\Scheduler\RealTimeActionScheduler;
57
58
class OrbitalBaseManager {
59
	/** @var EntityManager **/
60
	protected $entityManager;
61
	/** @var RealTimeActionScheduler **/
62
	protected $realtimeActionScheduler;
63
	/** @var BuildingQueueManager **/
64
	protected $buildingQueueManager;
65
	/** @var ShipQueueManager **/
66
	protected $shipQueueManager;
67
	/** @var TechnologyQueueManager **/
68
	protected $technologyQueueManager;
69
	/** @var TechnologyManager **/
70
	protected $technologyManager;
71
	/** @var TechnologyHelper **/
72
	protected $technologyHelper;
73
	/** @var CommercialShippingManager **/
74
	protected $commercialShippingManager;
75
	/** @var CommercialRouteManager **/
76
	protected $commercialRouteManager;
77
	/** @var TransactionManager **/
78
	protected $transactionManager;
79
	/** @var GalaxyColorManager **/
80
	protected $galaxyColorManager;
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 $session;
101
	
102
	/**
103
	 * @param EntityManager $entityManager
104
	 * @param RealTimeActionScheduler $realtimeActionScheduler
105
	 * @param BuildingQueueManager $buildingQueueManager
106
	 * @param ShipQueueManager $shipQueueManager
107
	 * @param TechnologyQueueManager $technologyQueueManager
108
	 * @param TechnologyHelper $technologyHelper
109
	 * @param CommercialShippingManager $commercialShippingManager
110
	 * @param CommercialRouteManager $commercialRouteManager
111
	 * @param TransactionManager $transactionManager
112
	 * @param GalaxyColorManager $galaxyColorManager
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 $session
122
	 */
123
	public function __construct(
124
		EntityManager $entityManager,
125
		RealTimeActionScheduler $realtimeActionScheduler,
126
		BuildingQueueManager $buildingQueueManager,
127
		ShipQueueManager $shipQueueManager,
128
		TechnologyQueueManager $technologyQueueManager,
129
		TechnologyManager $technologyManager,
130
		TechnologyHelper $technologyHelper,
131
		CommercialShippingManager $commercialShippingManager,
132
		CommercialRouteManager $commercialRouteManager,
133
		TransactionManager $transactionManager,
134
		GalaxyColorManager $galaxyColorManager,
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 $session
145
	) {
146
		$this->entityManager = $entityManager;
147
		$this->realtimeActionScheduler = $realtimeActionScheduler;
148
		$this->buildingQueueManager = $buildingQueueManager;
149
		$this->shipQueueManager = $shipQueueManager;
150
		$this->technologyQueueManager = $technologyQueueManager;
151
		$this->technologyManager = $technologyManager;
152
		$this->technologyHelper = $technologyHelper;
153
		$this->commercialShippingManager = $commercialShippingManager;
154
		$this->commercialRouteManager = $commercialRouteManager;
155
		$this->transactionManager = $transactionManager;
156
		$this->galaxyColorManager = $galaxyColorManager;
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->session = $session;
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\...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
		$this->uMethod($orbitalBase);
364
	}
365
366
	public function add(OrbitalBase $orbitalBase) {
367
		$this->entityManager->persist($orbitalBase);
368
		$this->entityManager->flush($orbitalBase);
369
	}
370
371
	public function changeOwnerById($id, $base, $newOwner, $baseCommanders) {
372
		if ($base->getId() == 0) {
373
			throw new ErrorException('Cette base orbitale n\'existe pas !');
374
		}
375
		# changement de possesseur des offres du marché
376
		$transactions = $this->transactionManager->getBasePropositions($base->rPlace);
377
378
		foreach ($transactions as $transaction) {
379
			# change owner of transaction
380
			$transaction->rPlayer = $newOwner;
381
382
			$commercialShipping = $this->commercialShippingManager->getByTransactionId($transaction->id);
383
			# change owner of commercial shipping
384
			$commercialShipping->rPlayer = $newOwner;
385
		}
386
387
		# attribuer le rPlayer à la Base
388
		$oldOwner = $base->rPlayer;
389
		$base->setRPlayer($newOwner);
390
391
		# suppression des routes commerciales
392
		$this->commercialRouteManager->removeBaseRoutes($base);
393
394
		# suppression des technologies en cours de développement
395
		foreach ($base->technoQueues as $queue) { 
396
			$this->entityManager->remove($queue);
397
		}
398
		$this->entityManager->flush(TechnologyQueue::class);
399
400
		# suppression des missions de recyclages ainsi que des logs de recyclages
401
		$S_REM1 = $this->recyclingMissionManager->getCurrentSession();
402
		$this->recyclingMissionManager->newSession();
403
		$this->recyclingMissionManager->load(array('rBase' => $base->getId()));
404
		for ($i = $this->recyclingMissionManager->size() - 1; $i >= 0; $i--) {
405
			$this->recyclingLogManager->deleteAllFromMission($this->recyclingMissionManager->get($i)->id);
406
			$this->recyclingMissionManager->deleteById($this->recyclingMissionManager->get($i)->id);
407
		}
408
		$this->recyclingMissionManager->changeSession($S_REM1);
409
410
		# mise des investissements à 0
411
		$base->iSchool = 0;
412
		$base->iAntiSpy = 0;
413
414
		# mise à jour de la date de création pour qu'elle soit dans l'ordre
415
		$base->dCreation = Utils::now();
416
417
		# ajouter/enlever la base dans le controller
418
		if ($this->session->get('playerId') == $newOwner) {
419
			$this->session->addBase('ob', $base->getId(), $base->getName(), $base->getSector(), $base->getSystem(), '1-' . Game::getSizeOfPlanet($base->getPlanetPopulation()), $base->typeOfBase);
420
		} else {
421
			$this->session->removeBase('ob', $base->getId());
422
		}
423
424
		# rendre déserteuses les flottes en voyage
425
		foreach ($baseCommanders as $commander) {
426
			if (in_array($commander->statement, [Commander::INSCHOOL, Commander::ONSALE, Commander::RESERVE])) {
427
				$commander->rPlayer = $newOwner;
428
			} else if ($commander->statement == Commander::MOVING) {
429
				$commander->statement = Commander::RETIRED;
430
			} else {
431
				$commander->statement = Commander::DEAD;		
432
			}
433
		}
434
435
		# 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
436
		$oldPlayerBases = $this->getPlayerBases($oldOwner);
437
		$nbOldPlayerBases = count($oldPlayerBases);
438
		if ($nbOldPlayerBases === 0 || ($nbOldPlayerBases === 1 && $oldPlayerBases[0]->rPlace === $id)) {
439
			$this->playerManager->reborn($oldOwner);
440
		}
441
        $this->entityManager->flush();
442
	}
443
	
444
	/**
445
	 * @param OrbitalBase $orbitalBase
446
	 * @return int
447
	 */
448
	public function updatePoints(OrbitalBase $orbitalBase) {
449
		$initialPoints = $orbitalBase->getPoints();
450
		$points = 0;
451
452
		for ($i = 0; $i < OrbitalBaseResource::BUILDING_QUANTITY; $i++) { 
453
			for ($j = 0; $j < $orbitalBase->getBuildingLevel($i); $j++) { 
454
				$points += $this->orbitalBaseHelper->getBuildingInfo($i, 'level', $j + 1, 'resourcePrice') / 1000;
455
			}
456
		}
457
458
		$points = round($points);
459
		$orbitalBase->setPoints($points);
460
		return $points - $initialPoints;
461
	}
462
463
	// UPDATE METHODS
464
	public function uMethod(OrbitalBase $orbitalBase) {
465
		$token = $this->ctc->createContext('orbitalbase');
466
		$now   = Utils::now();
467
468
		if (Utils::interval($orbitalBase->uOrbitalBase, $now, 's') > 0) {
469
			# RECYCLING MISSION
470
			$S_REM1 = $this->recyclingMissionManager->getCurrentSession();
471
			$this->recyclingMissionManager->newSession(ASM_UMODE);
472
			$this->recyclingMissionManager->load(array('rBase' => $orbitalBase->rPlace, 'statement' => array(RecyclingMission::ST_ACTIVE, RecyclingMission::ST_BEING_DELETED)));
473
			for ($i = 0; $i < $this->recyclingMissionManager->size(); $i++) { 
474
				$mission = $this->recyclingMissionManager->get($i);
475
476
				$interval = Utils::interval($mission->uRecycling, $now, 's');
477
				if ($interval > $mission->cycleTime) {
478
					# update time
479
					$recyclingQuantity = floor($interval / $mission->cycleTime);
480
481
					# Place
482
					$place = $this->placeManager->get($mission->rTarget);
483
484
					for ($j = 0; $j < $recyclingQuantity; $j++) { 
485
						$dateOfUpdate = Utils::addSecondsToDate($mission->uRecycling, ($j + 1) * $mission->cycleTime);
486
						$this->ctc->add($dateOfUpdate, $this, 'uRecycling', $mission, array($orbitalBase, $mission, $place, $dateOfUpdate));
487
					}
488
				}
489
			}
490
			$this->recyclingMissionManager->changeSession($S_REM1);
491
		}
492
493
		$this->ctc->applyContext($token);
494
		$this->entityManager->flush($orbitalBase);
495
	}
496
	
497
	public function updateBases()
498
	{
499
		$repository = $this->entityManager->getRepository(OrbitalBase::class);
500
		$bases = $repository->getAll();
501
		$this->entityManager->beginTransaction();
502
		$now = Utils::now();
503
		
504
		foreach ($bases as $base) {
505
			# update time
506
			$hours = Utils::intervalDates($now, $base->uOrbitalBase);
507
508
			if (count($hours) === 0) {
509
				continue;
510
			}
511
			$player = $this->playerManager->get($base->rPlayer);
512
			$playerBonus = $this->playerBonusManager->getBonusByPlayer($player);
513
			$this->playerBonusManager->load($playerBonus);
514
			$base->setUpdatedAt($now);
515
			$initialResources = $base->resourcesStorage;
516
			$initialAntiSpyAverage = $base->antiSpyAverage;
517
			
518
			foreach ($hours as $hour) {
519
				$this->updateResources($base, $playerBonus);
520
				$this->updateAntiSpy($base);
521
			}
522
			
523
			$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...
524
				$base,
525
				$base->resourcesStorage - $initialResources,
526
				$base->antiSpyAverage - $initialAntiSpyAverage
527
			);
528
		}
529
		$this->entityManager->commit();
530
	}
531
	
532
	/**
533
	 * @param OrbitalBase $orbitalBase
534
	 * @param PlayerBonus $playerBonus
535
	 */
536
	protected function updateResources(OrbitalBase $orbitalBase, PlayerBonus $playerBonus)
537
	{
538
		$addResources = Game::resourceProduction($this->orbitalBaseHelper->getBuildingInfo(OrbitalBaseResource::REFINERY, 'level', $orbitalBase->levelRefinery, 'refiningCoefficient'), $orbitalBase->planetResources);
539
		$addResources += $addResources * $playerBonus->bonus->get(PlayerBonus::REFINERY_REFINING) / 100;
540
541
		$this->increaseResources($orbitalBase, (int) $addResources, false, false);
542
	}
543
	
544
	protected function updateAntiSpy(OrbitalBase $orbitalBase)
545
	{
546
		$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...
547
	}
548
	
549
	/**
550
	 * @param OrbitalBase $orbitalBase
551
	 * @param int $resources
552
	 * @param bool $offLimits
553
	 * @param bool $persist
554
	 */
555
	public function increaseResources(OrbitalBase $orbitalBase, $resources, $offLimits = false, $persist = true)
556
	{
557
		$playerBonus = $this->playerBonusManager->getBonusByPlayer($this->playerManager->get($orbitalBase->rPlayer));
558
		$this->playerBonusManager->load($playerBonus);
559
		$maxStorage = $this->orbitalBaseHelper->getBuildingInfo(OrbitalBaseResource::STORAGE, 'level', $orbitalBase->levelStorage, 'storageSpace');
560
		$maxStorage += $maxStorage * $playerBonus->bonus->get(PlayerBonus::REFINERY_STORAGE) / 100;
561
562
		if ($offLimits === true) {
563
			$maxStorage += OrbitalBase::EXTRA_STOCK;
564
		}
565
		$addedResources = 
566
			(($orbitalBase->resourcesStorage + $resources) > $maxStorage)
567
			? $maxStorage - $orbitalBase->resourcesStorage
568
			: $resources
569
		;
570
		$orbitalBase->resourcesStorage += $addedResources;
571
		if ($persist === true) {
572
			$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...
573
				$orbitalBase,
574
				$addedResources
575
			);
576
		}
577
	}
578
	
579
	/**
580
	 * @param OrbitalBase $orbitalBase
581
	 * @param int $resources
582
	 */
583
	public function decreaseResources(OrbitalBase $orbitalBase, $resources)
584
	{
585
		$substractedResources = 
586
			(($orbitalBase->resourcesStorage - $resources) < 0)
587
			? abs(0 - $orbitalBase->resourcesStorage)
588
			: $resources
589
		;
590
		$orbitalBase->resourcesStorage -= $substractedResources;
591
		$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...
592
			$orbitalBase,
593
			$substractedResources
594
		);
595
	}
596
597
	public function uBuildingQueue($queueId) {
598
		$queue = $this->buildingQueueManager->get($queueId);
599
		$orbitalBase = $this->get($queue->rOrbitalBase);
600
		$player = $this->playerManager->get($orbitalBase->rPlayer);
601
		# update builded building
602
		$orbitalBase->setBuildingLevel($queue->buildingNumber, ($orbitalBase->getBuildingLevel($queue->buildingNumber) + 1));
603
		# update the points of the orbitalBase
604
		$earnedPoints = $this->updatePoints($orbitalBase);
605
		$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...
606
			$orbitalBase,
607
			$this->orbitalBaseHelper->getBuildingInfo($queue->buildingNumber, 'column'),
608
			$earnedPoints
609
		);
610
		# increase player experience
611
		$experience = $this->orbitalBaseHelper->getBuildingInfo($queue->buildingNumber, 'level', $queue->targetLevel, 'points');
612
		$this->playerManager->increaseExperience($player, $experience);
613
		
614
		# alert
615
		if ($this->session->get('playerId') == $orbitalBase->rPlayer) {
616
			$this->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);
617
		}
618
		# delete queue in database
619
		$this->entityManager->remove($queue);
620
		$this->entityManager->flush($queue);
621
	}
622
623
	public function uShipQueue1($shipQueueId) {
624
		$queue = $this->shipQueueManager->get($shipQueueId);
625
		$orbitalBase = $this->get($queue->rOrbitalBase);
626
		$player = $this->playerManager->get($orbitalBase->rPlayer);
627
		# vaisseau construit
628
		$orbitalBase->setShipStorage($queue->shipNumber, $orbitalBase->getShipStorage($queue->shipNumber) + $queue->quantity);
629
		# increase player experience
630
		$experience = $queue->quantity * ShipResource::getInfo($queue->shipNumber, 'points');
631
		$this->playerManager->increaseExperience($player, $experience);
632
633
		# alert
634
		if ($this->session->get('playerId') == $orbitalBase->rPlayer) {
635
			$alt = 'Construction de ';
636
			if ($queue->quantity > 1) {
637
				$alt .= 'vos <strong>' . $queue->quantity . ' ' . ShipResource::getInfo($queue->shipNumber, 'codeName') . 's</strong>';
638
			} else {
639
				$alt .= 'votre <strong>' . ShipResource::getInfo($queue->shipNumber, 'codeName') . '</strong>';
640
			}
641
			$alt .= ' sur <strong>' . $orbitalBase->name . '</strong> terminée. Vous gagnez ' . $experience . ' point' . Format::addPlural($experience) . ' d\'expérience.';
642
			$this->session->addFlashbag($alt, Flashbag::TYPE_DOCK1_SUCCESS);
643
		}
644
		$this->entityManager->remove($queue);
645
		$this->entityManager->flush();
646
	}
647
648
	public function uShipQueue2($shipQueueId) {
649
		$queue = $this->shipQueueManager->get($shipQueueId);
650
		$orbitalBase = $this->get($queue->rOrbitalBase);
651
		$player = $this->playerManager->get($orbitalBase->rPlayer);
652
		# vaisseau construit
653
		$orbitalBase->setShipStorage($queue->shipNumber, $orbitalBase->getShipStorage($queue->shipNumber) + 1);
654
		# increase player experience
655
		$experience = ShipResource::getInfo($queue->shipNumber, 'points');
656
		$this->playerManager->increaseExperience($player, $experience);
657
658
		# alert
659
		if ($this->session->get('playerId') == $orbitalBase->rPlayer) {
660
			$this->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);
661
		}
662
		$this->entityManager->remove($queue);
663
		$this->entityManager->flush();
664
	}
665
666
	public function uTechnologyQueue($technologyQueueId) {
667
		$technologyQueue = $this->technologyQueueManager->get($technologyQueueId);
668
		$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...
669
		$player = $this->playerManager->get($technologyQueue->getPlayerId());
670
		# technologie construite
671
		$technology = $this->technologyManager->getPlayerTechnology($player->getId());
672
		$this->technologyManager->affectTechnology($technology, $technologyQueue->getTechnology(), $technologyQueue->getTargetLevel(), $player);
673
		# increase player experience
674
		$experience = $this->technologyHelper->getInfo($technologyQueue->getTechnology(), 'points', $technologyQueue->getTargetLevel());
675
		$this->playerManager->increaseExperience($player, $experience);
676
677
		# alert
678
//		if ($this->session->get('playerId') == $orbitalBase->rPlayer) {
679
//			$alt = 'Développement de votre technologie ' . $this->technologyHelper->getInfo($technologyQueue->getTechnology(), 'name');
680
//			if ($technologyQueue->getTargetLevel() > 1) {
681
//				$alt .= ' niveau ' . $technologyQueue->getTargetLevel();
682
//			} 
683
//			$alt .= ' terminée. Vous gagnez ' . $experience . ' d\'expérience.';
684
//			$this->session->addFlashbag($alt, Flashbag::TYPE_TECHNOLOGY_SUCCESS);
685
//		}
686
		$this->entityManager->remove($technologyQueue);
687
		$this->entityManager->flush($technologyQueue);
688
	}
689
690
	public function uCommercialShipping($id) {
691
692
		$cs = $this->commercialShippingManager->get($id);
693
		$transaction = $this->transactionManager->get($cs->getTransactionId());
694
		$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...
695
		$destOB = $this->get($cs->getDestinationBaseId());
696
		$commander =
697
			($transaction !== null && $transaction->type === Transaction::TYP_COMMANDER)
698
			? $this->commanderManager->get($transaction->identifier)
699
			: null
700
		;
701
702
		switch ($cs->statement) {
703
			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...
704
				# shipping arrived, delivery of items to rBaseDestination
705
				$this->commercialShippingManager->deliver($cs, $transaction, $destOB, $commander);
706
				# prepare commercialShipping for moving back
707
				$cs->statement = CommercialShipping::ST_MOVING_BACK;
708
				$timeToTravel = strtotime($cs->dArrival) - strtotime($cs->dDeparture);
709
				$cs->dDeparture = $cs->dArrival;
710
				$cs->dArrival = Utils::addSecondsToDate($cs->dArrival, $timeToTravel);
711
				break;
712
			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...
713
				# shipping arrived, release of the commercial ships
714
				# send notification
715
				$n = new Notification();
716
				$n->setRPlayer($cs->rPlayer);
717
				$n->setTitle('Retour de livraison');
718
				if ($cs->shipQuantity == 1) {
719
					$n->addBeg()->addTxt('Votre vaisseau commercial est de retour sur votre ');
720
				} else {
721
					$n->addBeg()->addTxt('Vos vaisseaux commerciaux sont de retour sur votre ');
722
				}
723
				$n->addLnk('map/place-' . $cs->rBase, 'base orbitale')->addTxt(' après avoir livré du matériel sur une autre ');
724
				$n->addLnk('map/place-' . $cs->rBaseDestination, 'base')->addTxt(' . ');
725
				if ($cs->shipQuantity == 1) {
726
					$n->addSep()->addTxt('Votre vaisseau de commerce est à nouveau disponible pour faire d\'autres transactions ou routes commerciales.');
727
				} else {
728
					$n->addSep()->addTxt('Vos ' . $cs->shipQuantity . ' vaisseaux de commerce sont à nouveau disponibles pour faire d\'autres transactions ou routes commerciales.');
729
				}
730
				$n->addEnd();
731
				$this->notificationManager->add($n);
732
				# delete commercialShipping
733
				$this->entityManager->remove($cs);
734
				break;
735
			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...
736
		}
737
		$this->entityManager->flush();
738
	}
739
740
	public function uRecycling(OrbitalBase $orbitalBase, RecyclingMission $mission, Place $targetPlace, $dateOfUpdate) {
741
		$player = $this->playerManager->get($orbitalBase->getRPlayer());
742
		if ($targetPlace->typeOfPlace != Place::EMPTYZONE) {
743
			# make the recycling : decrease resources on the target place
744
			$totalRecycled = $mission->recyclerQuantity * RecyclingMission::RECYCLER_CAPACTIY;
745
			$targetPlace->resources -= $totalRecycled;
746
			# if there is no more resource
747
			if ($targetPlace->resources <= 0) {
748
				# the place become an empty place
749
				$targetPlace->resources = 0;
750
				$targetPlace->typeOfPlace = Place::EMPTYZONE;
751
752
				# stop the mission
753
				$mission->statement = RecyclingMission::ST_DELETED;
754
755
				# send notification to the player
756
				$n = new Notification();
757
				$n->setRPlayer($player->id);
758
				$n->setTitle('Arrêt de mission de recyclage');
759
				$n->addBeg()->addTxt('Un ');
760
				$n->addLnk('map/place-' . $mission->rTarget, 'lieu');
761
				$n->addTxt(' que vous recycliez est désormais totalement dépourvu de ressources et s\'est donc transformé en lieu vide.');
762
				$n->addSep()->addTxt('Vos recycleurs restent donc stationnés sur votre ');
763
				$n->addLnk('map/place-' . $orbitalBase->rPlace, 'base orbitale')->addTxt(' le temps que vous programmiez une autre mission.');
764
				$n->addEnd();
765
				$this->notificationManager->add($n);
766
			}
767
768
			# if the sector change its color between 2 recyclings
769
			if ($player->rColor != $targetPlace->sectorColor && $targetPlace->sectorColor != ColorResource::NO_FACTION) {
770
				# stop the mission
771
				$mission->statement = RecyclingMission::ST_DELETED;
772
773
				# send notification to the player
774
				$n = new Notification();
775
				$n->setRPlayer($player->id);
776
				$n->setTitle('Arrêt de mission de recyclage');
777
				$n->addBeg()->addTxt('Le secteur d\'un ');
778
				$n->addLnk('map/place-' . $mission->rTarget, 'lieu');
779
				$n->addTxt(' que vous recycliez est passé à l\'ennemi, vous ne pouvez donc plus y envoyer vos recycleurs. La mission est annulée.');
780
				$n->addSep()->addTxt('Vos recycleurs restent donc stationnés sur votre ');
781
				$n->addLnk('map/place-' . $orbitalBase->rPlace, 'base orbitale')->addTxt(' le temps que vous programmiez une autre mission.');
782
				$n->addEnd();
783
				$this->notificationManager->add($n);
784
			}
785
786
			$creditRecycled = round($targetPlace->population * $totalRecycled * 10 / 100);
787
			$resourceRecycled = round($targetPlace->coefResources * $totalRecycled / 100);
788
			$shipRecycled = round($targetPlace->coefHistory * $totalRecycled / 100);
789
790
			# diversify a little (resource and credit)
791
			$percent = rand(-5, 5);
792
			$diffAmountCredit = round($creditRecycled * $percent / 100);
793
			$diffAmountResource = round($resourceRecycled * $percent / 100);
794
			$creditRecycled += $diffAmountCredit;
795
			$resourceRecycled -= $diffAmountResource;
796
797
			if ($creditRecycled < 0) { $creditRecycled = 0; }
798
			if ($resourceRecycled < 0) { $resourceRecycled = 0; }
799
800
			# convert shipRecycled to real ships
801
			$pointsToRecycle = round($shipRecycled * RecyclingMission::COEF_SHIP);
802
			$shipsArray1 = array();
803
			$buyShip = array();
804
			for ($i = 0; $i < ShipResource::SHIP_QUANTITY; $i++) { 
805
				if (floor($pointsToRecycle / ShipResource::getInfo($i, 'resourcePrice')) > 0) {
806
					$shipsArray1[] = array(
807
						'ship' => $i,
808
						'price' => ShipResource::getInfo($i, 'resourcePrice'),
809
						'canBuild' => TRUE);
810
				}
811
				$buyShip[] = 0;
812
			}
813
814
			shuffle($shipsArray1);
815
			$shipsArray = array();
816
			$onlyThree = 0;
817
			foreach ($shipsArray1 as $key => $value) {
818
				$onlyThree++;
819
				$shipsArray[] = $value;
820
				if ($onlyThree == 3) {
821
					break;
822
				}
823
			}
824
			$continue = TRUE;
825
			if (count($shipsArray) > 0) {
826
				while($continue) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after WHILE keyword; 0 found
Loading history...
827
					foreach ($shipsArray as $key => $line) {
828
						if ($line['canBuild']) {
829
							$nbmax = floor($pointsToRecycle / $line['price']);
830
							if ($nbmax < 1) {
831
								$shipsArray[$key]['canBuild'] = FALSE;
832
							} else {
833
								$qty = rand(1, $nbmax);
834
								$pointsToRecycle -= $qty * $line['price'];
835
								$buyShip[$line['ship']] += $qty;
836
							}
837
						}
838
					}
839
840
					$canBuild = FALSE;
841
					# verify if we can build one more ship
842
					foreach ($shipsArray as $key => $line) {
843
						if ($line['canBuild']) {
844
							$canBuild = TRUE;
845
							break;
846
						}
847
					}
848
					if (!$canBuild) {
849
						# if the 3 types of ships can't be build anymore --> stop
850
						$continue = FALSE;
851
					}
852
				}
853
			}
854
855
			# create a RecyclingLog
856
			$rl = new RecyclingLog();
857
			$rl->rRecycling = $mission->id;
858
			$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...
859
			$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...
860
			$rl->ship0 = $buyShip[0];
861
			$rl->ship1 = $buyShip[1];
862
			$rl->ship2 = $buyShip[2];
863
			$rl->ship3 = $buyShip[3];
864
			$rl->ship4 = $buyShip[4];
865
			$rl->ship5 = $buyShip[5];
866
			$rl->ship6 = $buyShip[6];
867
			$rl->ship7 = $buyShip[7];
868
			$rl->ship8 = $buyShip[8];
869
			$rl->ship9 = $buyShip[9];
870
			$rl->ship10 = $buyShip[10];
871
			$rl->ship11 = $buyShip[11];
872
			$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...
873
			$this->recyclingLogManager->add($rl);
874
875
			# give to the orbitalBase ($orbitalBase) and player what was recycled
876
			$this->increaseResources($orbitalBase, $resourceRecycled);
877
			for ($i = 0; $i < ShipResource::SHIP_QUANTITY; $i++) { 
878
				$this->addShipToDock($orbitalBase, $i, $buyShip[$i]);
879
			}
880
			$this->playerManager->increaseCredit($player, $creditRecycled);
881
882
			# add recyclers waiting to the mission
883
			$mission->recyclerQuantity += $mission->addToNextMission;
884
			$mission->addToNextMission = 0;
885
886
			# if a mission is stopped by the user, delete it
887
			if ($mission->statement == RecyclingMission::ST_BEING_DELETED) {
888
				$mission->statement = RecyclingMission::ST_DELETED;
889
			}
890
891
			# update u
892
			$mission->uRecycling = $dateOfUpdate;
893
		} else {
894
			# the place become an empty place
895
			$targetPlace->resources = 0;
896
897
			# stop the mission
898
			$mission->statement = RecyclingMission::ST_DELETED;
899
900
			# send notification to the player
901
			$n = new Notification();
902
			$n->setRPlayer($player->id);
903
			$n->setTitle('Arrêt de mission de recyclage');
904
			$n->addBeg()->addTxt('Un ');
905
			$n->addLnk('map/place-' . $mission->rTarget, 'lieu');
906
			$n->addTxt(' que vous recycliez est désormais totalement dépourvu de ressources et s\'est donc transformé en lieu vide.');
907
			$n->addSep()->addTxt('Vos recycleurs restent donc stationnés sur votre ');
908
			$n->addLnk('map/place-' . $orbitalBase->rPlace, 'base orbitale')->addTxt(' le temps que vous programmiez une autre mission.');
909
			$n->addEnd();
910
			$this->notificationManager->add($n);
911
		}
912
	}
913
914
	public function addShipToDock(OrbitalBase $orbitalBase, $shipId, $quantity) {
915
		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...
916
			$orbitalBase->setShipStorage($shipId, $orbitalBase->getShipStorage($shipId) + $quantity);
917
			$this->entityManager->flush($orbitalBase);
918
			return TRUE;
919
		} else {
920
			return FALSE;
921
		}
922
	}
923
924
	public function removeShipFromDock(OrbitalBase $orbitalBase, $shipId, $quantity) {
925
		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...
926
			if ($orbitalBase->getShipStorage($shipId) >= $quantity) {
927
				$orbitalBase->setShipStorage($shipId, $orbitalBase->getShipStorage($shipId) - $quantity);
928
				$this->entityManager->flush($orbitalBase);
929
				return TRUE;
930
			} else {
931
				return FALSE;
932
			}
933
		}
934
	}
935
}