Completed
Push — master ( a182e4...7f1093 )
by Paul
04:26
created

vacfixedincl.php ➔ absences_updateFixedVacation()   D

Complexity

Conditions 9
Paths 11

Size

Total Lines 105
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 9
eloc 55
c 2
b 2
f 0
nc 11
nop 2
dl 0
loc 105
rs 4.8196

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/************************************************************************
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
require_once dirname(__FILE__).'/entry.class.php';
26
require_once dirname(__FILE__).'/entry_elem.class.php';
27
28
/**
29
 * Add a fixed vacation for a user
30
 * appelle lors de la creation/modification d'un droit de conge pre attribue
31
 * 
32
 * @param int $id_user
33
 * @param absences_Right $right
34
 * @param string $remarks
35
 * 
36
 * @throws absences_EntryException
37
 * 
38
 * @return bool
39
 */
40
function absences_addFixedVacation($id_user, absences_Right $right, $remarks = '')
41
{
42
43
	
44
	$entry = new absences_Entry;
45
	$entry->id_user = $id_user;
46
	$entry->date_begin = $right->date_begin_fixed;
47
	$entry->date_end = $right->date_end_fixed;
48
	$entry->comment = $remarks;
49
	$entry->status = 'Y';
50
	$entry->creation_type = absences_Entry::CREATION_FIXED;
51
	
52
	$elem = new absences_EntryElem();
53
	$elem->setEntry($entry);
54
	$elem->id_right = $right->id;
55
	$elem->quantity = $right->quantity;
56
	$elem->date_begin = $right->date_begin_fixed;
57
	$elem->date_end = $right->date_end_fixed;
58
	$entry->addElement($elem);
59
	
60
	try {
61
		$validity = $entry->checkValidity();
62
	} catch(absences_EntryException $e)
63
	{
64
		if (!$e->blocking)
65
		{
66
			// ignorer les erreur non bloquantes
67
			$validity = true;
68
		} else {
69
			
70
			throw $e;
71
		}
72
73
	}
74
	
75
	if ($validity)
76
	{
77
		$entry->save();
78
		$entry->saveElements();
79
		$entry->createPlannedPeriods();
80
		$entry->savePlannedPeriods();
81
		
82
		$entry->addElementsMovements(sprintf(absences_translate('Add the fixed vacation right %s to the user %s'), $right->description, bab_getUserName($id_user)));
83
		
84
		$entry->updateCalendar();
85
		absences_createPeriod($entry->id);
86
		
87
		$entry->applyDynamicRight();
88
		
89
		return true;
90
	}
91
	
92
	// on doit etre sur qu'il n'y a pas de demande existante
93
	// ile ne devrais pas y en avoir normalement
94
	if (false === absences_updateFixedVacation($id_user, $right)) {
95
	
96
	    return false; // tout est normal
97
	}
98
	
99
	// une mise a jour a ete faite
100
	return false;
101
}
102
103
104
105
/**
106
 * Update dates and quantity of a fixed vacation for a user
107
 * appelle lors de la creation/modification d'un droit de conge pre attribue
108
 * 
109
 * @param	int		             $id_user
110
 * @param 	absences_Right		 $right
111
 * 
112
 * @return bool
113
 */
