Passed
Push — master ( 703043...9c6704 )
by Anthony
02:42
created

Unite   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 421
Duplicated Lines 4.75 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 48
c 4
b 0
f 1
lcom 2
cbo 1
dl 20
loc 421
rs 8.4864

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B getCaracteristiqueUnite() 0 40 5
A getAllType() 0 3 1
A getUnitePossibleRecruter() 0 12 2
B getRecrutement() 0 26 5
A getAllUnites() 0 18 4
B getAllUniteType() 0 30 5
A getNombreUniteNom() 0 14 1
A getNombreUniteHumaine() 10 10 1
A getUnitesMission() 10 10 1
A getInfosRecrutementUnite() 0 17 4
B setCommencerRecruter() 0 38 5
B setTerminerRecrutement() 0 23 5
A setCommencerExpedition() 0 20 2
B setTerminerExpedition() 0 33 4
A setTuerUnites() 0 13 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Unite often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Unite, and based on these observations, apply Extract Interface, too.

1
<?php
2
	
3
	namespace modules\bataille\app\controller;
4
	
5
	
6
	use core\App;
7
	use core\functions\DateHeure;
8
	use core\HTML\flashmessage\FlashMessage;
9
10
	class Unite {
11
		private $coef_unite;
12
		private $pour_recruter;
13
		private $temps_recrutement;
14
15
		
16
		//-------------------------- BUILDER ----------------------------------------------------------------------------//
17
		public function __construct() {
18
			$this->coef_unite = Bataille::getParam("coef_niveau_unite");
19
		}
20
		//-------------------------- END BUILDER ----------------------------------------------------------------------------//
21
		
22
		
23
		//-------------------------- GETTER ----------------------------------------------------------------------------//
24
25
		/**
26
		 * @param $unite
27
		 * @param $niveau
28
		 * @param $type
29
		 * @return array
30
		 * récupère les caractéristiques de l'unité en fonction de son niveau
31
		 */
32
		public function getCaracteristiqueUnite($unite, $niveau, $type) {
33
			$dbc1 = Bataille::getDb();
34
35
			$query = $dbc1->select()
36
				->from("unites")
37
				->where("nom", "=", $unite, "AND")
38
				->where("type", "=", $type, "")
39
				->get();
40
41
			if ((is_array($query)) && (count($query) == 1)) {
42
				foreach ($query as $obj) {
43
					$base_carac = unserialize($obj->caracteristique);
44
					$ressource = unserialize($obj->pour_recruter);
45
					$temps_recrutement = DateHeure::Secondeenheure(round($obj->temps_recrutement-($obj->temps_recrutement*Bataille::getBatiment()->getNiveauBatiment("caserne")/100)));
46
				}
47
48
				$coef = $this->coef_unite*$niveau;
49
50
				if ($niveau == 1) $coef = 1;
51
52
				return [
53
					"caracteristique" => [
54
						"attaque" => round($base_carac["attaque"]*$coef),
0 ignored issues
show
Bug introduced by
The variable $base_carac does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
55
						"defense" => round($base_carac["defense"]*$coef),
56
						"resistance" => round($base_carac["resistance"]*$coef),
57
						"vitesse" => $base_carac["vitesse"]
58
					],
59
					"cout_recruter" => [
60
						"eau" => $ressource["eau"],
0 ignored issues
show
Bug introduced by
The variable $ressource does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
61
						"electricite" => $ressource["electricite"],
62
						"fer" => $ressource["fer"],
63
						"fuel" => $ressource["fuel"],
64
					],
65
					"temps_recrutement" => $temps_recrutement
0 ignored issues
show
Bug introduced by
The variable $temps_recrutement does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
66
				];
67
			}
68
			else {
69
				return [];
70
			}
71
		}
72
73
		/**
74
		 * @return array
75
		 * fonction qui renvoit tous les types d'unités qu'il est possible de recruter
76
		 */
77
		private function getAllType() {
78
			return explode(",", Bataille::getParam("type_unite"));
79
		}
80
81
		/**
82
		 * @param $type
83
		 * fonction qui permet de récupérer les unités qu'i est possible de recruter en fonction
84
		 * du type (batiment sur lequel on a cliqué)
85
		 */
86
		public function getUnitePossibleRecruter($type) {
87
			//on recup toutes les unites deja recherchée donc que l'on peut faire
88
			$unites = Bataille::getCentreRecherche()->getAllRechercheType($type);
89
90
			//recupérer les caractéristiques de l'unité en question
91
			for ($i=0 ; $i<count($unites) ; $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
92
				$unites[$i] += $this->getCaracteristiqueUnite($unites[$i]["recherche"], $unites[$i]["niveau"], $type);
93
				$unites[$i] += ["type" => $type];
94
			}
95
96
			Bataille::setValues(["unites" => $unites]);
97
		}
98
99
		/**
100
		 * fonction qui renvoi les unité  en cours de recrutement
101
		 */
102
		public function getRecrutement() {
103
			$dbc = App::getDb();
104
105
			$query = $dbc->select()->from("_bataille_recrutement")->where("ID_base", "=", Bataille::getIdBase())->get();
106
107
			if ((is_array($query)) && (count($query) > 0)) {
108
				$today = Bataille::getToday();
109
110
				foreach ($query as $obj) {
111
					if ($obj->date_fin-$today <= 0) {
112
						$this->setTerminerRecrutement($obj->ID_recrutement);
113
					}
114
					else {
115
						$recrutement[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$recrutement was never initialized. Although not strictly required by PHP, it is generally a good practice to add $recrutement = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
116
							"nom" => $obj->nom,
117
							"type" => $obj->type,
118
							"nombre" => $obj->nombre,
119
							"date_fin_recrutement" => $obj->date_fin-$today,
120
							"id_recrutement" => $obj->ID_recrutement
121
						];
122
					}
123
				}
124
125
				Bataille::setValues(["recrutement" => $recrutement]);
0 ignored issues
show
Bug introduced by
The variable $recrutement does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
126
			}
127
		}
128
129
		/**
130
		 * @param null $id_base
131
		 * fonction qui récupère toutes les unités qui sont dans la base
132
		 */
133
		public function getAllUnites($id_base = null) {
134
135
			if ($id_base == null) $id_base = Bataille::getIdBase();
136
137
			$types = $this->getAllType();
138
			$count_type = count($types);
139
			$unites = [];
140
141
			for ($i=0 ; $i<$count_type ; $i++) {
142
				$type_unite = $this->getAllUniteType($types[$i], $id_base);
143
144
				$unites = array_merge($unites, $type_unite);
145
			}
146
			
147
			if (count($unites) > 0) {
148
				Bataille::setValues(["unites" => $unites]);
149
			}
150
		}
151
152
		/**
153
		 * @param $type
154
		 * @param $id_base
155
		 * @return mixed
156
		 * fonction qui récupère toutes les unités en fonction d'un type précis
157
		 */
158
		private function getAllUniteType($type, $id_base) {
159
			$dbc = App::getDb();
160
161
			$query = $dbc->select("nom")->from("_bataille_unite")
162
				->where("type", "=", $type, "AND")
163
				->where("ID_base", "=", $id_base, "AND")
164
				->where("(ID_groupe IS NULL OR ID_groupe = 0)", "", "", "AND", true)
165
				->where("(ID_mission IS NULL OR ID_mission = 0)", "", "", "", true)
166
				->orderBy("nom")
167
				->get();
168
169
			if ((is_array($query)) && (count($query) > 0)) {
170
				$count = 1;
171
				$nom = "";
172
				foreach ($query as $obj) {
173
					if ($nom != $obj->nom) {
174
						$count = 1;
175
					}
176
					$unite[] = $unites[$type][$obj->nom] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$unite was never initialized. Although not strictly required by PHP, it is generally a good practice to add $unite = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
Coding Style Comprehensibility introduced by
$unites was never initialized. Although not strictly required by PHP, it is generally a good practice to add $unites = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
177
						"nom" => $obj->nom,
178
						"nombre" => $count++
179
					];
180
					$nom = $obj->nom;
181
				}
182
183
				return $unites;
0 ignored issues
show
Bug introduced by
The variable $unites does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
184
			}
185
			
186
			return [];
187
		}
