From d852805aea5553eac59e7ad2ea36cb929b6b1130 Mon Sep 17 00:00:00 2001 From: Richard Klees Date: Tue, 24 Oct 2023 15:34:31 +0200 Subject: [PATCH] Data: add Range::croppedTo --- src/Data/Range.php | 20 ++++++++++++++++++-- tests/Data/RangeTest.php | 36 ++++++++++++++++++++++++------------ 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/src/Data/Range.php b/src/Data/Range.php index 0b24eebeebbd..ae2a00ea376b 100644 --- a/src/Data/Range.php +++ b/src/Data/Range.php @@ -31,8 +31,8 @@ protected function checkStart(int $start): void protected function checkLength(int $length): void { - if ($length < 1) { - throw new \InvalidArgumentException("Length must be larger than 0", 1); + if ($length < 0) { + throw new \InvalidArgumentException("Length must be larger or equal then 0", 1); } } @@ -71,4 +71,20 @@ public function withLength(int $length): Range $clone->length = $length; return $clone; } + + /** + * This will create a range that is guaranteed to not exceed $max. + */ + public function croppedTo(int $max): Range + { + if ($max > $this->getEnd()) { + return $this; + } + + if ($this->getStart() > $max) { + return new self($max, 0); + } + + return $this->withLength($this->getLength() - $this->getEnd() + $max); + } } diff --git a/tests/Data/RangeTest.php b/tests/Data/RangeTest.php index 1f970d81f6c2..fc2eb6bf0726 100644 --- a/tests/Data/RangeTest.php +++ b/tests/Data/RangeTest.php @@ -88,15 +88,6 @@ public function testNegativeLength(Range $range): void $range = $range->withLength(-1); } - /** - * @depends testFactory - */ - public function testNullLength(Range $range): void - { - $this->expectException(InvalidArgumentException::class); - $range = $range->withLength(0); - } - public function testConstructionWrongStart(): void { $this->expectException(InvalidArgumentException::class); @@ -111,10 +102,31 @@ public function testConstructionWrongLength(): void $range = $f->range(1, -2); } - public function testConstructionNullLength(): void + /** + * @dataProvider cropCases + */ + public function testCroppedTo($start, $length, $max, $has_changed): void { - $this->expectException(InvalidArgumentException::class); $f = new ILIAS\Data\Factory(); - $range = $f->range(1, 0); + $range = $f->range($start, $length); + $cropped = $range->croppedTo($max); + + if (!$has_changed) { + $this->assertEquals($range, $cropped); + } else { + $this->assertEquals(min($max, $start), $cropped->getStart()); + $this->assertEquals($max, $cropped->getEnd()); + } + } + + public function cropCases(): array + { + return [ + [0, 100, 1000, false], + [0, 1000, 100, true], + [50, 100, 75, true], + [50, 100, 200, false], + [100, 100, 50, true] + ]; } }