[Stopwatch] Fix some logic

This commit is contained in:
Victor Berchet 2012-01-25 14:27:59 +01:00
parent 8c3505e33c
commit 416a2a46df
3 changed files with 34 additions and 6 deletions

View File

@ -76,7 +76,7 @@ class Stopwatch
public function start($name, $category = null)
{
if (!isset($this->events[$name])) {
$this->events[$name] = new StopwatchEvent($this->origin, $category);
$this->events[$name] = new StopwatchEvent($this->origin ?: microtime(true) * 1000, $category);
}
return $this->events[$name]->start();

View File

@ -28,10 +28,12 @@ class StopwatchEvent
*
* @param integer $origin The origin time in milliseconds
* @param string $category The event category
*
* @throws \InvalidArgumentException When the raw time is not valid
*/
public function __construct($origin, $category = null)
{
$this->origin = $origin;
$this->origin = $this->formatTime($origin);
$this->category = is_string($category) ? $category : 'default';
$this->started = array();
$this->periods = array();
@ -132,7 +134,7 @@ class StopwatchEvent
*/
public function getEndTime()
{
return count($this->periods) ? $this->periods[count($this->periods) - 1][1] : 0;
return ($count = count($this->periods)) ? $this->periods[$count - 1][1] : 0;
}
/**
@ -147,11 +149,29 @@ class StopwatchEvent
$total += $period[1] - $period[0];
}
return sprintf('%.1f', $total);
return $this->formatTime($total);
}
private function getNow()
{
return sprintf('%.1f', microtime(true) * 1000 - $this->origin);
return $this->formatTime(microtime(true) * 1000 - $this->origin);
}
/**
* Formats a time.
*
* @param numerical $time A raw time
*
* @return float The formatted time
*
* @throws \InvalidArgumentException When the raw time is not valid
*/
private function formatTime($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('The time must be a numerical value');
}
return round($time, 1);
}
}

View File

@ -31,7 +31,7 @@ class StopwatchEventTest extends \PHPUnit_Framework_TestCase
$event = new StopwatchEvent(microtime(true) * 1000);
$this->assertEquals('default', $event->getCategory());
$event = new StopwatchEvent(time(), 'cat');
$event = new StopwatchEvent(microtime(true) * 1000, 'cat');
$this->assertEquals('cat', $event->getCategory());
}
@ -141,4 +141,12 @@ class StopwatchEventTest extends \PHPUnit_Framework_TestCase
$end = $event->getEndTime();
$this->assertTrue($end >= 18 && $end <= 30);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInvalidOriginThrowsAnException()
{
new StopwatchEvent("abc");
}
}