absences_RightAct   F
last analyzed

Complexity

Total Complexity 117

Size/Duplication

Total Lines 1058
Duplicated Lines 6.71 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 117
lcom 1
cbo 13
dl 71
loc 1058
rs 2.7567
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A getDateValue() 0 17 3
B getDateTimeValue() 0 29 6
B checkPeriod() 10 27 4
A checkOptionalPeriod() 0 10 3
F checkPost() 20 143 29
B isFixedModified() 0 21 6
C updateCollectionsBeneficiaries() 0 73 7
D updateFixed() 10 107 12
D save() 5 278 21
A applyDynamicRights() 0 10 2
B saveCet() 0 77 6
F saveRules() 0 140 15
A goToNoBeneficiaries() 9 9 1
A goToUpdateFixed() 9 9 1
A redirect() 8 8 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like absences_RightAct often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use absences_RightAct, and based on these observations, apply Extract Interface, too.

1
<?php
2
/************************************************************************
3
 * OVIDENTIA http://www.ovidentia.org                                   *
4
 ************************************************************************
5
 * Copyright (c) 2003 by CANTICO ( http://www.cantico.fr )              *
6
 *                                                                      *
7
 * This file is part of Ovidentia.                                      *
8
 *                                                                      *
9
 * Ovidentia is free software; you can redistribute it and/or modify    *
10
 * it under the terms of the GNU General Public License as published by *
11
 * the Free Software Foundation; either version 2, or (at your option)  *
12
 * any later version.													*
13
 *																		*
14
 * This program is distributed in the hope that it will be useful, but  *
15
 * WITHOUT ANY WARRANTY; without even the implied warranty of			*
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.					*
17
 * See the  GNU General Public License for more details.				*
18
 *																		*
19
 * You should have received a copy of the GNU General Public License	*
20
 * along with this program; if not, write to the Free Software			*
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,*
22
 * USA.																	*
23
************************************************************************/
24
25
26
require_once dirname(__FILE__).'/right.class.php';
27
require_once dirname(__FILE__).'/type.class.php';
28
require_once dirname(__FILE__).'/movement.class.php';
29
30
31
class absences_RightAct
32
{
33
	private static $post;
34
35
	
36
	
37
	/**
38
	 * Get date from field name
39
	 * @param string $name
40
	 * @return string
41
	 */
42
	private static function getDateValue($name)
43
	{
44
		if (!isset(self::$post[$name]))
45
		{
46
			return '0000-00-00';
47
		}
48
	
49
		$W = bab_Widgets();
50
		$date = $W->DatePicker()->getISODate(self::$post[$name]);
51
	
52
		if (false === $date)
53
		{
54
			return '0000-00-00';
55
		}
56
	
57
		return $date;
58
	}
59
	
60
	
61
	/**
62
	 *
63
	 * @param string $datename		name of datepicker
64
	 * @param string $timename		Name of select contains times values
65
	 * @return string
66
	 */
67
	private static function getDateTimeValue($datename, $timename)
68
	{
69
		if (!isset(self::$post[$datename]))
70
		{
71
			return '0000-00-00 00:00:00';
72
		}
73
	
74
		$W = bab_Widgets();
75
		$date = $W->DatePicker()->getISODate(self::$post[$datename]);
76
	
77
		if (false === $date || '0000-00-00' === $date)
78
		{
79
			return '0000-00-00 00:00:00';
80
		}
81
	
82
		$time = '00:00:00';
83
	
84
		if (isset(self::$post[$timename]))
85
		{
86
			if (8 !== mb_strlen(self::$post[$timename]))
87
			{
88
				return '0000-00-00 00:00:00';
89
			}
90
	
91
			$time = self::$post[$timename];
92
		}
93
	
94
		return $date.' '.$time;
95
	}
96
	
97
	
98
	/**
99
	 * 
100
	 * @param string $begin		Field name
101
	 * @param string $end		Field name
102
	 * @param string $title		title for error message
103
	 * 
104
	 * @return boolean
105
	 */
106
	private static function checkPeriod($begin, $end, $title)
107
	{
108
		global $babBody;
109
		
110
		$date_begin = self::getDateValue($begin);
111
		$date_end = self::getDateValue($end);
112
		
113 View Code Duplication
		if ('0000-00-00' === $date_begin)
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...
114
		{
115
			$babBody->addError(sprintf(absences_translate("Invalid start date for the %s"), mb_strtolower($title)));
116
			return false;
117
		}
118
		
119 View Code Duplication
		if ('0000-00-00' === $date_end)
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...
120
		{
121
			$babBody->addError(sprintf(absences_translate("Invalid end date for the %s"), mb_strtolower($title)));
122
			return false;
123
		}
124
		
125
		if($date_begin > $date_end )
126
		{
127
			$babBody->addError(sprintf(absences_translate("Begin date must be less than end date in %s"), $title));
128
			return false;
129
		}
130
		
131
		return true;
132
	}
133
	
134
	/**
135
	 * Validate optional period
136
	 * 
137
 	 * @param string $begin		Field name
138
	 * @param string $end		Field name
139
	 * @param string $title		title for error message
140
	 * 
141
	 * @return boolean
142
	 */
143
	private static function checkOptionalPeriod($begin, $end, $title)
144
	{
145
		if ('' === self::$post[$begin] && '' === self::$post[$end])
146
		{
147
			// period not set
148
			return true;
149
		}
150
		
151
		return self::checkPeriod($begin, $end, $title);
152
	}
153
	
154
	
155
	
156
	/**
157
	 * Test posted values before saving
158
	 * @return bool
159
	 */
160
	protected static function checkPost()
161
	{
162
		global $babBody, $babDB;
163
		
164
		
165
		if( empty(self::$post['description']))
166
		{
167
			$babBody->msgerror = absences_translate("You must specify a vacation description");
168
			return false;
169
		}
170
		
171
		$query = "SELECT id FROM absences_rights WHERE description LIKE '".$babDB->db_escape_like(self::$post['description'])."'";
172
		if (!empty(self::$post['id']))
173
		{
174
			$query .= ' AND id<>'.$babDB->quote(self::$post['id']);
175
		}
176
		
177
		$res = $babDB->db_query($query);
178
		if (0 !== $babDB->db_num_rows($res))
179
		{
180
			$babBody->addError(absences_translate("A vacation right with the same name already exists"));
181
			return false;
182
		}
183
		
184
		
185
		if(empty(self::$post['id']))
186
		{
187 View Code Duplication
			if (absences_Right::REPORT === (int) self::$post['kind'])
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...
188
			{
189
				$babBody->addError(absences_translate("A report right cannot be created by a manager, they are created automaticaly after expiration of a right"));
190
				return false;
191
			}
192
			
193 View Code Duplication
			if (absences_Right::RECOVERY === (int) self::$post['kind'])
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...
194
			{
195
				$babBody->addError(absences_translate("A recovery right cannot be created by a manager, they are created after approval of a workingday entitling recovery"));
196
				return false;
197
			}
198
		}
199
		
200
		
201
		if ((empty(self::$post['date_begin']) || empty(self::$post['date_end'])) && !empty(self::$post['quantity_alert_days']))
202
		{
203
			$babBody->addError(absences_translate("The configuration of an alert depending on the consumed number of days require a valid theoretical period"));
204
			return false;
205
		}
206
		
207
		
208
		if( absences_Right::CET !== (int) self::$post['kind'])
209
		{
210
			// tests de la quantite
211
			
212 View Code Duplication
			if( !is_numeric(self::$post['quantity']))
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...
213
			{
214
				$babBody->addError(absences_translate("You must specify a correct quantity"));
215
				return false;
216
			}
217
			
218 View Code Duplication
			if( 0 > (int) self::$post['quantity'])
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...
219
			{
220
				$babBody->addError(absences_translate("You must specify a correct quantity"));
221
				return false;
222
			}
223
		}
224
		
225
		if (0 !== (int) self::$post['id_rgroup'])
226
		{
227
			$res = $babDB->db_query("SELECT quantity_unit FROM absences_rgroup WHERE id=".$babDB->quote(self::$post['id_rgroup']));
228
			$rgroup = $babDB->db_fetch_assoc($res);
229
230
			if (!$rgroup || ($rgroup['quantity_unit'] != self::$post['quantity_unit']))
231
			{
232
				$babBody->msgerror = absences_translate("The right quantity unit and the right group quantity unit must be the same");
233
				return false;
234
			}
235
			
236
		}
237
		
238
		if (absences_Right::REGULAR === (int) self::$post['kind'] || absences_Right::INCREMENT === (int) self::$post['kind'])
239
		{
240
			$type = new absences_Type(self::$post['id_type']);
241
			if (!isset($type->cbalance) || ($type->cbalance == 'N' && self::$post['cbalance'] != 'N'))
242
			{
243
				$babBody->msgerror = absences_translate("Negative balance are not allowed with this vacation type");
244
				return false;
245
			}
246
		}
247
		
248
		
249
		if (!self::checkOptionalPeriod('date_begin', 'date_end', absences_translate('theoretical period')))
250
		{
251
			return false;
252
		}
253
		
254
		if (!self::checkOptionalPeriod('date_begin_valid', 'date_end_valid', absences_translate('validity period')))
255
		{
256
			return false;
257
		}
258
		
259
		if (!self::checkOptionalPeriod('trigger_p1_begin', 'trigger_p1_end', absences_translate('first test period')))
260
		{
261
			return false;
262
		}
263
		
264
		if (!self::checkOptionalPeriod('trigger_p2_begin', 'trigger_p2_end', absences_translate('second test period')))
265
		{
266
			return false;
267
		}
268
		
269
		
270
		
271
		
272
		
273
		if(absences_Right::FIXED === (int) self::$post['kind'])
274
		{
275
			// mandatory if fixed vacation
276
			
277
			$date_begin_fixed = self::getDateTimeValue('datebeginfx', 'hourbeginfx');
278
			$date_end_fixed = self::getDateTimeValue('dateendfx', 'hourendfx');
279
			
280
			if ('0000-00-00 00:00:00' === $date_begin_fixed)
281
			{
282
				$babBody->msgerror = absences_translate("Invalid start date for the fixed vacation period");
283
				return false;
284
			}
285
			
286
			if ('0000-00-00 00:00:00' === $date_end_fixed)
287
			{
288
				$babBody->msgerror = absences_translate("Invalid end date for the fixed vacation period");
289
				return false;
290
			}
291
			
292
			if($date_begin_fixed >= $date_end_fixed )
293
			{
294
				$babBody->msgerror = absences_translate("Begin date must be less than end date");
295
				return false;
296
			}
297
			
298
		}
299
		
300
		
301
		return true;
302
	}
303
	
304
	
305
	/**
306
	 * Si le droit est fixe+modifie ou si le droit deviens fixe
307
	 * @param absences_Right $right
308
	 * @return boolean
309
	 */
310
	protected function isFixedModified(absences_Right $right = null)
311
	{
312
		if (absences_Right::FIXED !== (int) self::$post['kind'] || null === $right)
313
		{
314
			return false;
315
		}
316
		
317
		if (absences_Right::FIXED !== $right->getKind())
318
		{
319
			return true;
320
		}
321
		
322
		
323
		if($right->date_begin_fixed != self::getDateTimeValue('datebeginfx', 'hourbeginfx')
324
				|| $right->date_end_fixed != self::getDateTimeValue('dateendfx', 'hourendfx'))
325
		{
326
			return true;
327
		}
328
		
329
		return false;
330
	}
331
	
332
	
333
	
334
	/**
335
	 * Update rights beneficiaries
336
	 * @param absences_Right 		$right
337
	 * @param Widget_ProgressBar 	$progress
338
	 * @param array					$checked_collections
339
	 */
340
	public static function updateCollectionsBeneficiaries(absences_Right $right, Widget_ProgressBar $progress, Array $checked_collections)
341
	{
342
		$already_exists = array();
343
		$I = $right->getCollectionIterator();
344
		
345
		$total = $I->count() + count($checked_collections);
346
		$pos = 1;
347
		$progress->updateProgress(0);
348
		
349
		foreach($I as $collection)
350
		{
351
			/*@var $collection absences_Collection */
352
		    
353
		    
354
			if (!in_array($collection->id, $checked_collections))
355
			{
356
				
357
				try
358
				{
359
					$collection->removeRight($right);
360
					$collection->unlinkAgentsFromRight($right);
361
				} catch (absences_EntryException $e) {
362
					$agent = $e->entry->getAgent();
363
					echo bab_toHtml(sprintf(absences_translate('Failed to update the period for %s, %s (%s)'), 
364
							$agent->getName(), 
365
							$e->getMessage(),
366
							absences_DateTimePeriod($e->entry->date_begin, $e->entry->date_end))
367
					, BAB_HTML_ALL);
368
				}
369
			} else {
370
			    
371
			    
372
				$already_exists[$collection->id] = true;
373
				
374
				// la collection etait deja cochee, il faut creer les demandes pour les agents qui n'en ont pas
375
				$collection->updateAgents($right, $progress);
376
			}
377
			
378
			$p = ($pos * 100) / $total;
379
			$progress->updateProgress($p);
380
			$pos++;
381
		}
382
		
383
		
384
		
385
		
386
		foreach($checked_collections as $id_collection)
387
		{
388
			$p = ($pos * 100) / $total;
389
			$progress->updateProgress($p);
390
			$pos++;
391
			
392
			
393
			if (isset($already_exists[$id_collection]))
394
			{
395
				continue;
396
			}
397
		
398
			$collection = absences_Collection::getById($id_collection);
399
			$collection->addRight($right);
400
			
401
			try {
402
			    $collection->linkAgentsToRight($right, $progress);
403
			}  catch (Exception $e) {
404
			    // ex: l'url vers caldav est vide mais on utilise caldav
405
			    // exception remontee par LibCaldav
406
			    echo bab_toHtml($e->getMessage(), BAB_HTML_ALL);
407
			}
408
		}
409
		
410
		
411
		$progress->updateProgress(100, absences_translate('Finished'));
412
	}
413
414
	
415
	/**
416
	 * Update fixed vacation periods on an existing right
417
	 * 
418
	 */
419
	public static function updateFixed(absences_Right $right, Widget_ProgressBar $progress)
420
	{
421
		global $babDB;
422
		
423
		
424
		$rightusers = array();
425
		foreach($right->getAgentIterator() as $agent)
426
		{
427
			$rightusers[$agent->id_user] = $agent;
428
		}
429
430
		$entriesusers = array();
431
		$res = $babDB->db_query("select 
432
			vet.*, 
433
			veet.id elem,
434
			veet.quantity 
435
				
436
				from absences_entries_elem veet 
437
					left join absences_entries vet on veet.id_entry=vet.id 
438
			where 
439
				veet.id_right=".$babDB->quote($right->id)." 
440
		");
441
		
442
		$remove_total = $babDB->db_num_rows($res);
443
		
444
		if ($remove_total > 0)
445
		{
446
			// dans ce cas on effectue une premiere progression de la gauge pour le nettoyage
447
			$pos = 0;
448
			while( $arr = $babDB->db_fetch_array($res))
449
			{
450
				if (!isset($arr['id']))
451
				{
452
					throw new Exception('missing entry for elem id='.$arr['elem']);
453
				}
454
				
455
				
456
				$entriesusers[$arr['id_user']] = $arr['id'];
457
				if( !isset($rightusers[$arr['id_user']]) )
458
				{
459
					$progress->updateProgress(100*$pos/$remove_total, sprintf(absences_translate('Remove vacation for user %s'), bab_getUserName($arr['id_user'])));
460
					absences_removeFixedVacation($arr['id']);
461
					$arrnotif = array($arr['id_user']);
462
					// remove vacation and notify
463
					absences_notifyOnVacationChange($arrnotif, $arr['quantity'], $arr['date_begin'], $arr['date_end'], ABSENCES_FIX_DELETE);
0 ignored issues
show
Documentation introduced by
$arrnotif is of type array<integer,?,{"0":"?"}>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
464
				}
465
				
466
				$pos++;
467
			}
468
		}
469
	
470
		// reset gauge
471
		$progress->updateProgress(0, absences_translate('Add and update vacations'));
472
		$update_total = count($rightusers);
473
		$pos = 0;
474
		
475
		$uupd = array();
476
		$uadd = array();
477
		foreach($rightusers as $ukey => $agent )
478
		{
479
480
			
481
			if( isset($entriesusers[$ukey]))
482
			{
483
				// update
484
				$progress->updateProgress(90*$pos/$update_total, sprintf(absences_translate('Update vacation for user %s'), $agent->getName()));
485
				try 
486
				{
487
					absences_updateFixedVacation($ukey, $right);
488
					$uupd[] = $ukey;
489
				} catch(absences_EntryException $e)
490
				{
491
					echo bab_toHtml(sprintf(absences_translate('Failed to update the period for %s, %s'), $agent->getName(), $e->getMessage()), BAB_HTML_ALL);
492
				}
493
				
494
				
495
			}
496
			else
497
			{
498
				// add
499
				$progress->updateProgress(90*$pos/$update_total, sprintf(absences_translate('Add new vacation for user %s'), bab_getUserName($ukey)));
500
				try {
501
					absences_addFixedVacation($ukey, $right);
502
					$uadd[] = $ukey;
503
				} catch(absences_EntryException $e)
504
				{
505
					echo bab_toHtml(sprintf(absences_translate('Failed to add the period for %s, %s'), $agent->getName(), $e->getMessage()), BAB_HTML_ALL);
506
				}
507
			}
508
			
509
			$pos++;
510
		}
511
	
512 View Code Duplication
		if( count($uupd)> 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...
513
		{
514
			$progress->updateProgress(92, absences_translate('Notify users about the modified vacation'));
515
			absences_notifyOnVacationChange($uupd, $right->quantity, $right->date_begin_fixed,  $right->date_end_fixed, ABSENCES_FIX_UPDATE);
0 ignored issues
show
Documentation introduced by
$uupd is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
516
		}
517
		
518 View Code Duplication
		if( count($uadd)> 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...
519
		{
520
			$progress->updateProgress(97, absences_translate('Notify users about the new vacation'));
521
			absences_notifyOnVacationChange($uadd, $right->quantity, $right->date_begin_fixed,  $right->date_end_fixed,  ABSENCES_FIX_ADD);
0 ignored issues
show
Documentation introduced by
$uadd is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
522
		}
523
		
524
		$progress->updateProgress(100, absences_translate('Finished'));
525
	}
526
	
527
528
529
	/**
530
	 * Save posted values
531
	 * @return boolean
532
	 */
533
	public static function save()
534
	{
535
		global $babBody, $babDB;
536
	
537
	
538
		self::$post = $_POST['right'];
539
	
540
		
541
		if (!self::checkPost())
542
		{
543
			return false;
544
		}
545
		
546
		
547
		if (absences_Right::CET === ((int) self::$post['kind']) || absences_Right::FIXED === ((int) self::$post['kind']))
548
		{
549
			$use_in_cet = 0;
550
			$cet_quantity = 0.0;
551
		} else {
552
			$use_in_cet = self::$post['use_in_cet'];
553
			$cet_quantity = str_replace(',', '.', self::$post['cet_quantity']);
554
		}
555
		
556
		
557
		
558
		
559
		if (isset(self::$post['report']) && self::$post['report'])
560
		{
561
			$id_report_type = self::$post['id_report_type'];
562
			$date_end_report = self::getDateValue('date_end_report');
563
			$description_report = self::$post['description_report'];
564
		} else {
565
			$id_report_type = 0;
566
			$date_end_report = '0000-00-00';
567
			$description_report = '';
568
		}
569
		
570
		
571
	
572
		if (!empty(self::$post['id']))
573
		{
574
				
575
			$right = new absences_Right(self::$post['id']);
576
			
577
			if (!$right->getRow())
578
			{
579
				// on ne doit pas passer ici, normallement
580
				$babBody->addError(absences_translate("This right does not exists"));
581
				return false;
582
			}
583
	
584 View Code Duplication
			if($right->date_begin_fixed != '0000-00-00 00:00:00' && absences_Right::FIXED !== (int) self::$post['kind'])
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...
585
				{
586
				$babBody->addError(absences_translate("A fixed vacation right cannot be changed to another right because vacation entries can be associated with it, please delete the right to remove all vacation entries created by this right"));
587
				return false;
588
			}
589
	
590
			
591
			$fixedModified = self::isFixedModified($right);
592
593
594
			$babDB->db_query("
595
	
596
				UPDATE ".ABSENCES_RIGHTS_TBL."
597
				SET 
598
					kind				=".$babDB->quote(self::$post['kind']).",
599
					description			=".$babDB->quote(self::$post['description']).",
600
					id_creditor			=".$babDB->quote($GLOBALS['BAB_SESS_USERID']).",
601
					id_type				=".$babDB->quote(self::$post['id_type']).",
602
					quantity			=".$babDB->quote(self::$post['quantity']).",
603
					quantity_unit		=".$babDB->quote(self::$post['quantity_unit']).",
604
					date_entry			=curdate(),
605
					date_begin			=".$babDB->quote(self::getDateValue('date_begin')).",
606
					date_end			=".$babDB->quote(self::getDateValue('date_end')).",
607
					active				=".$babDB->quote(self::$post['active']).",
608
					cbalance			=".$babDB->quote(self::$post['cbalance']).",
609
					date_begin_valid	=".$babDB->quote(self::getDateValue('date_begin_valid')).",
610
					date_end_valid		=".$babDB->quote(self::getDateValue('date_end_valid')).",
611
					date_begin_fixed	=".$babDB->quote(self::getDateTimeValue('datebeginfx', 'hourbeginfx')).",
612
					date_end_fixed		=".$babDB->quote(self::getDateTimeValue('dateendfx', 'hourendfx')).",
613
			        hide_empty		    =".$babDB->quote(self::$post['hide_empty']).",
614
					no_distribution		=".$babDB->quote(self::$post['no_distribution']).",
615
					use_in_cet			=".$babDB->quote($use_in_cet).",
616
					cet_quantity		=".$babDB->quote($cet_quantity).",
617
					id_rgroup			=".$babDB->quote(self::$post['id_rgroup']).",
618
					earlier				=".$babDB->quote(self::$post['earlier']).",
619
				 	earlier_begin_valid =".$babDB->quote(self::$post['earlier_begin_valid']).",
620
				 	earlier_end_valid	=".$babDB->quote(self::$post['earlier_end_valid']).",
621
					later				=".$babDB->quote(self::$post['later']).",
622
					later_begin_valid	=".$babDB->quote(self::$post['later_begin_valid']).",
623
					later_end_valid		=".$babDB->quote(self::$post['later_end_valid']).",
624
					delay_before		=".$babDB->quote(self::$post['delay_before']).",
625
					id_report_type		=".$babDB->quote($id_report_type).", 
626
					date_end_report		=".$babDB->quote($date_end_report).", 
627
					description_report	=".$babDB->quote($description_report).", 
628
					quantity_alert_days	=".$babDB->quote(self::$post['quantity_alert_days']).", 
629
					quantity_alert_types =".$babDB->quote(isset(self::$post['quantity_alert_types']) ? implode(',',self::$post['quantity_alert_types']) : '').", 
630
					quantity_alert_begin =".$babDB->quote(self::getDateValue('quantity_alert_begin')).", 
631
					quantity_alert_end	=".$babDB->quote(self::getDateValue('quantity_alert_end')).", 
632
					quantity_inc_month	=".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_month'])).",
633
					quantity_inc_max	=".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_max'])).",
634
					
635
					dynconf_types 		=".$babDB->quote(isset(self::$post['dynconf_types']) ? implode(',',self::$post['dynconf_types']) : '').", 
636
					dynconf_begin 		=".$babDB->quote(self::getDateValue('dynconf_begin')).", 
637
					dynconf_end			=".$babDB->quote(self::getDateValue('dynconf_end')).", 
638
					
639
					require_approval	=".$babDB->quote(self::$post['require_approval'])."  
640
				WHERE 
641
					id=".$babDB->quote(self::$post['id'])."
642
	
643
				");
644
	
645
			$id = self::$post['id'];
646
			
647
			$right->addMovement(sprintf(absences_translate('Vacation right updated : %s'), self::$post['description']));
648
			 
649
			// si la quantite du droit a ete changee, enregistrer un mouvement pour tout les utilisateurs concernes
650
			if (!absences_cq($right->quantity, self::$post['quantity']) || $right->quantity_unit !== self::$post['quantity_unit'])
651
			{
652
				foreach($right->getAgentRightIterator() as $agentRight)
653
				{
654
					/*@var $agentRight absences_AgentRight */
655
					if ($agentRight->quantity == '')
656
					{
657
						$agentRight->addMovement(sprintf(absences_translate('The quantity on right %s has been modified from %s to %s for the user %s'), 
658
								self::$post['description'], 
659
								absences_quantity($right->quantity, $right->quantity_unit),
660
								absences_quantity(self::$post['quantity'], self::$post['quantity_unit']),
661
								$agentRight->getAgent()->getName()
662
						));
663
					}
664
				}
665
			}
666
		}
667
		else
668
		{
669
	
670
			require_once $GLOBALS['babInstallPath'].'utilit/uuid.php';
671
			
672
			$fixedModified = self::isFixedModified(null);
673
			
674
			if (!isset(self::$post['active'])) {
675
				self::$post['active'] = 'N';
676
			}
677
	
678
	
679
			$babDB->db_query("
680
	
681
				INSERT into ".ABSENCES_RIGHTS_TBL."
682
					(
683
					kind,
684
					description,
685
					id_creditor,
686
					id_type,
687
					quantity,
688
					quantity_unit,
689
			        createdOn,
690
					date_entry,
691
					date_begin,
692
					date_end,
693
					active,
694
					cbalance,
695
					date_begin_valid,
696
					date_end_valid,
697
					date_begin_fixed,
698
					date_end_fixed,
699
					no_distribution,
700
					use_in_cet,
701
					cet_quantity,
702
					id_rgroup,
703
					
704
					earlier,
705
				 	earlier_begin_valid,
706
				 	earlier_end_valid,
707
					later,
708
					later_begin_valid,
709
					later_end_valid,
710
					delay_before,
711
					
712
					id_report_type,
713
					date_end_report,
714
					description_report,
715
					quantity_alert_days,
716
					quantity_alert_types,
717
					quantity_alert_begin,
718
					quantity_alert_end,
719
					quantity_inc_month,
720
					quantity_inc_max,
721
					
722
					dynconf_types, 
723
					dynconf_begin,
724
					dynconf_end,
725
					
726
					require_approval,
727
					uuid
728
					)
729
				VALUES 
730
					(
731
					".$babDB->quote(self::$post['kind']).",
732
					".$babDB->quote(self::$post['description']).",
733
					".$babDB->quote($GLOBALS['BAB_SESS_USERID']).",
734
					".$babDB->quote(self::$post['id_type']).",
735
					".$babDB->quote(self::$post['quantity']).",
736
					".$babDB->quote(self::$post['quantity_unit']).",
737
			        curdate(),
738
					curdate(),
739
					".$babDB->quote(self::getDateValue('date_begin')).",
740
					".$babDB->quote(self::getDateValue('date_end')).",
741
					".$babDB->quote(self::$post['active']).",
742
					".$babDB->quote(self::$post['cbalance']).",
743
					".$babDB->quote(self::getDateValue('date_begin_valid')).",
744
					".$babDB->quote(self::getDateValue('date_end_valid')).",
745
					".$babDB->quote(self::getDateTimeValue('datebeginfx', 'hourbeginfx')).",
746
					".$babDB->quote(self::getDateTimeValue('dateendfx', 'hourendfx')).",
747
					".$babDB->quote(self::$post['no_distribution']).",
748
					".$babDB->quote($use_in_cet).",
749
					".$babDB->quote($cet_quantity).",
750
					".$babDB->quote(self::$post['id_rgroup']).",
751
					
752
					".$babDB->quote(self::$post['earlier']).",
753
					".$babDB->quote(self::$post['earlier_begin_valid']).",
754
					".$babDB->quote(self::$post['earlier_end_valid']).",
755
					".$babDB->quote(self::$post['later']).",
756
					".$babDB->quote(self::$post['later_begin_valid']).",
757
					".$babDB->quote(self::$post['later_end_valid']).",
758
					".$babDB->quote(self::$post['delay_before']).",
759
					
760
					".$babDB->quote($id_report_type).",
761
					".$babDB->quote($date_end_report).",
762
					".$babDB->quote($description_report).",
763
					".$babDB->quote(self::$post['quantity_alert_days']).",
764
					".$babDB->quote(isset(self::$post['quantity_alert_types']) ? implode(',',self::$post['quantity_alert_types']) : '').",
765
					".$babDB->quote(self::getDateValue('quantity_alert_begin')).",
766
					".$babDB->quote(self::getDateValue('quantity_alert_end')).",
767
					".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_month'])).",
768
					".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_max'])).",
769
					
770
					".$babDB->quote(isset(self::$post['dynconf_types']) ? implode(',',self::$post['dynconf_types']) : '').", 
771
					".$babDB->quote(self::getDateValue('dynconf_begin')).", 
772
					".$babDB->quote(self::getDateValue('dynconf_end')).", 
773
					
774
					".$babDB->quote(self::$post['require_approval']).",
775
					".$babDB->quote(bab_uuid())."
776
					)
777
				");
778
	
779
			$id = $babDB->db_insert_id();
780
			
781
			
782
			$movement = new absences_Movement;
783
			$movement->id_right = $id;
784
			$movement->message = sprintf(absences_translate('Vacation right created : %s'), self::$post['description']);
785
			$movement->save();
786
		}
787
			
788
		self::saveRules($id);
789
		self::saveCet($id);
790
		self::applyDynamicRights($id);
791
		
792
793
		// si aucun beneficiaire, proposer d'en ajouter
794
		$res = $babDB->db_query('SELECT id FROM absences_users_rights WHERE id_right='.$babDB->quote($id));
795
		if ($babDB->db_num_rows($res) === 0)
796
		{
797
			absences_RightAct::goToNoBeneficiaries($id);
798
		}
799
		
800
		
801
		// if fixed, update fixed requests
802
		if ($fixedModified)
803
		{
804
		    absences_RightAct::goToUpdateFixed($id);
805
		}
806
	
807
		
808
		// to list
809
		absences_RightAct::redirect();
810
	}
811
	
812
	
813
	
814
	/**
815
	 * Apply dynamic rights for current beneficiaries
816
	 * @param int $id
817
	 */
818
	protected static function applyDynamicRights($id)
819
	{
820
		$right = new absences_Right($id);
821
		$res = $right->getAgentRightIterator();
822
		
823
		foreach($res as $agentRight)
824
		{
825
			$agentRight->applyDynamicRight();
826
		}
827
	}
828
	
829
	
830
	
831
	protected static function saveCet($id)
832
	{
833
		global $babDB;
834
835
		if (absences_Right::CET !== (int) self::$post['kind'])
836
		{
837
			// save
838
			$babDB->db_query("DELETE FROM absences_rights_cet WHERE id_right=".$babDB->quote($id));
839
			
840
			
841
		} else {
842
			
843
			$per_year = str_replace(',', '.', self::$post['per_year']);
844
			// $per_cet = str_replace(',', '.', self::$post['per_cet']);
845
			$per_cet = 0.0;
846
			$ceiling = str_replace(',', '.', self::$post['ceiling']);
847
			
848
			switch((int) self::$post['min_use_opt'])
849
			{
850
				case 0:
851
					$min_use = 0.0;
852
					break;
853
				case -1:
854
					$min_use = -1.0;
855
					break;
856
				case 1:
857
					$min_use = str_replace(',', '.', self::$post['min_use']);
858
					break;
859
			}
860
			
861
			
862
			
863
			$res = $babDB->db_query("SELECT id FROM absences_rights_cet WHERE id_right=".$babDB->quote($id));
864
			if ($babDB->db_num_rows($res) > 0)
865
			{
866
				list($id_cet) = $babDB->db_fetch_array($res);
867
				$babDB->db_query("
868
					UPDATE absences_rights_cet 
869
					SET
870
						saving_begin	=".$babDB->quote(self::getDateValue('saving_begin')).",
871
						saving_end		=".$babDB->quote(self::getDateValue('saving_end')).",
872
						per_year		=".$babDB->quote($per_year).",
873
						per_cet			=".$babDB->quote($per_cet).",
874
						ceiling			=".$babDB->quote($ceiling).",
875
						min_use			=".$babDB->quote($min_use)."
0 ignored issues
show
Bug introduced by
The variable $min_use 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...
876
						
877
					WHERE
878
						id=".$babDB->quote($id_cet)."
879
				");
880
			}
881
			else
882
			{
883
				$babDB->db_query("
884
					INSERT INTO absences_rights_cet 
885
					(
886
						id_right,
887
						saving_begin,
888
						saving_end,
889
						per_year,
890
						per_cet,
891
						ceiling,
892
						min_use
893
					)
894
					VALUES 
895
					(
896
						".$babDB->quote($id).",
897
						".$babDB->quote(self::getDateValue('saving_begin')).",
898
						".$babDB->quote(self::getDateValue('saving_end')).",
899
						".$babDB->quote($per_year).",
900
						".$babDB->quote($per_cet).",
901
						".$babDB->quote($ceiling).",
902
						".$babDB->quote($min_use)."
903
					)
904
				");
905
			}
906
		}
907
	}
908
	
909
	
910
	
911
	/**
912
	 * Save rules associated to right
913
	 * @param	int		$id			
914
	 */
915
	protected static function saveRules($id)
916
	{
917
		global $babDB;
918
		require_once $GLOBALS['babInstallPath'].'utilit/uuid.php';
919
		
920
		if (absences_Right::FIXED === (int) self::$post['kind'])
921
		{
922
			$babDB->db_query("DELETE FROM ".ABSENCES_RIGHTS_RULES_TBL." WHERE id_right=".$babDB->quote($id));
923
			$babDB->db_query("DELETE FROM ".ABSENCES_RIGHTS_INPERIOD_TBL." WHERE id_right=".$babDB->quote($id));
924
		}
925
		else // rules
926
		{
927
			$validoverlap = isset(self::$post['validoverlap']) ? self::$post['validoverlap'] : 0;
928
			$trigger_type = isset(self::$post['trigger_type']) ? self::$post['trigger_type'] : 0;
929
			$trigger_overlap = isset(self::$post['trigger_overlap']) ? self::$post['trigger_overlap'] : 0;
930
		
931
		
932
			$res = $babDB->db_query("SELECT id FROM ".ABSENCES_RIGHTS_RULES_TBL." WHERE id_right=".$babDB->quote($id));
933
			if ($babDB->db_num_rows($res) > 0)
934
			{
935
				list($id_rule) = $babDB->db_fetch_array($res);
936
				$babDB->db_query("
937
						UPDATE ".ABSENCES_RIGHTS_RULES_TBL."
938
						SET
939
							validoverlap		=".$babDB->quote($validoverlap).",
940
							trigger_nbdays_min	=".$babDB->quote((int) self::$post['trigger_nbdays_min']).",
941
							trigger_nbdays_max	=".$babDB->quote((int) self::$post['trigger_nbdays_max']).",
942
							trigger_type		=".$babDB->quote($trigger_type).",
943
							trigger_p1_begin	=".$babDB->quote(self::getDateValue('trigger_p1_begin')).",
944
							trigger_p1_end		=".$babDB->quote(self::getDateValue('trigger_p1_end')).",
945
							trigger_p2_begin	=".$babDB->quote(self::getDateValue('trigger_p2_begin')).",
946
							trigger_p2_end		=".$babDB->quote(self::getDateValue('trigger_p2_end')).",
947
							trigger_overlap		=".$babDB->quote($trigger_overlap)."
948
						WHERE
949
							id=".$babDB->quote($id_rule)."
950
					");
951
			}
952
			else
953
			{
954
				$babDB->db_query("
955
						INSERT INTO ".ABSENCES_RIGHTS_RULES_TBL."
956
						(
957
							id_right,
958
							validoverlap,
959
							trigger_nbdays_min,
960
							trigger_nbdays_max,
961
							trigger_type,
962
							trigger_p1_begin,
963
							trigger_p1_end,
964
							trigger_p2_begin,
965
							trigger_p2_end,
966
							trigger_overlap
967
						)
968
						VALUES
969
						(
970
							".$babDB->quote($id).",
971
							".$babDB->quote($validoverlap).",
972
							".$babDB->quote((int) self::$post['trigger_nbdays_min']).",
973
							".$babDB->quote((int) self::$post['trigger_nbdays_max']).",
974
							".$babDB->quote($trigger_type).",
975
							".$babDB->quote(self::getDateValue('trigger_p1_begin')).",
976
							".$babDB->quote(self::getDateValue('trigger_p1_end')).",
977
							".$babDB->quote(self::getDateValue('trigger_p2_begin')).",
978
							".$babDB->quote(self::getDateValue('trigger_p2_end')).",
979
							".$babDB->quote($trigger_overlap)."
980
				)
981
						");
982
			}
983
		
984
		
985
			$babDB->db_query('DELETE FROM '.ABSENCES_RIGHTS_INPERIOD_TBL.' WHERE id_right='.$babDB->quote($id));
986
		
987
		
988
			$W = bab_Widgets();
989
			$datePicker = $W->DatePicker();
990
			
991
			foreach(self::$post['inperiod'] as $arr) {
992
				
993
				
994
				$period_start = $datePicker->getISODate($arr['period_start']);
995
				$period_end = $datePicker->getISODate($arr['period_end']);
996
		
997
				if($period_start && $period_end && '0000-00-00' !== $period_start && '0000-00-00' !== $period_end)
998
				{
999
					$babDB->db_query('
1000
						INSERT INTO '.ABSENCES_RIGHTS_INPERIOD_TBL.'
1001
						(
1002
							id_right,
1003
							period_start,
1004
							period_end,
1005
							right_inperiod,
1006
							uuid
1007
						)
1008
						VALUES
1009
						(
1010
							'.$babDB->quote($id).',
1011
							'.$babDB->quote($period_start).',
1012
							'.$babDB->quote($period_end).',
1013
							'.$babDB->quote($arr['right_inperiod']).',
1014
							'.$babDB->quote(bab_uuid()).'
1015
						)
1016
					');
1017
				}
1018
			}
1019
			
1020
			
1021
			$babDB->db_query('DELETE FROM absences_dynamic_configuration WHERE id_right='.$babDB->quote($id));
1022
			
1023
			foreach(self::$post['dynconf'] as $arr) {
1024
			
1025
			
1026
				$test_quantity = (float) str_replace(',', '.', $arr['test_quantity']);
1027
				$quantity = (float) str_replace(',', '.', $arr['quantity']);
1028
				
1029
				if ('-' === $arr['sign'])
1030
				{
1031
					$quantity *= -1;
1032
				}
1033
			
1034
				if(0 !== (int) round(100 * $test_quantity) && 0 !== (int) round(100 * $quantity))
1035
				{
1036
					$babDB->db_query('
1037
						INSERT INTO absences_dynamic_configuration 
1038
						(
1039
							id_right,
1040
							test_quantity,
1041
							quantity
1042
						)
1043
						VALUES
1044
						(
1045
							'.$babDB->quote($id).',
1046
							'.$babDB->quote($test_quantity).',
1047
							'.$babDB->quote($quantity).'
1048
						)
1049
					');
1050
				}
1051
			}
1052
		
1053
		}
1054
	}
1055
	
1056
	
1057 View Code Duplication
	public static function goToNoBeneficiaries($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
1058
	{
1059
		require_once $GLOBALS['babInstallPath'].'utilit/urlincl.php';
1060
		$url = bab_url::get_request('tg');
1061
		$url->idx = 'nobenef';
1062
		$url->idvr = $id;
1063
		$url->location();
1064
		return true;
1065
	}
1066
	
1067
	
1068 View Code Duplication
	public static function goToUpdateFixed($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
1069
	{
1070
		require_once $GLOBALS['babInstallPath'].'utilit/urlincl.php';
1071
		$url = bab_url::get_request('tg');
1072
		$url->idx = 'fixedud';
1073
		$url->idvr = $id;
1074
		$url->location();
1075
		return true;
1076
	}
1077
	
1078
	
1079 View Code Duplication
	public static function redirect()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
1080
	{
1081
		require_once $GLOBALS['babInstallPath'].'utilit/urlincl.php';
1082
		$url = bab_url::get_request('tg');
1083
		$url->idx = 'lrig';
1084
		$url->location();
1085
		return true;
1086
	}
1087
	
1088
}	
1089