1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Itmedia\ZippyBusBundle\Schedule; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Актальная дата для расписания |
9
|
|
|
*/ |
10
|
|
|
class ScheduleDate |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var \DateTimeImmutable |
15
|
|
|
*/ |
16
|
|
|
private $datetime; |
17
|
|
|
|
18
|
|
|
const WORKDAY = 'workday'; |
19
|
|
|
|
20
|
|
|
const WEEKEND = 'weekend'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Date constructor. |
24
|
|
|
* @param \DateTimeImmutable $datetime |
25
|
|
|
*/ |
26
|
|
|
public function __construct(\DateTimeImmutable $datetime) |
27
|
|
|
{ |
28
|
|
|
$this->datetime = $datetime; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
public static function createNow(): ScheduleDate |
33
|
|
|
{ |
34
|
|
|
return new ScheduleDate(new \DateTimeImmutable('now')); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
|
38
|
|
View Code Duplication |
public static function createWeekend(): ScheduleDate |
|
|
|
|
39
|
|
|
{ |
40
|
|
|
$datetime = new \DateTimeImmutable('now'); |
41
|
|
|
$day = (int)$datetime->format('N'); |
42
|
|
|
|
43
|
|
|
if ($day !== 7) { |
44
|
|
|
$datetime = $datetime->add( |
45
|
|
|
new \DateInterval( |
46
|
|
|
sprintf('P%sD', 7 - $day) |
47
|
|
|
)); |
48
|
|
|
} |
49
|
|
|
return new ScheduleDate($datetime); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
|
53
|
|
View Code Duplication |
public static function createWorkday(): ScheduleDate |
|
|
|
|
54
|
|
|
{ |
55
|
|
|
$datetime = new \DateTimeImmutable('now'); |
56
|
|
|
$day = (int)$datetime->format('N'); |
57
|
|
|
|
58
|
|
|
if ($day > 5) { |
59
|
|
|
$datetime = $datetime->sub( |
60
|
|
|
new \DateInterval( |
61
|
|
|
sprintf('P2D') |
62
|
|
|
)); |
63
|
|
|
} |
64
|
|
|
return new ScheduleDate($datetime); |
|
|
|
|
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* День недели |
70
|
|
|
* @return int |
71
|
|
|
*/ |
72
|
|
|
public function getWeekDay(): int |
73
|
|
|
{ |
74
|
|
|
$day = (int)$this->datetime->format('N'); |
75
|
|
|
|
76
|
|
|
if ((int)$this->datetime->format('H') < 4) { |
77
|
|
|
$day = $day === 1 ? 7 : $day - 1; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $day; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
|
84
|
|
|
public function getTypeDay(): string |
85
|
|
|
{ |
86
|
|
|
return in_array($this->getWeekDay(), [6, 7], true) ? self::WEEKEND : self::WORKDAY; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
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.