ILIAS  release_8 Revision v8.24
Range.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
21namespace ILIAS\Data;
22
30class Range
31{
32 protected int $start;
33 protected int $length;
34
35 public function __construct(int $start, int $length)
36 {
37 $this->checkStart($start);
38 $this->checkLength($length);
39 $this->start = $start;
40 $this->length = $length;
41 }
42
43 protected function checkStart(int $start): void
44 {
45 if ($start < 0) {
46 throw new \InvalidArgumentException("Start must be a positive number (or 0)", 1);
47 }
48 }
49
50 protected function checkLength(int $length): void
51 {
52 if ($length < 0) {
53 throw new \InvalidArgumentException("Length must be larger or equal then 0", 1);
54 }
55 }
56
57 public function unpack(): array
58 {
60 }
61
62 public function getStart(): int
63 {
64 return $this->start;
65 }
66
67 public function getLength(): int
68 {
69 return $this->length;
70 }
71
76 public function getEnd(): int
77 {
78 if ($this->length === PHP_INT_MAX) {
79 return PHP_INT_MAX;
80 }
81
82 return $this->start + $this->length;
83 }
84
85 public function withStart(int $start): Range
86 {
87 $this->checkStart($start);
88 $clone = clone $this;
89 $clone->start = $start;
90 return $clone;
91 }
92
93 public function withLength(int $length): Range
94 {
95 $this->checkLength($length);
96 $clone = clone $this;
97 $clone->length = $length;
98 return $clone;
99 }
100
104 public function croppedTo(int $max): Range
105 {
106 if ($max > $this->getEnd()) {
107 return $this;
108 }
109
110 if ($this->getStart() > $max) {
111 return new self($max, 0);
112 }
113
114 return $this->withLength($max - $this->getStart());
115 }
116}
A simple class to express a range of whole positive numbers.
Definition: Range.php:31
withLength(int $length)
Definition: Range.php:93
withStart(int $start)
Definition: Range.php:85
croppedTo(int $max)
This will create a range that is guaranteed to not exceed $max.
Definition: Range.php:104
getEnd()
getEnd will return the (excluded) endpoint.
Definition: Range.php:76
checkStart(int $start)
Definition: Range.php:43
checkLength(int $length)
Definition: Range.php:50
__construct(int $start, int $length)
Definition: Range.php:35