Skip to content

Commit

Permalink
trim returns a copy
Browse files Browse the repository at this point in the history
  • Loading branch information
smhg committed Oct 21, 2014
1 parent 8b95b68 commit 157ce1c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 14 deletions.
22 changes: 16 additions & 6 deletions src/Timespan/Timespan.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,19 +101,29 @@ public function merge(Timespan $span)
* Trim timespan to fit within boundaries
* @param DateTime $start
* @param DateTime $end
* @return Timespan
* @return Timespan A new, trimmed, timespan
*/
public function trim(DateTime $start, DateTime $end)
{
if ($this->start < $start) {
$this->start = $start;
$trimmed = clone $this;

if ($start > $trimmed->end || $end < $trimmed->start) {
return;
}

if ($trimmed->start < $start) {
$trimmed->start = $start;
}

if ($trimmed->end > $end) {
$trimmed->end = $end;
}

if ($this->end > $end) {
$this->end = $end;
if ($trimmed->start == $trimmed->end) {
return;
}

return $this;
return $trimmed;
}

/**
Expand Down
33 changes: 25 additions & 8 deletions test/Timespan.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,17 +184,34 @@ public function testMerge($span)
*/
public function testTrim($span)
{
$tmp = clone $span;
$start = clone $tmp->start;
$start = clone $span->start;
$start->modify('+1 day');
$tmp->trim($start, $tmp->end);
$this->assertEquals($start, $tmp->start);
$trimmed = $span->trim($start, $span->end);
$this->assertTrue($trimmed !== $span, 'Trim should not mutate the original span, but return a new one.');
$this->assertEquals($start, $trimmed->start);
$this->assertNotEquals($span->start, $trimmed->start);

$tmp = clone $span;
$end = clone $tmp->end;
$end = clone $span->end;
$end->modify('-1 day');
$tmp->trim($tmp->start, $end);
$this->assertEquals($end, $tmp->end);
$trimmed = $span->trim($span->start, $end);
$this->assertEquals($end, $trimmed->end);
$this->assertNotEquals($span->end, $trimmed->end);

$start = clone $span->start;
$start->modify('+2 week');
$end = clone $span->end;
$end->modify('+2 week');
$this->assertTrue(!$span->trim($start, $end), 'Trim should not return anything if no time is left inside the span.');

$start = clone $span->start;
$start->modify('-2 week');
$end = clone $span->end;
$end->modify('-2 week');
$this->assertTrue(!$span->trim($start, $end), 'Trim should not return anything if no time is left inside the span.');

$start = clone $span->start;
$start->modify('+1 day');
$this->assertTrue(!$span->trim($start, $start), 'Trim should not return anything if no time is left inside the span.');
}

/**
Expand Down

0 comments on commit 157ce1c

Please sign in to comment.