diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ab89a2..a2999f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +3.4.4 (2014-04-11) +------------------ + + * added `net\stubbles\lang\types\Date::castFrom()` + + 3.4.3 (2014-03-25) ------------------ diff --git a/src/main/php/net/stubbles/lang/types/Date.php b/src/main/php/net/stubbles/lang/types/Date.php index fc36365..e295f0c 100644 --- a/src/main/php/net/stubbles/lang/types/Date.php +++ b/src/main/php/net/stubbles/lang/types/Date.php @@ -88,6 +88,28 @@ public static function now(TimeZone $timeZone = null) return new self(time(), $timeZone); } + /** + * casts given value to an instance of Date + * + * @param int|string|\DateTime|Date $value + * @param string $name + * @return Date + * @throws IllegalArgumentException + * @since 3.4.4 + */ + public static function castFrom($value, $name = 'Argument') + { + if (is_int($value) || is_string($value) || $value instanceof \DateTime) { + return new self($value); + } + + if (!($value instanceof Date)) { + throw new IllegalArgumentException($name . ' must be a timestamp, a string containing time info or an instance of \DateTime or net\stubbles\lang\types\Date, but was ' . gettype($value)); + } + + return $value; + } + /** * returns internal date/time handle * @@ -302,4 +324,3 @@ public function __clone() $this->dateTime = clone $this->dateTime; } } -?> \ No newline at end of file diff --git a/src/test/php/net/stubbles/lang/types/DateTestCase.php b/src/test/php/net/stubbles/lang/types/DateTestCase.php index bb935e4..475085b 100644 --- a/src/test/php/net/stubbles/lang/types/DateTestCase.php +++ b/src/test/php/net/stubbles/lang/types/DateTestCase.php @@ -548,5 +548,57 @@ public function asStringIsAnnotatedWithXmlAttribute() ->hasAnnotation('XmlAttribute') ); } + + /** + * @test + * @since 3.4.4 + */ + public function castFromIntCreatesDateInstance() + { + $this->assertEquals(new Date(1187872547), Date::castFrom(1187872547)); + } + + /** + * @test + * @since 3.4.4 + */ + public function castFromStringCreatesDateInstance() + { + $this->assertEquals( + new Date('2007-11-04 14:32:00+1000'), + Date::castFrom('2007-11-04 14:32:00+1000') + ); + } + + /** + * @test + * @since 3.4.4 + */ + public function castFromDateTimeCreatesDateInstance() + { + $this->assertEquals( + new Date('2007-11-04 14:32:00+1000'), + Date::castFrom(new \DateTime('2007-11-04 14:32:00+1000')) + ); + } + + /** + * @test + * @since 3.4.4 + */ + public function castFromDateReturnsSameInstance() + { + $date = new Date('2007-11-04 14:32:00+1000'); + $this->assertSame($date, Date::castFrom($date)); + } + + /** + * @test + * @expectedException net\stubbles\lang\exception\IllegalArgumentException + * @since 3.4.4 + */ + public function castFromOtherValueThrowsIllegalArgumentException() + { + Date::castFrom(new \stdClass()); + } } -?> \ No newline at end of file