Skip to content
This repository has been archived by the owner on Jan 16, 2019. It is now read-only.

Commit

Permalink
Merge pull request #85 from mikey179/master
Browse files Browse the repository at this point in the history
add net\stubbles\lang\types\Date::castFrom()
  • Loading branch information
mikey179 committed Apr 11, 2014
2 parents 10bfad6 + 7342460 commit 94c7d92
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 2 deletions.
6 changes: 6 additions & 0 deletions 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)
------------------

Expand Down
23 changes: 22 additions & 1 deletion src/main/php/net/stubbles/lang/types/Date.php
Expand Up @@ -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
*
Expand Down Expand Up @@ -302,4 +324,3 @@ public function __clone()
$this->dateTime = clone $this->dateTime;
}
}
?>
54 changes: 53 additions & 1 deletion src/test/php/net/stubbles/lang/types/DateTestCase.php
Expand Up @@ -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());
}
}
?>

0 comments on commit 94c7d92

Please sign in to comment.