absences_EntryPeriod   B
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 319
Duplicated Lines 17.24 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 62.81%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 55
loc 319
rs 8.2608
ccs 76
cts 121
cp 0.6281
wmc 40
lcom 1
cbo 3

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getById() 0 7 1
A getRow() 0 16 3
A setEntry() 0 5 1
A getEntry() 10 10 2
A checkValidity() 0 10 2
B save() 23 41 3
B getPeriod() 0 16 5
B isOutOfBounds() 0 16 7
A getDurationHours() 0 12 2
C getDurationDays() 0 31 7
A halfDayCache() 0 21 3
A getMorningDays() 11 11 2
A getAfternoonDays() 11 11 2

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_EntryPeriod 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_EntryPeriod, 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
require_once dirname(__FILE__).'/record.class.php';
26
require_once dirname(__FILE__).'/entry.class.php';
27
require_once $GLOBALS['babInstallPath'].'utilit/dateTime.php';
28
29
/**
30
 * Entry planned period
31
 * this is a working period saved when the entry has been created
32
 * the planned period remain after a workschedule modification
33
 * 
34
 * @property int	$id_entry
35
 * @property string $date_begin
36
 * @property string $date_end
37
 * 
38
 */
39
class absences_EntryPeriod extends absences_Record 
40
{
41
42
	/**
43
	 * 
44
	 * @var absences_Entry
45
	 */
46
	private $entry;
47
	
48
	
49
	
50
	/**
51
	 * @return absences_EntryPeriod
52
	 */
53
	public static function getById($id_elem)
54
	{
55
		$entryPeriod = new absences_EntryPeriod;
56
		$entryPeriod->id = $id_elem;
57
	
58
		return $entryPeriod;
59
	}
60
	
61
	
62
	
63
	
64
	/**
65
	 * (non-PHPdoc)
66
	 * @see absences_Record::getRow()
67
	 */
68 31
	public function getRow()
69
	{
70 31
		if (null === $this->row)
71 31
		{
72
			if (!isset($this->id))
73
			{
74
				throw new Exception('Failed to load entry period, missing entry period id');
75
			}
76
	
77
			global $babDB;
78
			$res = $babDB->db_query('SELECT * FROM absences_entries_periods WHERE id='.$babDB->quote($this->id));
79
			$this->setRow($babDB->db_fetch_assoc($res));
80
		}
81
	
82 31
		return $this->row;
83
	}
84
	
85
86
	
87
	
88
	/**
89
	 *
90
	 * @param absences_Entry $entry
91
	 * @return absences_EntryPeriod
92
	 */
93 36
	public function setEntry(absences_Entry $entry)
94
	{
95 36
		$this->entry = $entry;
96 36
		return $this;
97
	}
98
	
99
	
100
	/**
101
	 * @return absences_Entry
102
	 */
103 27 View Code Duplication
	public function getEntry()
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...
104
	{
105 27
		if (!isset($this->entry))
106 27
		{
107
			$row = $this->getRow();
108
			$this->entry = absences_Entry::getById($row['id_entry']);
109
		}
110
	
111 27
		return $this->entry;
112
	}
113
	
114
	
115
	/**
116
	 * Check validity before saving an element
117
	 * @return bool
118
	 */
119
	public function checkValidity()
120
	{
121
122
		if ($this->date_end <= $this->date_begin)
123
		{
124
			throw new UnexpectedValueException('date_begin must be lower than date_end');
125
		}
126
		
127
		return true;
128
	}
129
	
130
	
131
132
	
133
	/**
134
	 * Save element (insert or update or delete)
135
	 */
136
	public function save()
137
	{
138
		global $babDB;
139
		
140
		if (isset($this->id))
141
		{
142
143
			$babDB->db_query("
144
				UPDATE absences_entries_periods 
145
				SET 
146
			        date_begin=".$babDB->quote($this->date_begin).",
147
			        date_end=".$babDB->quote($this->date_end)." 
148
				WHERE 
149
					id=".$babDB->quote($this->id)
150
			);
151
152
			
153 View Code Duplication
		} else {
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...
154
			
155
			if (isset($this->id_entry))
156
			{
157
				$id_entry = $this->id_entry;
158
			} else {
159
				$entry = $this->getEntry();
160
				$id_entry = $entry->id;
161
			}
162
			
163
			$babDB->db_query("
164
				INSERT INTO absences_entries_periods 
165
					(id_entry, date_begin, date_end)
166
				VALUES 
167
				(
168
					" .$babDB->quote($id_entry). ",
169
			        " .$babDB->quote($this->date_begin). ",
170
			        " .$babDB->quote($this->date_end). "
171
				)
172
			");
173
			
174
			$this->id = $babDB->db_insert_id();
175
		}
176
	}
177
	
178
	
179
	/**
180
	 * get a period on boundaries
181
	 * 
182
	 * @param string $begin    Optional limit to use for duration
183
	 * @param string $end      Optional limit to use for duration
184
	 * 
185
	 * @return array
186
	 */
187 29
	private function getPeriod($begin = null, $end = null)
188
	{
189 29
	    if (!isset($begin)) {
190 26
	        $begin = $this->date_begin;
191 29
	    } elseif ($begin < $this->date_begin) {
192 1
	        $begin = $this->date_begin;
193 1
	    }
194
	     
195 29
	    if (!isset($end)) {
196 26
	        $end = $this->date_end;
197 29
	    } elseif ($end > $this->date_end) {
198 1
	        $end = $this->date_end;
199 1
	    }
200
	     
201 29
	    return array($begin, $end);
202
	}
203
	
204
	
205
	/**
206
	 * Test if the restrictive boundaries exclude the totality of period
207
	 * 
208
	 * @param string $begin    Optional limit to use for duration
209
	 * @param string $end      Optional limit to use for duration
210
	 * 
211
	 * @return bool
212
	 */
213 31
	private function isOutOfBounds($begin = null, $end = null)
214
	{
215 31
	    if (!isset($begin) && !isset($end)) {
216 26
	        return false;
217
	    }
218
	    
219 5
	    if (isset($begin) && $begin >= $this->date_end) {
220 2
	        return true;
221
	    }
222
	    
223 3
	    if (isset($end) && $end <= $this->date_begin) {
224 2
	        return true;
225
	    }
226
	    
227 3
	    return false;
228
	}
229
	
230
	
231
	/**
232
	 * Get duration in days for the working period
233
	 * 
234
	 * @param string $begin    Optional limit to use for duration
235
	 * @param string $end      Optional limit to use for duration
236
	 * 
237
	 * @return float
238
	 */
239 28
	public function getDurationDays($begin = null, $end = null)
240
	{
241 28
	    if ($this->isOutOfBounds($begin, $end)) {
242 2
	        return 0;
243
	    }
244
	    
245 27
	    list($begin, $end) = $this->getPeriod($begin, $end);
246 27
	    $dtbegin = BAB_DateTime::fromIsoDateTime($begin);
247 27
	    $dtend = BAB_DateTime::fromIsoDateTime($end);
248
	    
249 27
	    $hb = sprintf('%02d:%02d', $dtbegin->getHour(), $dtbegin->getMinute());
250 27
	    $he = sprintf('%02d:%02d', $dtend->getHour(), $dtend->getMinute());
251
	    
252 27
	    if ($hb === $he) {
253
	        return 0;
254
	    }
255
256 27
	    if ($he <= '12:00') {
257 20
	        return $this->getMorningDays(); // 0.5 or 0
258
	    }
259
	    
260 26
	    if ($hb >= '12:00') {
261 26
	        return $this->getAfternoonDays(); // 0.5 or 0
262
	    }
263
	    
264 7
	    if ($hb <= '12:00' && $he >= '12:00') {
265 7
	        $duration = $this->getMorningDays();
266 7
	        $duration += $this->getAfternoonDays();
267 7
	        return $duration;
268
	    }
269
	}
270
	
271
	/**
272
	 * Get or set the cache for half day
273
	 * @param string $period  am|pm
274
	 * @return string the entry_period dates
275
	 */
276 27
	private function halfDayCache($period)
277
	{
278 27
	    $date = substr($this->date_begin, 0, 10);
279 27
	    $entry = $this->getEntry();
280
	    
281
282 27
	    if (!isset($entry->_getDurationDays_halfDays[$date])) {
283 27
	        $entry->_getDurationDays_halfDays[$date] = array(
284 27
	            'am' => null,
285
	            'pm' => null
286 27
	        );
287 27
	    }
288
	    
289 27
	    if (isset($entry->_getDurationDays_halfDays[$date][$period])) {
290 25
	        return $entry->_getDurationDays_halfDays[$date][$period];
291
	    }
292
	    
293 27
	    $entry->_getDurationDays_halfDays[$date][$period] = $this->date_begin.'/'.$this->date_end;
294
	     
295 27
	    return $entry->_getDurationDays_halfDays[$date][$period];
296
	}
297
	
298
	
299
	/**
300
	 * Get number of days for the morning of the day
301
	 * if more than one period exists in the morning, the half day duration will be positive only for the first period
302
	 * @return float
303
	 */
304 27 View Code Duplication
	public function getMorningDays()
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...
305
	{
306 27
	    $period = $this->halfDayCache('am');
307
	    
308 27
	    if ($this->date_begin.'/'.$this->date_end == $period) {
309
	        // this period is the first for the morning, it is accounted
310 27
	        return 0.5;
311
	    }
312
	    
313
	    return 0;
314
	}
315
	
316
	
317
	/**
318
	 * Get number of days for the afternoon of the day
319
	 * if more than one period exists in the morning, the half day duration will be positive only for the first period
320
	 * @return float
321
	 */
322 26 View Code Duplication
	public function getAfternoonDays()
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...
323
	{
324 26
	    $period = $this->halfDayCache('pm');
325
	     
326 26
	    if ($this->date_begin.'/'.$this->date_end == $period) {
327
	        // this period is the first for the afternoon, it is accounted
328 26
	        return 0.5;
329
	    }
330
	     
331 7
	    return 0;
332
	}
333
	
334
	
335
	
336
	
337
	/**
338
	 * Get duration in hours for the working period
339
	 * 
340
	 * @param string $begin    Optional limit to use for duration
341
	 * @param string $end      Optional limit to use for duration
342
	 * 
343
	 * @return float
344
	 */
345 27
	public function getDurationHours($begin = null, $end = null)
346
	{
347 27
	    if ($this->isOutOfBounds($begin, $end)) {
348 2
	        return 0;
349
	    }
350
	    
351 26
	    list($begin, $end) = $this->getPeriod($begin, $end);
352 26
	    $dtbegin = BAB_DateTime::fromIsoDateTime($begin);
353 26
	    $dtend = BAB_DateTime::fromIsoDateTime($end);
354
	    
355 26
	    return (($dtend->getTimeStamp() - $dtbegin->getTimeStamp()) / 3600);
356
	}
357
}