188
		
189
		/**
190
		 * @param $type
191
		 * @param $nom
192
		 * @return int
193
		 * renvoi le nombre d'unite en fonction d'un type et d'un nom qui ne sont ni dans un groupe ni
194
		 * en mission
195
		 */
196
		private function getNombreUniteNom($type, $nom) {
197
			$dbc = App::getDb();
198
			
199
			$query = $dbc->select("nom")->from("_bataille_unite")
200
				->where("type", "=", $type, "AND")
201
				->where("nom", "=", $nom, "AND")
202
				->where("ID_base", "=", Bataille::getIdBase(), "AND")
203
				->where("(ID_groupe IS NULL OR ID_groupe = 0)", "", "", "AND", true)
204
				->where("(ID_mission IS NULL OR ID_mission = 0)", "", "", "", true)
205
				->orderBy("nom")
206
				->get();
207
			
208
			return count($query);
209
		}
210
		
211
		/**
212
		 * @return int
213
		 * fonction qui renvoi le nombre d'unité vivante dans la base qui consomme de la nourriture
214
		 */
215 View Code Duplication
		public function getNombreUniteHumaine() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
216
			$dbc = App::getDb();
217
			
218
			$query = $dbc->select("ID_unite")->from("_bataille_unite")
219
				->where("type", "=", "infanterie", "AND")
