Time   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 0
dl 0
loc 77
ccs 31
cts 31
cp 1
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A fromString() 0 10 2
A fromDateTime() 0 4 1
A isSame() 0 4 1
A isAfter() 0 12 4
A isBefore() 0 8 2
A isSameOrAfter() 0 4 2
A toDateTime() 0 4 1
A format() 0 4 1
A __toString() 0 4 1
1
<?php
2
3
namespace Webfactor\Laravel\OpeningHours\Entities;
4
5
use DateTime;
6
use DateTimeInterface;
7
use Webfactor\Laravel\OpeningHours\Exceptions\InvalidTimeString;
8
9
class Time
10
{
11
    /** @var int */
12
    protected $hours;
13
14
    /** @var int */
15
    protected $minutes;
16
17 53
    protected function __construct(int $hours, int $minutes)
18
    {
19 53
        $this->hours = $hours;
20 53
        $this->minutes = $minutes;
21 53
    }
22
23 54
    public static function fromString(string $string): self
24
    {
25 54
        if (! preg_match('/^([0-1][0-9])|(2[0-4]):[0-5][0-9]$/', $string)) {
26 1
            throw InvalidTimeString::forString($string);
27
        }
28
29 53
        list($hours, $minutes) = explode(':', $string);
30
31 53
        return new self($hours, $minutes);
32
    }
33
34 15
    public static function fromDateTime(DateTimeInterface $dateTime): self
35
    {
36 15
        return self::fromString($dateTime->format('H:i'));
37
    }
38
39 33
    public function isSame(Time $time): bool
40
    {
41 33
        return (string) $this === (string) $time;
42
    }
43
44 32
    public function isAfter(Time $time): bool
45
    {
46 32
        if ($this->isSame($time)) {
47 1
            return false;
48
        }
49
50 32
        if ($this->hours > $time->hours) {
51 32
            return true;
52
        }
53
54 15
        return $this->hours === $time->hours && $this->minutes >= $time->minutes;
55
    }
56
57 30
    public function isBefore(Time $time): bool
58
    {
59 30
        if ($this->isSame($time)) {
60 4
            return false;
61
        }
62
63 30
        return ! $this->isAfter($time);
64
    }
65
66 29
    public function isSameOrAfter(Time $time): bool
67
    {
68 29
        return $this->isSame($time) || $this->isAfter($time);
69
    }
70
71 44
    public function toDateTime(): DateTime
72
    {
73 44
        return (new DateTime('1970-01-01 00:00:00'))->setTime($this->hours, $this->minutes);
74
    }
75
76 44
    public function format(string $format = 'H:i'): string
77
    {
78 44
        return $this->toDateTime()->format($format);
79
    }
80
81 37
    public function __toString(): string
82
    {
83 37
        return $this->format();
84
    }
85
}
86