Passed
Push — master ( d2520f...3f8ec2 )
by Michael
02:50
created

Calendar_Week   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 314
Duplicated Lines 14.01 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 44
loc 314
rs 8.3206
c 0
b 0
f 0
wmc 51
lcom 1
cbo 4

12 Methods

Rating   Name   Duplication   Size   Complexity  
A setFirst() 0 3 1
C thisWeek() 0 24 9
A getHelper() 0 3 1
B nextWeek() 0 17 8
B thisYear() 0 22 4
B setSelection() 0 12 6
A findFirstDay() 0 8 4
C build() 0 32 7
A setTimestamp() 0 6 1
A __construct() 0 9 1
B prevWeek() 0 17 8
A setLast() 0 3 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 Calendar_Week 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 Calendar_Week, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 47 and the first side effect is on line 53.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5
/**
6
 * Contains the Calendar_Week class.
7
 *
8
 * PHP versions 4 and 5
9
 *
10
 * LICENSE: Redistribution and use in source and binary forms, with or without
11
 * modification, are permitted provided that the following conditions are met:
12
 * 1. Redistributions of source code must retain the above copyright
13
 *    notice, this list of conditions and the following disclaimer.
14
 * 2. Redistributions in binary form must reproduce the above copyright
15
 *    notice, this list of conditions and the following disclaimer in the
16
 *    documentation and/or other materials provided with the distribution.
17
 * 3. The name of the author may not be used to endorse or promote products
18
 *    derived from this software without specific prior written permission.
19
 *
20
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
21
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23
 * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
24
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
 *
31
 * @category  Date and Time
32
 *
33
 * @author    Harry Fuecks <[email protected]>
34
 * @author    Lorenzo Alberton <[email protected]>
35
 * @copyright 2003-2007 Harry Fuecks, Lorenzo Alberton
36
 * @license   http://www.debian.org/misc/bsd.license  BSD License (3 Clause)
37
 *
38
 * @link      http://pear.php.net/package/Calendar
39
 */
40
41
/**
42
 * Allows Calendar include path to be redefined.
43
 *
44
 * @ignore
45
 */
46
if (!defined('CALENDAR_ROOT')) {
47
    define('CALENDAR_ROOT', 'Calendar/');
48
}
49
50
/**
51
 * Load Calendar base class.
52
 */
53
require_once CALENDAR_ROOT . 'Calendar.php';
54
55
/**
56
 * Represents a Week and builds Days in tabular format<br>
57
 * <code>
58
 * require_once __DIR__ . '/Calendar/Week.php';
59
 * $Week = new Calendar_Week(2003, 10, 1); Oct 2003, 1st tabular week
60
 * echo '<tr>';
61
 * while ($Day = $Week->fetch()) {
62
 *     if ($Day->isEmpty()) {
63
 *         echo '<td>&nbsp;</td>';
64
 *     } else {
65
 *         echo '<td>'.$Day->thisDay().'</td>';
66
 *      }
67
 * }
68
 * echo '</tr>';
69
 * </code>.
70
 *
71
 * @category  Date and Time
72
 *
73
 * @author    Harry Fuecks <[email protected]>
74
 * @author    Lorenzo Alberton <[email protected]>
75
 * @copyright 2003-2007 Harry Fuecks, Lorenzo Alberton
76
 * @license   http://www.debian.org/misc/bsd.license  BSD License (3 Clause)
77
 *
78
 * @link      http://pear.php.net/package/Calendar
79
 */