220
				->where("ID_base", "=", Bataille::getIdBase())
221
				->get();
222
			
223
			return count($query);
224
		}
225
		
226
		/**
227
		 * @param $id_mission
228
		 * @return int
229
		 * fonction qui renvoi le nombre d'unités envoyées sur une mission en particulier
230
		 */
231 View Code Duplication
		public function getUnitesMission($id_mission) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
232
			$dbc = App::getDb();
233
			
234
			$query = $dbc->select("ID_unite")->from("_bataille_unite")
235
				->where("ID_mission", "=", $id_mission, "AND")
236
				->where("ID_base", "=", Bataille::getIdBase())
237
				->get();
238
			
239
			return count($query);
240
		}
241
		
242
		/**
243
		 * @param $type
244
		 * @param $nom
245
		 * récupération du temmp de recrutement + les ressources nécéssaires
246
		 */
247
		private function getInfosRecrutementUnite($type, $nom) {
248
			$dbc1 = Bataille::getDb();
249
			
250
			$query = $dbc1->select("temps_recrutement")
251
				->select("pour_recruter")
252
				->from("unites")
253
				->where("nom", "=", $nom, "AND")
254
				->where("type", "=", $type, "")
255
				->get();
256
			
257
			if ((is_array($query)) && (count($query) == 1)) {
258
				foreach ($query as $obj) {
259
					$this->pour_recruter = unserialize($obj->pour_recruter);
260
					$this->temps_recrutement = round($obj->temps_recrutement-($obj->temps_recrutement*Bataille::getBatiment()->getNiveauBatiment("caserne")/100));
261
				}
262
			}
263
		}
264
		//-------------------------- END GETTER ----------------------------------------------------------------------------//
265
		
266
		
267
		//-------------------------- SETTER ----------------------------------------------------------------------------//
268
		/**
269
		 * @param $nom -> nom de l'unité à recruter
270
		 * @param $type -> type de l'unité à recruter
271
		 * @param $nombre -> nombre d'unité à recruter
272
		 * fonction qui permet d'initialiser le début du recrutement d'unités
273
		 */
274
		public function setCommencerRecruter($nom, $type, $nombre) {
275
			$dbc = App::getDb();
276
277
			$this->getInfosRecrutementUnite($type, $nom);
278
279
			//on test si on a assez de ressource pour recruter les unites
280
			//on test si assez de ressources dans la base
281
			$retirer_eau = intval($this->pour_recruter["eau"])*$nombre;
282
			$retirer_electricite = intval($this->pour_recruter["electricite"])*$nombre;
283
			$retirer_fer = intval($this->pour_recruter["fer"])*$nombre;
284
			$retirer_fuel = intval($this->pour_recruter["fuel"])*$nombre;
285
			$eau = Bataille::getTestAssezRessourceBase("eau", $retirer_eau);
286
			$electricite = Bataille::getTestAssezRessourceBase("electricite", $retirer_electricite);
287
			$fer = Bataille::getTestAssezRessourceBase("fer", $retirer_fer);
288
			$fuel = Bataille::getTestAssezRessourceBase("fuel", $retirer_fuel);
289
290
291
			if (($eau["class"] || $electricite["class"] || $fer["class"] || $fuel["class"]) == "rouge" ) {
292
				FlashMessage::setFlash("Pas assez de ressources pour recruter autant d'unités");
293
				return false;
294
			}
295
			else {
296
				//on retire les ressources
297
				Bataille::getRessource()->setUpdateRessource($retirer_eau, $retirer_electricite, $retirer_fer, $retirer_fuel, 0, "-");
298
299
				$date_fin = Bataille::getToday()+($this->temps_recrutement *$nombre);
300
301
				$dbc->insert("nom", $nom)
302
					->insert("type", $type)
303
					->insert("nombre", $nombre)
304
					->insert("date_fin", $date_fin)
305
					->insert("ID_base", Bataille::getIdBase())
306
					->into("_bataille_recrutement")
307
					->set();
308
309
				return true;
310
			}
311
		}
312
313
		/**
314
		 * @param $id_recrutement
315
		 * fonction appellée dans celle qui récupère les recrutement uniquement quand celui ci est finit
316
		 * fonction qui sert à terminer un rcrutement et ajouter les unités dans la base
317
		 */
