Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

DateTimeNode to support datetime objects. #3

Merged
merged 2 commits into from Nov 3, 2011
Jump to file or symbol
Failed to load files and symbols.
+77 −0
Split
View
@@ -47,6 +47,26 @@ public static function define($name = null) {
return $node;
}
+ /**
+ * Given a class name, define a Structr which exports all its
+ * public properties as a map.
+ */
+ public static function defineFromClass($className)
+ {
+ $reflect = new \ReflectionClass($className);
+ $structr = static::define($className)
+ ->pre(function($s) { return (array)$s; })
+ ->isMap();
+
+ foreach ($reflect->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop)
+ {
+ $structr->key($prop->getName())->optional()->isAny()->end();
+ }
+
+ return $structr;
+ }
+
+
public static function getDefinition($name) {
if(!isset(self::$_definitions[$name]))
throw new Exception("Structr definition '{$name}' does not exist");
@@ -9,6 +9,7 @@
use Structr\Tree\Scalar\BooleanNode;
use Structr\Tree\Scalar\NullNode;
use Structr\Tree\Scalar\StringNode;
+use Structr\Tree\Scalar\DateTimeNode;
use Structr\Tree\Scalar\AnyNode;
use Structr\Tree\Composite\ListNode;
@@ -75,6 +76,15 @@ public function isNull() {
}
/**
+ * @return \Structr\Tree\Scalar\DateTime
+ */
+ public function isDateTime() {
+ $this->_prototype = new DateTimeNode($this);
+
+ return $this->_prototype;
+ }
+
+ /**
* @return \Structr\Tree\Scalar\AnyNode
*/
public function isAny() {
@@ -0,0 +1,29 @@
+<?php
+
+namespace Structr\Tree\Scalar;
+
+use Structr\Tree\Base\Node;
+
+use Structr\Exception;
+
+class DateTimeNode extends Node
+{
+
+ protected function _walk_value($value) {
+ $value = parent::_walk_value($value);
+
+ if (!($value instanceof \DateTime))
+ {
+ try
+ {
+ $value = new \DateTime($value);
+ }
+ catch (\Exception $e)
+ {
+ throw new Exception("Failed to parse DateTime from '$value'");
+ }
+ }
+ return $value;
+ }
+
+}
@@ -100,4 +100,22 @@ public function testStringRegexpFail() {
Structr::ize($string)->isString()->regexp("/^\d{4}\w{2}$/")->run();
}
+
+ public function testDateTime() {
+ $variable = new \DateTime;
+
+ $this->assertSame(Structr::ize($variable)
+ ->isDateTime()
+ ->run(), $variable);
+ }
+
+ public function testDateTimeFail() {
+ $this->setExpectedException('\\Structr\\Exception');
+
+ $notADateTime = 'fsdafsd';
+
+ Structr::ize($notADateTime)->isDateTime()->run();
+ }
+
+
}