Marche::__construct()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 52
Code Lines 37

Duplication

Lines 29
Ratio 55.77 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 29
loc 52
rs 7.2396
cc 7
eloc 37
nc 6
nop 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
	namespace modules\bataille\app\controller;
3
	
4
	
5
	use core\App;
6
	use core\HTML\flashmessage\FlashMessage;
7
8
	class Marche {
9
		private $id_base_dest;
10
		private $id_base;
11
		private $aller;
12
		private $ressources;
13
		private $date_arrivee;
14
		private $nom_base;
15
		private $id_marche_transport;
16
		private $duree_restante_trajet;
17
18
		//-------------------------- BUILDER ----------------------------------------------------------------------------//
19
		public function __construct() {
20
			$dbc = App::getDb();
21
			$marche = [];
22
23
			//récupération des trajets en cours d'envoi
24
			$query = $dbc->select()->from("_bataille_marche_transport")
25
				->from("_bataille_base")
26
				->where("_bataille_marche_transport.ID_base", "=", Bataille::getIdBase(), "AND")
27
				->where("_bataille_marche_transport.ID_base_dest", "=", "_bataille_base.ID_base", "", true)
28
				->orderBy("_bataille_marche_transport.aller", "DESC")
29
				->get();
30
31 View Code Duplication
			if ((is_array($query)) && (count($query) > 0)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
32
				foreach ($query as $obj) {
33
					$this->id_base_dest = $obj->ID_base_dest;
34
					$this->aller = $obj->aller;
35
					$this->ressources = $obj->ressources;
36
					$this->nom_base = $obj->nom_base;
37
					$this->date_arrivee = $obj->date_arrivee;
38
					$this->id_marche_transport = $obj->ID_marche_transport;
39
40
					$marche[] = $this->getTransportArrive();
41
				}
42
43
				Bataille::setValues(["marche_envoyer" => $marche]);
44
			}
45
46
			//récupération des trajets que l'on va recevoir
47
			$query = $dbc->select()->from("_bataille_marche_transport")
48
				->from("_bataille_base")
49
				->where("aller", "=", 1, "AND")
50
				->where("_bataille_marche_transport.ID_base_dest", "=", Bataille::getIdBase(), "AND")
51
				->where("_bataille_marche_transport.ID_base", "=", "_bataille_base.ID_base", "", true)
52
				->orderBy("_bataille_marche_transport.aller", "DESC")
53
				->get();
54
55 View Code Duplication
			if ((is_array($query)) && (count($query) > 0)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
56
				foreach ($query as $obj) {
57
					$this->id_base_dest = $obj->ID_base_dest;
58
					$this->id_base = $obj->ID_base;
59
					$this->aller = $obj->aller;
60
					$this->ressources = $obj->ressources;
61
					$this->nom_base = $obj->nom_base;
62
					$this->date_arrivee = $obj->date_arrivee;
63
					$this->id_marche_transport = $obj->ID_marche_transport;
64
65
					$marche[] = $this->getTransportArrive();
66
				}
67
68
				Bataille::setValues(["marche_recevoir" => $marche]);
69
			}
70
		}
71
		//-------------------------- END BUILDER ----------------------------------------------------------------------------//
72
73
74
75
		//-------------------------- GETTER ----------------------------------------------------------------------------//
76
		/**
77
		 * fonction qui permet de savoir si un transport est arrivé à la base de destination
78
		 * +si arrivé appel la fonction pour ajouter les ressources et passe le trajet sur le retour
79
		 * ou en trajet fini suivant le temps de la date d'aujourd'hui et la date à laquelle le
80
		 * trajet aurait du revenir
81
		 */
82
		private function getTransportArrive() {
83
			$today = Bataille::getToday();
84
85
			//on test si déja arrivé à destination
86
			if (($this->aller == 1) && (($this->date_arrivee-$today) <= 0)) {
87
				$this->setLivrerRessource();
88
89
				//on calcul la date d'arrivée du retour
90
				if ($this->id_base_dest == Bataille::getIdBase()) {
91
					$date_retour = Bataille::getDureeTrajet($this->id_base, Bataille::getParam("vitesse_marchand"))+$this->date_arrivee;
92
				}
93
				else {
94
					$date_retour = Bataille::getDureeTrajet($this->id_base_dest, Bataille::getParam("vitesse_marchand"))+$this->date_arrivee;
95
				}
96
97
				//si le retour du trajet est également arrivé on finit le transport sinon on le place sur le retour
98
				if ($date_retour < $today) {
99
					$this->setTerminerTransport();
100
				}
101
				else {
102
					$this->setTrajetRetour($date_retour);
103
					$this->duree_restante_trajet = $date_retour-$today;
104
					$set_array = true;
105
				}
106
			}
107
			else if (($this->aller == 0) && (($this->date_arrivee-$today) <= 0)) {
108
				$this->setTerminerTransport();
109
			}
110
			else {
111
				$this->duree_restante_trajet = $this->date_arrivee-$today;
112
				$set_array = true;
113
			}
114
115
			if ($set_array === true) {
0 ignored issues
show
Bug introduced by
The variable $set_array 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...
116
				if ($this->aller == 1) {
117
					$marche = [
118
						"id_marche_transport" => $this->id_marche_transport,
119
						"date_arrivee" => $this->duree_restante_trajet,
120
						"nom_base_dest" => $this->nom_base,
121
						"aller" => $this->aller
122
					];
123
				}
124
				else {
125
					$marche = [
126
						"id_marche_transport" => $this->id_marche_transport,
127
						"date_arrivee" => $this->duree_restante_trajet,
128
						"nom_base_dest" => $this->nom_base,
129
						"aller" => $this->aller
130
					];
131
				}
132
133
				return $marche;
134
			}
135
		}
136
137
		/**
138
		 * @param $all_ressource
139
		 * @return bool
140
		 * fonction qui renvoi true si on a assez de marchand pour ce trajet dans la base
141
		 * sinon on renvoi false
142
		 */
143
		private function getAssezMarchand($all_ressource) {
144
			$dbc = App::getDb();
145
146
			//récupération du nombre max du marchand dispo dans la base
147
			$nombre_max_marchand = Bataille::getBatiment()->getNiveauBatiment("marche");
148
149
			//on récupère tous les marchands qui sont en transport
150
			$query = $dbc->select("nb_marchand")->from("_bataille_marche_transport")
151
				->where("ID_base", "=", Bataille::getIdBase(), "OR")
152
				->where("ID_base_dest", "=", Bataille::getIdBase())
153
				->get();
154
155
			$marchand_transport = 0;
156
			if ((is_array($query)) && (count($query) > 0)) {
157
				foreach ($query as $obj) {
158
					$marchand_transport += $obj->nb_marchand;
159
				}
160
			}
161
162
			//on a le nombre de marchand dispo dans la base
163
			$nombre_marchand_dispo = $nombre_max_marchand-$marchand_transport;
164
165
			//on calcul savoir si on en a assez pour transport toutes les ressoures
166
			//il faut 1 marchand pour 1000 ressource
167
			$nombre_marchand_trajet = ceil($all_ressource/1000);
168
169
			//si on a assez de marchand on revoi true sinon false
170
			if ($nombre_marchand_dispo >= $nombre_marchand_trajet) {
171
				return $nombre_marchand_trajet;
172
			}
173
174
			return false;
175
		}
176
		//-------------------------- END GETTER ----------------------------------------------------------------------------//
177
178
179
180
		//-------------------------- SETTER ----------------------------------------------------------------------------//
181
		/**
182
		 * fonction qui permet d'ajouter les ressources à la base destinatrice du transport
183
		 */
184
		private function setLivrerRessource() {
185
			$ressource = new Ressource($this->id_base_dest);
186
187
			$ressource_transport = unserialize($this->ressources);
188
189
			$ressource->setUpdateRessource($ressource_transport['eau'], $ressource_transport['electricite'], $ressource_transport['fer'], $ressource_transport['fuel'], $ressource_transport['nourriture'], "+");
190
		}
191
		
192
		/**
193
		 * @param $date_retour
194
		 * fonction qui place le trajet en retour
195
		 */
196
		private function setTrajetRetour($date_retour) {
197
			$dbc = App::getDb();
198
199
			$dbc->update("ressources", 0)
200
				->update("aller", 0)
201
				->update("date_arrivee", $date_retour)
202
				->from("_bataille_marche_transport")
203
				->where("ID_marche_transport", "=", $this->id_marche_transport)
204
				->set();
205
206
			$this->aller = 0;
207
		}
208
209
		/**
210
		 * permet de terminer totallement un transport
211
		 */
212
		private function setTerminerTransport() {
213
			$dbc = App::getDb();
214
215
			$dbc->delete()->from("_bataille_marche_transport")->where("ID_marche_transport", "=", $this->id_marche_transport)->del();
216
		}
217
218
		/**
219
		 * @param $eau
220
		 * @param $electricite
221
		 * @param $fer
222
		 * @param $fuel
223
		 * @param $nourriture
224
		 * @param $posx
225
		 * @param $posy
226
		 * @return bool
227
		 * Fonction qui permet d'initialiser un transport de ressources d'une base à une autre
228
		 */
229
		public function setCommencerTransport($eau, $electricite, $fer, $fuel, $nourriture, $posx, $posy) {
230
			$dbc = App::getDb();
231
			$id_base_dest = Bataille::getBaseExistPosition($posx, $posy);
232
233
			if (($id_base_dest != 0) && ($id_base_dest != Bataille::getIdBase())) {
234
				$ressource["eau"] = Bataille::getTestAssezRessourceBase("eau", $eau);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ressource was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ressource = 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...
235
				$ressource["electricite"] = Bataille::getTestAssezRessourceBase("electricite", $electricite);
236
				$ressource["fer"] = Bataille::getTestAssezRessourceBase("fer", $fer);
237
				$ressource["fuel"] = Bataille::getTestAssezRessourceBase("fuel", $fuel);
238
				$ressource["nourriture"] = Bataille::getTestAssezRessourceBase("nourriture", $nourriture);
239
240
				//si pas assez de ressources dispo dans la base pour l'envoi on renvoi erreur
241
				foreach ($ressource as $tab) {
242
					if (in_array("rouge", $tab)) {
243
						FlashMessage::setFlash("Vous n'avez pas autant de ressources disponibles à l'envoi");
244
						return false;
245
					};
246
				}
247
248
				//on check si assez marchand dans la base, si pas assez on return false
249
				$nb_marchand = $this->getAssezMarchand($eau+$electricite+$fer+$fuel+$nourriture);
250
251
				if ($nb_marchand === false) {
252
					FlashMessage::setFlash("Vous n'avez pas assez de marchans disponibles pour effectuer ce trajet");
253
					return false;
254
				}
255
				
256
				if (Profil::getTestVacancesBase($id_base_dest) == 1) {
257
					FlashMessage::setFlash("Cette base est en mode vacances, vous ne pouvez pas y envoyer des ressources");
258
					return false;
259
				}
260
261
				//sinon initialise le transport
262
				//on recup la date d'arrivee dans la base de destintation
263
				$date_arrivee = Bataille::getDureeTrajet($id_base_dest, Bataille::getParam("vitesse_marchand"))+Bataille::getToday();
264
265
				$ressource = [
266
					"eau" => $eau,
267
					"electricite" => $electricite,
268
					"fer" => $fer,
269
					"fuel" => $fuel,
270
					"nourriture" => $nourriture,
271
				];
272
273
				//on insert le transport dans la table
274
				$dbc->insert("date_arrivee", $date_arrivee)
275
					->insert("ressources", serialize($ressource))
276
					->insert("aller", 1)
277
					->insert("nb_marchand", $nb_marchand)
278
					->insert("ID_base_dest", $id_base_dest)
279
					->insert("ID_base", Bataille::getIdBase())
280
					->into("_bataille_marche_transport")
281
					->set();
282
283
				//on retire les ressources de la base
284
				Bataille::getRessource()->setUpdateRessource($eau, $electricite, $fer, $fuel, $nourriture, "-");
285
286
				FlashMessage::setFlash("Votre transport vient de partir !", "info");
287
				return true;
288
			}
289
290
			FlashMessage::setFlash("Aucune base présente aux coordonnées données");
291
			return false;
292
		}
293
		//-------------------------- END SETTER ----------------------------------------------------------------------------//
294
	}