318
		private function setTerminerRecrutement($id_recrutement) {
319
			$dbc = App::getDb();
320
321
			$query = $dbc->select()->from("_bataille_recrutement")->where("ID_recrutement", "=", $id_recrutement)->get();
322
323
			if ((is_array($query)) && (count($query) == 1)) {
324
				foreach ($query as $obj) {
325
					$nombre = $obj->nombre;
326
					$nom = $obj->nom;
327
					$type = $obj->type;
328
				}
329
330
				for ($i=0 ; $i<$nombre ; $i++) {
0 ignored issues
show
Bug introduced by
The variable $nombre does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
331
					$dbc->insert("nom", $nom)
0 ignored issues
show
Bug introduced by
The variable $nom does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
332
						->insert("type", $type)
0 ignored issues
show
Bug introduced by
The variable $type does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
333
						->insert("ID_base", Bataille::getIdBase())
334
						->into("_bataille_unite")
335
						->set();
336
				}
337
338
				$dbc->delete()->from("_bataille_recrutement")->where("ID_recrutement", "=", $id_recrutement)->del();
339
			}
340
		}
341
		
342
		/**
343
		 * @param $nombre_unite
344
		 * @param $nom_unite
345
		 * @param $type_unite
346
		 * @param $id_mission
347
		 * @return bool
348
		 * permet de lancer des unites en expédition en ajoutant à chaque unité un id_mission
349
		 */
350
		public function setCommencerExpedition($nombre_unite, $nom_unite, $type_unite, $id_mission) {
351
			$dbc = App::getDb();
352
			
353
			$nombre_unite_base = $this->getNombreUniteNom($type_unite, $nom_unite);
354
			
355
			if ($nombre_unite > $nombre_unite_base) {
356
				FlashMessage::setFlash("Pas assez d'unités ".$nom_unite." disponibles dans la base pour partir en mission");
357
				return false;
358
			}
359
			
360
			$dbc->update("ID_mission", $id_mission)
361
				->from("_bataille_unite")
362
				->where("type", "=", $type_unite, "AND")
363
				->where("nom", "=", $nom_unite, "AND")
364
				->where("ID_base", "=", Bataille::getIdBase())
365
				->limit($nombre_unite, "no")
366
				->set();
367
			
368
			return true;
369
		}
370
		
371
		/**
372
		 * @param $id_mission
373
		 * @param $pourcentage_perte
374
		 * @return int
375
		 * fonction qui termine une expdedition au niveau des troupes, cette fonction s'occupe d'en
376
		 * supprimer de la bdd en fonction du nombre de troupe envoyé et du cpourcentage de perte
377
		 */
378
		public function setTerminerExpedition($id_mission, $pourcentage_perte) {
379
			$dbc = App::getDb();
380
			$perte = rand(0, $pourcentage_perte);
381
			
382
			$query = $dbc->select()->from("_bataille_unite")->where("ID_mission", "=", $id_mission, "AND")
383
				->where("ID_base", "=", Bataille::getIdBase())
384
				->get();
385
			
386
			//test si il y aura des unités à tuer
387
			$nombre_unite = count($query);
388
			$unite_tuees = 0;
389
			if ((is_array($query)) && ($nombre_unite > 0)) {
390
				$unite_tuees = round($nombre_unite*$perte/100);
391
			}
392
			
393
			//si oui on en delete aléatoirement
394
			if ($unite_tuees > 0) {
395
				$dbc->delete()->from("_bataille_unite")->where("ID_mission", "=", $id_mission, "AND")
396
					->where("ID_base", "=", Bataille::getIdBase())
397
					->orderBy("RAND() ")
398
					->limit($unite_tuees)
399
					->del();
400
			}
401
			
402
			$dbc->update("ID_mission", 0)
403
				->from("_bataille_unite")
404
				->where("ID_base", "=", Bataille::getIdBase(), "AND")
405
				->where("ID_mission", "=", $id_mission, "", true)
406
				->set();
407
			
408
			//renvoi le nombre d'unites qui ont réussi àrentrer à la base
409
			return $nombre_unite-$unite_tuees;
410
		}
411
		
412
		/**
413
		 * @param $nombre
414
		 * fonction qui permet de tuer des unites
415
		 */
416
		public function setTuerUnites($nombre) {
417
			$dbc = App::getDb();
418
			
419
			if ($nombre > 0) {
420
				$dbc->delete()->from("_bataille_unite")
421
					->where("ID_base", "=", Bataille::getIdBase(), "AND")
422
					->where("type", "=", "infanterie", "AND")
423
					->where("(ID_mission IS NULL OR ID_mission = 0)", "", "", "", true)
424
					->orderBy("RAND() ")
425
					->limit($nombre)
426
					->del();
427
			}
428
		}
429
		//-------------------------- END SETTER ----------------------------------------------------------------------------//    
430
	}