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