114
function absences_updateFixedVacation($id_user, absences_Right $right)
115
{
116
	global $babDB;
117
	require_once $GLOBALS['babInstallPath'].'utilit/dateTime.php';
118
	
119
	$res = $babDB->db_query("select 
120
		vet.id 	entry, 
121
		veet.id entryelem 
122
	from ".ABSENCES_ENTRIES_ELEM_TBL." veet 
123
		left join ".ABSENCES_ENTRIES_TBL." vet 
124
		on veet.id_entry=vet.id 
125
		where veet.id_right=".$babDB->quote($right->id)." 
126
			and vet.id_user=".$babDB->quote($id_user)."
127
	");
128
	
129
	
130
	if (0 === $babDB->db_num_rows($res)) {
131
		return false;
132
	}
133
134
	$entry = null;
135
136
	while( $arr = $babDB->db_fetch_assoc($res))
137
	{
138
		if (isset($entry))
139
		{
140
			// already updated, all other entries must not exists
141
			absences_delete_request($arr['entry']);
142
			continue;
143
		}
144
		
145
		if (absences_Right::FIXED !== (int) $right->kind) {
146
		    continue;
147
		}
148
		
149
		$entry = new absences_Entry;
150
		$entry->id = (int) $arr['entry'];
151
		$entry->date_begin = $right->date_begin_fixed;
152
		$entry->date_end = $right->date_end_fixed;
153
		$entry->id_user = $id_user;
154
		$entry->status = 'Y';
155
		$entry->creation_type = absences_Entry::CREATION_FIXED;
156
		
157
		$entry_elem = new absences_EntryElem;
158
		$entry_elem->id = (int) $arr['entryelem'];
159
		$entry_elem->id_right = $right->id;
160
		$entry_elem->id_entry = $entry->id;
161
		$entry_elem->quantity = $right->quantity;
162
		$entry_elem->date_begin = $right->date_begin_fixed;
163
		$entry_elem->date_end = $right->date_end_fixed;
164
		$entry_elem->setEntry($entry);
165
		
166
		$entry->addElement($entry_elem);
167
		
168
		
169
		try {
170
			$validity = $entry->checkValidity();
171
		} catch(absences_EntryException $e)
172
		{
173
			if (!$e->blocking)
174
			{
175
				// ignorer les erreur non bloquantes
176
				$validity = true;
177
			} else {
178
		
179
				throw $e;
180
			}
181
		
182
		}
183
		
184
185
		$begin = BAB_DateTime::fromIsoDateTime($entry->date_begin);
186
		$end = BAB_DateTime::fromIsoDateTime($entry->date_end);
187
		
188
		
189
		if ($validity)
190
		{
191
			$entry->save();
192
			$entry->saveElements();
193
			$entry->createPlannedPeriods();
194
			$entry->savePlannedPeriods();
195
			
196
			$entry->addElementsMovements(sprintf(absences_translate('Update fixed vacation %s for the user %s'), $right->description, bab_getUserName($id_user)));
197
			
198
			$entry->applyDynamicRight();
199
200
				
201
			// try to update event copy in other backend (caldav)
202
			absences_updatePeriod($arr['entry'], $begin, $end);
203
			
204
		} else {
205
			absences_removeFixedVacation($arr['entry']);
206
			
207
			// remove period in calendar backend
208
			if ($period = absences_getPeriod($arr['entry'], $id_user, $begin, $end)) {
209
			     $period->delete();
210
			}
211
		}
212
		
213
		
214
		
215
	}
216
217
	return true;
218
}
219
220
221
/**
222
 * Remove fixed vacation
223
 * return false if entry cannot be removed (entry not found), or true on success
224
 * 
225
 * @param int $id_entry
226
 * 
227
 * @return bool
228
 */
229
function absences_removeFixedVacation($id_entry)
230
{
231
	global $babDB;
232
	require_once $GLOBALS['babInstallPath'].'utilit/dateTime.php';
233
	
234
	$res = $babDB->db_query("select id_user, date_begin, date_end FROM ".ABSENCES_ENTRIES_TBL." where id=".$babDB->quote($id_entry));
235
	$arr = $babDB->db_fetch_array($res);
236
	
237
	
238
	if (!$arr)
239
	{
240
		// not found
241
		return false;
242
	}
243
244
	$babDB->db_query("DELETE from ".ABSENCES_ENTRIES_TBL." where id='".$babDB->db_escape_string($id_entry)."'");
245
	$babDB->db_query("DELETE from ".ABSENCES_ENTRIES_ELEM_TBL." where id_entry='".$babDB->db_escape_string($id_entry)."'");
246
	$babDB->db_query("UPDATE absences_movement SET id_request='0' where request_class='absences_Entry' AND id_request='".$babDB->db_escape_string($id_entry)."'");
247
	
248
	absences_clearCalendars();
249
	
250
	// try to delete event copy in other backend (caldav)
251
	
252
	$begin = BAB_DateTime::fromIsoDateTime($arr['date_begin']);
253
	$end = BAB_DateTime::fromIsoDateTime($arr['date_end']);
254
	$period = absences_getPeriod($id_entry, $arr['id_user'],  $begin, $end);
255
	if ($period) {
256
		$period->delete();
257
	}
258
	
259
	return true;
260
}
261
262
263
264
265
/**
266
 * Update all fixed rights for one user
267
 * @param	int		$id_user
268
 * @param	array 	$messages
269
 */
270
function absences_updateFixedRightsOnUser($id_user, &$messages) {
271
272
	global $babDB, $babBody;
273
	
274
	/* @var $babBody babBody */
275
276
	// trouver les droits fixes de l'utilisateur
277
	
278
	$agent = absences_Agent::getFromIdUser($id_user);
279
	$I = $agent->getAgentRightUserIterator();
280
	$I->setKind(absences_Right::FIXED);
281
282
	foreach($I as $agentRight)
283
	{
284
		/*@var $agentRight absences_AgentRight */
285
		
286
		$right = $agentRight->getRight();
287
		
288
		try {
289
			if (false === absences_updateFixedVacation($id_user, $right)) {
0 ignored issues
show
Bug introduced by
It seems like $right defined by $agentRight->getRight() on line 286 can be null; however, absences_updateFixedVacation() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
290
				absences_addFixedVacation($id_user, $right);
0 ignored issues
show
Bug introduced by
It seems like $right defined by $agentRight->getRight() on line 286 can be null; however, absences_addFixedVacation() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
291
			}
292
		}
293
		catch(absences_EntryException $e)
294
		{
295
			$messages[] = sprintf(
296
				absences_translate('Failed to update period for right "%s", %s (%s)'), 
297
				$right->description, 
298
				$e->getMessage(), 
299
				absences_DateTimePeriod($e->entry->date_begin, $e->entry->date_end)
300
			);
301
		}
302
	}
303
304
}
305
306
307
/**
308
 * Tester si la demande du droit a date fixe existe
309
 * @return bool
310
 */
311
function absences_isFixedCreated($id_user, $id_right)
312
{
313
    global $babDB;
314
    $res = $babDB->db_query("
315
            SELECT * 
316
        FROM 
317
            absences_entries e,
318
            absences_entries_elem ee
319
        WHERE 
320
            e.id=ee.id_entry 
321
            AND e.id_user=".$babDB->quote($id_user)." 
322
            AND ee.id_right=".$babDB->quote($id_right)
323
    );
324
    
325
    return (0 < $babDB->db_num_rows($res));
326
}
327