80
class Calendar_Week extends Calendar
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
81
{
82
    /**
83
     * Instance of Calendar_Table_Helper.
84
     *
85
     * @var Calendar_Table_Helper
86
     */
87
    public $tableHelper;
88
89
    /**
90
     * Stores the timestamp of the first day of this week.
91
     *
92
     * @var object
93
     */
94
    public $thisWeek;
95
96
    /**
97
     * Stores the timestamp of first day of previous week.
98
     *
99
     * @var object
100
     */
101
    public $prevWeek;
102
103
    /**
104
     * Stores the timestamp of first day of next week.
105
     *
106
     * @var object
107
     */
108
    public $nextWeek;
109
110
    /**
111
     * Used by build() to set empty days.
112
     *
113
     * @var bool
114
     */
115
    public $firstWeek = false;
116
117
    /**
118
     * Used by build() to set empty days.
119
     *
120
     * @var bool
121
     */
122
    public $lastWeek = false;
123
124
    /**
125
     * First day of the week (0=sunday, 1=monday...).
126
     *
127
     * @var bool
128
     */
129
    public $firstDay = 1;
130
131
    /**
132
     * Constructs Week.
133
     *
134
     * @param int $y        year e.g. 2003
135
     * @param int $m        month e.g. 5
136
     * @param int $d        a day of the desired week
137
     * @param int $firstDay (optional) first day of week (e.g. 0 for Sunday, 2 for Tuesday etc.)
138
     */
139
    public function __construct($y, $m, $d, $firstDay = null)
140
    {
141
        require_once CALENDAR_ROOT . 'Table/Helper.php';
142
        parent::__construct($y, $m, $d);
143
        $this->firstDay    = $this->defineFirstDayOfWeek($firstDay);
0 ignored issues
show
Documentation Bug introduced by
The property $firstDay was declared of type boolean, but $this->defineFirstDayOfWeek($firstDay) is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
144
        $this->tableHelper = new Calendar_Table_Helper($this, $this->firstDay);
145
        $this->thisWeek    = $this->tableHelper->getWeekStart($y, $m, $d, $this->firstDay);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->tableHelper->getW...m, $d, $this->firstDay) of type integer is incompatible with the declared type object of property $thisWeek.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
146
        $this->prevWeek    = $this->tableHelper->getWeekStart($y, $m, $d - $this->cE->getDaysInWeek($this->thisYear(), $this->thisMonth(), $this->thisDay()), $this->firstDay);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->tableHelper->getW...ay()), $this->firstDay) of type integer is incompatible with the declared type object of property $prevWeek.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
147
        $this->nextWeek    = $this->tableHelper->getWeekStart($y, $m, $d + $this->cE->getDaysInWeek($this->thisYear(), $this->thisMonth(), $this->thisDay()), $this->firstDay);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->tableHelper->getW...ay()), $this->firstDay) of type integer is incompatible with the declared type object of property $nextWeek.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
148
    }
149
150
    /**
151
     * Defines the calendar by a timestamp (Unix or ISO-8601), replacing values
152
     * passed to the constructor.
153
     *
154
     * @param int|string $ts Unix or ISO-8601 timestamp
155
     */
156
    public function setTimestamp($ts)
157
    {
158
        parent::setTimestamp($ts);
159
        $this->thisWeek = $this->tableHelper->getWeekStart($this->year, $this->month, $this->day, $this->firstDay);
0 ignored issues
show
Bug introduced by
$this->firstDay of type boolean is incompatible with the type integer expected by parameter $firstDay of Calendar_Table_Helper::getWeekStart(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

159
        $this->thisWeek = $this->tableHelper->getWeekStart($this->year, $this->month, $this->day, /** @scrutinizer ignore-type */ $this->firstDay);
Loading history...
Documentation Bug introduced by
It seems like $this->tableHelper->getW...->day, $this->firstDay) of type integer is incompatible with the declared type object of property $thisWeek.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
160
        $this->prevWeek = $this->tableHelper->getWeekStart($this->year, $this->month, $this->day - $this->cE->getDaysInWeek($this->thisYear(), $this->thisMonth(), $this->thisDay()), $this->firstDay);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->tableHelper->getW...ay()), $this->firstDay) of type integer is incompatible with the declared type object of property $prevWeek.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
161
        $this->nextWeek = $this->tableHelper->getWeekStart($this->year, $this->month, $this->day + $this->cE->getDaysInWeek($this->thisYear(), $this->thisMonth(), $this->thisDay()), $this->firstDay);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->tableHelper->getW...ay()), $this->firstDay) of type integer is incompatible with the declared type object of property $nextWeek.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
162
    }
163
164
    /**
165
     * Builds Calendar_Day objects for this Week.
166
     *
167
     * @param array $sDates (optional) Calendar_Day objects representing selected dates
168
     *
169
     * @return bool
170
     */
171
    public function build($sDates = [])
