Passed
Push — master ( e67967...d90199 )
by Anthony
02:46
created

MissionsAleatoire::setTerminerMissions()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 30
rs 8.439
cc 5
eloc 18
nc 4
nop 0
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 $type
161
		 * fonction qui recupere des missions aleatoirement de chaque type et qui les ajoute
162
		 * dans la table _bataille_mission_aleatoire
163
		 */
164
		private function setMissionsAleatoire() {
165
			$dbc = App::getDb();
166
			$dbc1 = Bataille::getDb();
167
			
168
			$dbc->delete()->from("_bataille_mission_aleatoire")->where("ID_base", "=", Bataille::getIdBase())->del();
169
			
170
			$type_missions = $this->getTypeMission();
171
			
172
			foreach ($type_missions as $un_type) {
173
				$query = $dbc1->select()->from("mission")
174
					->where("type", "=", $un_type)
175
					->orderBy("RAND()")
176
					->limit(0, 3)
177
					->get();
178
				
179
				if ((is_array($query)) && (count($query))) {
180
					foreach ($query as $obj) {
181
						$dbc->insert("ID_mission", $obj->ID_mission)
182
							->insert("ID_base", Bataille::getIdBase())
183
							->into("_bataille_mission_aleatoire")
184
							->set();
185
					}
186
				}
187
			}
188
		}
189
		
190
		/**
191
		 * @param $id_mission
192
		 * @param $nombre_unite
193
		 * @param $nom_unite
194
		 * @param $type_unite
195
		 * fonction sert a lancer une mission
196
		 */
197
		public function setCommencerMission($id_mission, $nombre_unite, $nom_unite, $type_unite) {
198
			$dbc = App::getDb();
199
			
200
			$dbc->insert("date_fin", $this->getTempsMission($id_mission)+Bataille::getToday())
201
				->insert("ID_base", Bataille::getIdBase())
202
				->insert("ID_mission", $id_mission)
203
				->into("_bataille_missions_cours")
204
				->set();
205
			
206
			$id_missions_cours = $dbc->lastInsertId();
207
			
208
			$count = count($nombre_unite);
209
			for ($i=0 ; $i<$count ; $i++) {
210
				Bataille::getUnite()->setCommencerExpedition($nombre_unite[$i], $nom_unite[$i], $type_unite[$i], $id_missions_cours);
211
			}
212
		}
213
		
214
		/**
215
		 * fonctin qui termine les missions en cours et qui ajoutera les ressources + les points
216
		 * et qui au cas ou pourra tuer des inités
217
		 */
218
		public function setTerminerMissions() {
219
			$dbc = App::getDb();
220
			
221
			$query = $dbc->select()->from("_bataille_missions_cours")
222
				->where("date_fin", "<=", Bataille::getToday(), "AND")
223
				->where("ID_base", "=", Bataille::getIdBase())
224
				->get();
225
			
226
			if ((is_array($query)) && (count($query))) {
227
				foreach ($query as $obj) {
228
					$infos_missions = $this->getInfosMission($obj->ID_mission);
229
					
230
					if ($infos_missions["type"] == "nourriture") {
231
						Bataille::getRessource()->setUpdateRessource(0, 0, 0, 0, $infos_missions["ressource_gagnee"], "+");
232
					}
233
					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...
234
						//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...
235
					}
236
					
237
					Points::setAjouterPoints(Bataille::getIdBase(), "", $infos_missions["points_gange"]);
238
					
239
					Bataille::getUnite()->setTerminerExpedition($obj->ID_mission, $infos_missions["pourcentage_perte"]);
240
					
241
					$dbc->delete()->from("_bataille_missions_cours")
242
						->where("ID_base", "=", Bataille::getIdBase(), "AND")
243
						->where("ID_mission", "=", $obj->ID_mission)
244
						->del();
245
				}
246
			}
247
		}
248
		//-------------------------- END SETTER ----------------------------------------------------------------------------//
249
		
250
	}