Passed
Push — master ( d4b0ea...714742 )
by Anthony
02:39
created

MissionsAleatoire::setCommencerMission()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
rs 8.9713
cc 3
eloc 15
nc 2
nop 4
1
<?php
2
	namespace modules\bataille\app\controller;
3
	
4
	
5
	use core\App;
6
	use core\functions\DateHeure;
7
	use core\HTML\flashmessage\FlashMessage;
8
	
9
	class MissionsAleatoire {
10
		private $last_check_mission;
11
		
12
		
13
		//-------------------------- BUILDER ----------------------------------------------------------------------------//
14
		/**
15
		 * MissionsAleatoire constructor.
16
		 * le constructeur s'occupe de vérifier le last_check des missions et au cas ou si il est plus vieux d'un jour
17
		 * appeler la fonction pour recharger les missions
18
		 */
19
		public function __construct() {
20
			$dbc = App::getDb();
21
			
22
			$query = $dbc->select("last_check_mission")->from("_bataille_base")->where("ID_base", "=", Bataille::getIdBase())->get();
23
			
24
			if (is_array($query) && (count($query) == 1)) {
25
				foreach ($query as $obj) {
26
					$this->last_check_mission = $obj->last_check_mission;
27
				}
28
				
29
				if ($this->last_check_mission == "") {
30
					$this->setUpdateLastCheckMissions();
31
					$this->setMissionsAleatoire();
32
				}
33
				else {
34
					$today = Bataille::getToday();
35
					$interval = $today-$this->last_check_mission;
36
					
37
					if ($interval >= 10800) {
38
						$this->setUpdateLastCheckMissions();
39
						$this->setMissionsAleatoire();
40
					}
41
				}
42
			}
43
			
44
			$this->getNbMissions();
45
			Bataille::setValues(["next_check_missions" => ($this->last_check_mission+10800)-Bataille::getToday()]);
46
			
47
			$this->getMissionsCours();
48
		}
49
		//-------------------------- END BUILDER ----------------------------------------------------------------------------//
50
		
51
		
52
		
53
		//-------------------------- GETTER ----------------------------------------------------------------------------//
54
		/**
55
		 * fonction qui récupere tous les types de missions et les return dans un array
56
		 */
57
		private function getTypeMission() {
58
			return explode(",", Bataille::getParam("type_missions"));
59
		}
60
		
61
		/**
62
		 * @return int
63
		 * renvoi le nombre de missions encore disponibles dans la base
64
		 */
65
		private function getNbMissions() {
66
			$dbc = App::getDb();
67
			
68
			$query = $dbc->select("ID_mission_aleatoire")->from("_bataille_mission_aleatoire")->where("ID_base", "=", Bataille::getIdBase())->get();
69
			
70
			if ((is_array($query)) && (count($query))) {
71
				foreach ($query as $obj) {
72
					$id[] = $obj->ID_base;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$id was never initialized. Although not strictly required by PHP, it is generally a good practice to add $id = 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...
73
				}
74
				
75
				$count = count($id);
0 ignored issues
show
Bug introduced by
The variable $id 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...
76
				Bataille::setValues([
77
					"nb_missions" => $count
78
				]);
79
				
80
				return $count;
81
			}
82
		}
83
		
84
		/**
85
		 * @param $id_mission
86
		 * @return mixed
87
		 * fonction qui récupère la durée d'une mission
88
		 */
89
		private function getTempsMission($id_mission) {
90
			$dbc1 = Bataille::getDb();
91
			
92
			$query = $dbc1->select("duree")->from("mission")->where("ID_mission", "=", $id_mission)->get();
93
			
94
			if ((is_array($query)) && (count($query))) {
95
				foreach ($query as $obj) {
96
					return $obj->duree;
97
				}
98
			}
99
		}
100
		
101
		/**
102
		 * récupères les missions encore disponible dans la base
103
		 */
104
		public function getMissions() {
105
			$dbc = App::getDb();
106
			
107
			$query = $dbc->select()->from("_bataille_mission_aleatoire")->where("ID_base", "=", Bataille::getIdBase())->get();
108
			
109
			if ((is_array($query)) && (count($query))) {
110
				foreach ($query as $obj) {
111
					$missions[] = $this->getInfosMission($obj->ID_mission);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$missions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $missions = 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...
112
				}
113
				
114
				Bataille::setValues(["missions" => $missions]);
0 ignored issues
show
Bug introduced by
The variable $missions 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
			}
116
		}
117
		
118
		/**
119
		 * @param $id_mission
120
		 * @return array
121
		 * pour récupérer les infos d'une mission dans la bdd _core
122
		 */
123
		private function getInfosMission($id_mission) {
124
			$dbc1 = Bataille::getDb();
125
			$query1 = $dbc1->select()->from("mission")->where("ID_mission", "=", $id_mission)->get();
126
			
127
			if ((is_array($query1)) && (count($query1) > 0)) {
128
				foreach ($query1 as $obj) {
129
					return [
130
						"id_mission" => $obj->ID_mission,
131
						"nom_mission" => $obj->nom_mission,
132
						"description" => $obj->description,
133
						"points_gagne" => $obj->points_gagne,
134
						"type" => $obj->type,
135
						"ressource_gagnee" => $obj->ressource_gagnee,
136
						"pourcentage_perte" => $obj->pourcentage_perte,
137
						"duree" => DateHeure::Secondeenheure($obj->duree)
138
					];
139
				}
140
			}
141
		}
142
		
143
		/**
144
		 * fonction qui récupère les missions qui sont en cours dans la base
145
		 */
146
		private function getMissionsCours() {
147
			$dbc = App::getDb();
148
			
149
			$query = $dbc->select()->from("_bataille_missions_cours")->where("ID_base", "=", Bataille::getIdBase())->get();
150
			
151
			if ((is_array($query)) && (count($query) > 0)) {
152
				foreach ($query as $obj) {
153
					$missions[] =[
0 ignored issues
show
Coding Style Comprehensibility introduced by
$missions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $missions = 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...
154
						"id_missions_cours" => $obj->ID_missions_cours,
155
						"date_fin" => $obj->date_fin-Bataille::getToday(),
156
						"infos" => $this->getInfosMission($obj->ID_mission)
157
					];
158
				}
159
				
160
				Bataille::setValues(["missions_cours" => $missions]);
0 ignored issues
show
Bug introduced by
The variable $missions 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...
161
			}
162
		}
163
		//-------------------------- END GETTER ----------------------------------------------------------------------------//
164
		
165
		
166
		
167
		//-------------------------- SETTER ----------------------------------------------------------------------------//
168
		/**
169
		 * fonction qui met a jour le last_ckeck_missions dans _bataille_base
170
		 * le met à la date du jour
171
		 */
172
		private function setUpdateLastCheckMissions() {
173
			$dbc = App::getDb();
174
			
175
			$dbc->update("last_check_mission", Bataille::getToday())
176
				->from("_bataille_base")
177
				->where("ID_base", "=", Bataille::getIdBase())
178
				->set();
179
			
180
			$this->last_check_mission = Bataille::getToday();
181
		}
182
		
183
		/**
184
		 * @param $id_mission
185
		 * fonction qui retire une mission de la liste des missions aleatoire des qu'on la lance
186
		 */
187
		private function setDeleteMission($id_mission) {
188
			$dbc = App::getDb();
189
			
190
			$dbc->delete()->from("_bataille_mission_aleatoire")->where("ID_base", "=", Bataille::getIdBase(), "AND")
191
				->where("ID_mission", "=", $id_mission)->del();
192
		}
193
		
194
		/**
195
		 * @param $type
196
		 * fonction qui recupere des missions aleatoirement de chaque type et qui les ajoute
197
		 * dans la table _bataille_mission_aleatoire
198
		 */
199
		private function setMissionsAleatoire() {
200
			$dbc = App::getDb();
201
			$dbc1 = Bataille::getDb();
202
			
203
			$dbc->delete()->from("_bataille_mission_aleatoire")->where("ID_base", "=", Bataille::getIdBase())->del();
204
			
205
			$type_missions = $this->getTypeMission();
206
			
207
			foreach ($type_missions as $un_type) {
208
				$query = $dbc1->select()->from("mission")
209
					->where("type", "=", $un_type)
210
					->orderBy("RAND()")
211
					->limit(0, 3)
212
					->get();
213
				
214
				if ((is_array($query)) && (count($query))) {
215
					foreach ($query as $obj) {
216
						$dbc->insert("ID_mission", $obj->ID_mission)
217
							->insert("ID_base", Bataille::getIdBase())
218
							->into("_bataille_mission_aleatoire")
219
							->set();
220
					}
221
				}
222
			}
223
		}
224
		
225
		/**
226
		 * @param $id_mission
227
		 * @param $nombre_unite
228
		 * @param $nom_unite
229
		 * @param $type_unite
230
		 * fonction sert a lancer une mission
231
		 */
232
		public function setCommencerMission($id_mission, $nombre_unite, $nom_unite, $type_unite) {
233
			$dbc = App::getDb();
234
			if ($nombre_unite > 0) {
235
				$dbc->insert("date_fin", $this->getTempsMission($id_mission)+Bataille::getToday())
236
					->insert("ID_base", Bataille::getIdBase())
237
					->insert("ID_mission", $id_mission)
238
					->into("_bataille_missions_cours")
239
					->set();
240
				
241
				$id_missions_cours = $dbc->lastInsertId();
242
				
243
				$count = count($nombre_unite);
244
			
245
			
246
				for ($i=0 ; $i<$count ; $i++) {
247
					Bataille::getUnite()->setCommencerExpedition($nombre_unite[$i], $nom_unite[$i], $type_unite[$i], $id_missions_cours);
248
				}
249
				
250
				$this->setDeleteMission($id_mission);
251
			}
252
			
253
			FlashMessage::setFlash("Pas assez d'unité pour effectuer cette missions");
254
			return false;
255
		}
256
		
257
		/**
258
		 * fonctin qui termine les missions en cours et qui ajoutera les ressources + les points
259
		 * et qui au cas ou pourra tuer des inités
260
		 */
261
		public function setTerminerMissions() {
262
			$dbc = App::getDb();
263
			
264
			$query = $dbc->select()->from("_bataille_missions_cours")
265
				->where("date_fin", "<=", Bataille::getToday(), "AND")
266
				->where("ID_base", "=", Bataille::getIdBase())
267
				->get();
268
			
269
			if ((is_array($query)) && (count($query))) {
270
				foreach ($query as $obj) {
271
					$infos_missions = $this->getInfosMission($obj->ID_mission);
272
					
273
					$unite_revenu = Bataille::getUnite()->setTerminerExpedition($obj->ID_missions_cours, $infos_missions["pourcentage_perte"]);
274
					
275
					if ($infos_missions["type"] == "nourriture") {
276
						Bataille::getRessource()->setUpdateRessource(0, 0, 0, 0, $infos_missions["ressource_gagnee"]*$unite_revenu, "+");
277
					}
278
					else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
279
						//Bataille::getRessource()->setUpdateRessource(0, 0, 0, 0, $obj->ressource_gagnee, "+");
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
280
					}
281
					
282
					Points::setAjouterPoints(Bataille::getIdBase(), "missions", $infos_missions["points_gange"]);
283
					
284
					$dbc->delete()->from("_bataille_missions_cours")
285
						->where("ID_base", "=", Bataille::getIdBase(), "AND")
286
						->where("ID_mission", "=", $obj->ID_mission)
287
						->del();
288
				}
289
			}
290
		}
291
		//-------------------------- END SETTER ----------------------------------------------------------------------------//
292
		
293
	}