172
    {
173
        require_once CALENDAR_ROOT . 'Day.php';
174
        $year  = $this->cE->stampToYear($this->thisWeek);
175
        $month = $this->cE->stampToMonth($this->thisWeek);
176
        $day   = $this->cE->stampToDay($this->thisWeek);
177
        $end   = $this->cE->getDaysInWeek($this->thisYear(), $this->thisMonth(), $this->thisDay());
178
179
        for ($i = 1; $i <= $end; ++$i) {
180
            $stamp              = $this->cE->dateToStamp($year, $month, $day++);
181
            $this->children[$i] = new Calendar_Day($this->cE->stampToYear($stamp), $this->cE->stampToMonth($stamp), $this->cE->stampToDay($stamp));
182
        }
183
184
        //set empty days (@see Calendar_Month_Weeks::build())
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% 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...
185
        if ($this->firstWeek) {
186
            $eBefore = $this->tableHelper->getEmptyDaysBefore();
187
            for ($i = 1; $i <= $eBefore; ++$i) {
188
                $this->children[$i]->setEmpty();
189
            }
190
        }
191
        if ($this->lastWeek) {
192
            $eAfter = $this->tableHelper->getEmptyDaysAfterOffset();
193
            for ($i = $eAfter + 1; $i <= $end; ++$i) {
194
                $this->children[$i]->setEmpty();
195
            }
196
        }
197
198
        if (count($sDates) > 0) {
199
            $this->setSelection($sDates);
200
        }
201
202
        return true;
203
    }
204
205
    /**
206
     * Set as first week of the month.
207
     *
208
     * @param bool $state whether it's first or not
209
     */
210
    public function setFirst($state = true)
211
    {
212
        $this->firstWeek = $state;
213
    }
214
215
    /**
216
     * Set as last week of the month.
217
     *
218
     * @param bool $state whether it's lasst or not
219
     */
220
    public function setLast($state = true)
221
    {
222
        $this->lastWeek = $state;
223
    }
224
225
    /**
226
     * Called from build().
227
     *
228
     * @param array $sDates Calendar_Day objects representing selected dates
229
     * @return bool|void
230
     */
231
    public function setSelection($sDates)
232
    {
233
        foreach ($sDates as $sDate) {
234
            foreach ($this->children as $key => $child) {
235
                if ($child->thisDay() == $sDate->thisDay() && $child->thisMonth() == $sDate->thisMonth()
236
                    && $child->thisYear() == $sDate->thisYear()) {
237
                    $this->children[$key] = $sDate;
238
                    $this->children[$key]->setSelected();
239
                }
240
            }
241
        }
242
        reset($this->children);
243
    }
244
245
    /**
246
     * Returns the value for this year.
247
     *
248
     * When a on the first/last week of the year, the year of the week is
249
     * calculated according to ISO-8601
250
     *
251
     * @param string $format return value format ['int' | 'timestamp' | 'object' | 'array']
252
     *
253
     * @return int e.g. 2003 or timestamp
254
     */
255
    public function thisYear($format = 'int')
