1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* This file is part of the daikon-cqrs/value-object project. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Daikon\ValueObject; |
10
|
|
|
|
11
|
|
|
use Daikon\Interop\Assertion; |
12
|
|
|
|
13
|
|
|
final class Range implements ValueObjectInterface |
14
|
|
|
{ |
15
|
|
|
private array $range; |
16
|
|
|
|
17
|
|
|
/** @param self $comparator */ |
18
|
|
|
public function equals($comparator): bool |
19
|
|
|
{ |
20
|
|
|
Assertion::isInstanceOf($comparator, self::class); |
21
|
|
|
return $this->toNative() === $comparator->toNative(); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** @param array $value */ |
25
|
|
|
public static function fromNative($value): self |
26
|
|
|
{ |
27
|
|
|
Assertion::isArray($value, 'Trying to create Range from unsupported value type.'); |
28
|
|
|
Assertion::count($value, 2, 'Range must have two values.'); |
29
|
|
|
Assertion::allInteger($value, 'Range values are not integers.'); |
30
|
|
|
|
31
|
|
|
$values = array_values($value); |
32
|
|
|
Assertion::greaterOrEqualThan($values[1], $values[0], 'Range end must be greater than or equal to start.'); |
33
|
|
|
|
34
|
|
|
return new self($values); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function toNative(): array |
38
|
|
|
{ |
39
|
|
|
return $this->range; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function getStart(): int |
43
|
|
|
{ |
44
|
|
|
return $this->range[0]; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function getEnd(): int |
48
|
|
|
{ |
49
|
|
|
return $this->range[1]; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function getSize(): int |
53
|
|
|
{ |
54
|
|
|
return ($this->range[1] - $this->range[0]) + 1; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function __toString(): string |
58
|
|
|
{ |
59
|
|
|
return sprintf('[%d,%d]', $this->range[0], $this->range[1]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function __construct(array $range) |
63
|
|
|
{ |
64
|
|
|
$this->range = $range; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|