Passed
Push — master ( d4b0ea...d4b0ea )
by Anthony
04:31
created

MissionsAleatoire   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 256
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 37
c 5
b 0
f 0
lcom 1
cbo 2
dl 0
loc 256
rs 8.6

11 Methods

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