Passed
Push — master ( 9ed1fd...287d79 )
by Anthony
02:34
created

Marche::__construct()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 51
Code Lines 36

Duplication

Lines 29
Ratio 56.86 %

Importance

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