256
    {
257
        if (null !== $this->thisWeek) {
258
            $tmp_cal = new Calendar();
259
            $tmp_cal->setTimestamp($this->thisWeek);
0 ignored issues
show
Bug introduced by
$this->thisWeek of type object is incompatible with the type integer|string expected by parameter $ts of Calendar::setTimestamp(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

259
            $tmp_cal->setTimestamp(/** @scrutinizer ignore-type */ $this->thisWeek);
Loading history...
260
            $first_dow    = $tmp_cal->thisDay('array');
261
            $days_in_week = $tmp_cal->cE->getDaysInWeek($tmp_cal->year, $tmp_cal->month, $tmp_cal->day);
262
            $tmp_cal->day += $days_in_week;
263
            $last_dow     = $tmp_cal->thisDay('array');
264
265
            if ($first_dow['year'] == $last_dow['year']) {
266
                return $first_dow['year'];
267
            }
268
269
            if ($last_dow['day'] > floor($days_in_week / 2)) {
270
                return $last_dow['year'];
271
            }
272
273
            return $first_dow['year'];
274
        }
275
276
        return parent::thisYear();
277
    }
278
279
    /**
280
     * Gets the value of the previous week, according to the requested format.
281
     *
282
     * @param string $format ['timestamp' | 'n_in_month' | 'n_in_year' | 'array']
283
     *
284
     * @return mixed
285
     */
286
    public function prevWeek($format = 'n_in_month')
287
    {
288
        switch (strtolower($format)) {
289
            case 'int':
290
            case 'n_in_month':
291
                return $this->firstWeek ? null : $this->thisWeek('n_in_month') - 1;
292
            case 'n_in_year':
293
                return $this->cE->getWeekNInYear($this->cE->stampToYear($this->prevWeek), $this->cE->stampToMonth($this->prevWeek), $this->cE->stampToDay($this->prevWeek));
294
            case 'array':
295
                return $this->toArray($this->prevWeek);
296
            case 'object':
297
                require_once CALENDAR_ROOT . 'Factory.php';
298
299
                return Calendar_Factory::createByTimestamp('Week', $this->prevWeek);
300
            case 'timestamp':
301
            default:
302
                return $this->prevWeek;
303
        }
304
    }
305
306
    /**
307
     * Gets the value of the current week, according to the requested format.
308
     *
309
     * @param string $format ['timestamp' | 'n_in_month' | 'n_in_year' | 'array']
310
     *
311
     * @return mixed
312
     */
313
    public function thisWeek($format = 'n_in_month')
314
    {
315
        switch (strtolower($format)) {
316
            case 'int':
317
            case 'n_in_month':
318
                if ($this->firstWeek) {
319
                    return 1;
320
                }
321
                if ($this->lastWeek) {
322
                    return $this->cE->getWeeksInMonth($this->thisYear(), $this->thisMonth(), $this->firstDay);
323
                }
324
325
                return $this->cE->getWeekNInMonth($this->thisYear(), $this->thisMonth(), $this->thisDay(), $this->firstDay);
326
            case 'n_in_year':
327
                return $this->cE->getWeekNInYear($this->cE->stampToYear($this->thisWeek), $this->cE->stampToMonth($this->thisWeek), $this->cE->stampToDay($this->thisWeek));
328
            case 'array':
329
                return $this->toArray($this->thisWeek);
330
            case 'object':
331
                require_once CALENDAR_ROOT . 'Factory.php';
332
333
                return Calendar_Factory::createByTimestamp('Week', $this->thisWeek);
334
            case 'timestamp':
335
            default:
336
                return $this->thisWeek;
337
        }
338
    }
339
340
    /**
341
     * Gets the value of the following week, according to the requested format.
342
     *
343
     * @param string $format ['timestamp' | 'n_in_month' | 'n_in_year' | 'array']
344
     *
345
     * @return mixed
346
     */
347
    public function nextWeek($format = 'n_in_month')
348
    {
349
        switch (strtolower($format)) {
350
            case 'int':
351
            case 'n_in_month':
352
                return $this->lastWeek ? null : $this->thisWeek('n_in_month') + 1;
353
            case 'n_in_year':
354
                return $this->cE->getWeekNInYear($this->cE->stampToYear($this->nextWeek), $this->cE->stampToMonth($this->nextWeek), $this->cE->stampToDay($this->nextWeek));
355
            case 'array':
356
                return $this->toArray($this->nextWeek);
357
            case 'object':
358
                require_once CALENDAR_ROOT . 'Factory.php';
359
360
                return Calendar_Factory::createByTimestamp('Week', $this->nextWeek);
361
            case 'timestamp':
362
            default:
363
                return $this->nextWeek;
364
        }
365
    }
366
367
    /**
368
     * Returns the instance of Calendar_Table_Helper.
369
     * Called from Calendar_Validator::isValidWeek.
370
     *
371
     * @return Calendar_Table_Helper
372
     */
373
    public function &getHelper()
374
    {
375
        return $this->tableHelper;
376
    }
377
378
    /**
379
     * Makes sure theres a value for $this->day.
380
     */
381
    public function findFirstDay()
382
    {
383
        if (!count($this->children) > 0) {
384
            $this->build();
385
            foreach ($this->children as $Day) {
386
                if (!$Day->isEmpty()) {
387
                    $this->day = $Day->thisDay();
388
                    break;
389
                }
390
            }
391
        }
392
    }
393
}
394