fix duration parsing if regexp fails - added some Duration Unit Tests

master
Tanguy Pruvot 2010-10-29 09:59:59 +02:00
rodzic 233c4d9ffc
commit 3d4447fffb
3 zmienionych plików z 52 dodań i 17 usunięć

Wyświetl plik

@ -20,32 +20,30 @@ class SG_iCal_Duration {
* @param $duration string
*/
public function __construct( $duration ) {
if( $duration{0} == 'P' || (($duration{0} == '+' || $duration{0} == '-') && $duration{1} == 'P') ) {
$ts = 0;
if (preg_match('/[\\+\\-]{0,1}P((\d+)W)?((\d+)D)?(T)?((\d+)H)?((\d+)M)?((\d+)S)?/', $duration, $matches) === 1) {
$results = array(
'weeks'=> (int)@ $matches[2],
'days'=> (int)@ $matches[4],
'hours'=> (int)@ $matches[7],
'minutes'=>(int)@ $matches[9],
'seconds'=>(int)@ $matches[11]
);
if (preg_match('/P((\d+)W)?((\d+)D)?(T)?((\d+)H)?((\d+)M)?((\d+)S)?/', $duration, $matches) === 1) {
$results = array(
'weeks'=> (int) $matches[2],
'days'=> (int) $matches[4],
'hours'=> (int)@ $matches[7],
'minutes'=>(int)@ $matches[9],
'seconds'=>(int)@ $matches[11]
); //7-9-11 are optional, so ignore warnings if not found with @
}
$ts = 0;
$ts += $results['seconds'];
$ts += 60 * $results['minutes'];
$ts += 60 * 60 * $results['hours'];
$ts += 24 * 60 * 60 * $results['days'];
$ts += 7 * 24 * 60 * 60 * $results['weeks'];
$dir = ($duration{0} == '-') ? -1 : 1;
$this->dur = $dir * $ts;
} else {
// Invalid duration!
$this->dur = 0;
}
$dir = ($duration{0} == '-') ? -1 : 1;
$this->dur = $dir * $ts;
}
/**

Wyświetl plik

@ -2,6 +2,7 @@
require_once 'PHPUnit/Framework.php';
require_once dirname(__FILE__).'/FreqTest.php';
require_once dirname(__FILE__).'/RecurrenceTest.php';
require_once dirname(__FILE__).'/DurationTest.php';
class Helpers_AllTests {
@ -9,6 +10,7 @@ class Helpers_AllTests {
$suite = new PHPUnit_Framework_TestSuite('Helpers');
$suite->addTestSuite('FreqTest');
$suite->addTestSuite('RecurrenceTest');
$suite->addTestSuite('DurationTest');
return $suite;
}

Wyświetl plik

@ -0,0 +1,35 @@
<?php
require_once dirname(__FILE__) . '/../common.php';
require_once 'PHPUnit/Framework.php';
class DurationTest extends PHPUnit_Framework_TestCase {
public function setUp() {
$this->secsMin = 60;
$this->secsHour = 60 * 60;
$this->secsDay = 24 * 60 * 60;
$this->secsWeek = 7 * 24 * 60 * 60;
}
public function testDurationDateTime() {
//A duration of 10 days, 6 hours and 20 seconds
$dur = new SG_iCal_Duration('P10DT6H0M20S');
$this->assertEquals($this->secsDay*10 + $this->secsHour*6 + 20, $dur->getDuration() );
}
public function testDurationWeek() {
//A duration of 2 weeks
$dur = new SG_iCal_Duration('P2W');
$this->assertEquals($this->secsWeek * 2, $dur->getDuration() );
}
public function testDurationNegative() {
//A duration of -1 day
$dur = new SG_iCal_Duration('-P1D');
$this->assertEquals(-1 * $this->secsDay, $dur->getDuration() );
}
}