Skip to content
Permalink
Browse files

Add tests for DateTimeType marshalling.

Add the various cases for marshalling datetimes.
  • Loading branch information...
markstory committed Mar 2, 2014
1 parent 6a278f4 commit 8d633748b0a341b8540a9e18284ea0ff0c1e4f41
Showing with 94 additions and 0 deletions.
  1. +38 −0 src/Database/Type/DateTimeType.php
  2. +56 −0 tests/TestCase/Database/Type/DateTimeTypeTest.php
@@ -55,4 +55,42 @@ public function toPHP($value, Driver $driver) {
return $value;
}
/**
* Convert request data into a datetime object.
*
* @param mixed $value Request data
* @return \DateTime
*/
public function marshall($value) {
try {
if ($value === '' || $value === null || $value === false || $value === true) {
return $value;
} elseif (is_numeric($value)) {
$date = new DateTime('@' . $value);
} elseif (is_string($value)) {
$date = new DateTime($value);
}
if (isset($date)) {
return $date;
}
} catch (\Exception $e) {
return $value;
}
$value += ['second' => 0];
$date = new DateTime();
$date->setTime(0, 0, 0);
if (isset($value['year'], $value['month'], $value['day'])) {
$date->setDate($value['year'], $value['month'], $value['day']);
}
if (isset($value['hour'], $value['minute'])) {
if (isset($value['meridian'])) {
$value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
}
$date->setTime($value['hour'], $value['minute'], $value['second']);
}
return $date;
}
}
@@ -69,4 +69,60 @@ public function testToDatabase() {
$this->assertEquals('2013-08-12 15:16:17', $result);
}
/**
* Data provider for marshall()
*
* @return array
*/
public static function marshallProvider() {
return [
// invalid types.
[null, null],
[false, false],
[true, true],
['', ''],
['derpy', 'derpy'],
['2013-nope!', '2013-nope!'],
// valid string types
['1392387900', new \DateTime('@1392387900')],
[1392387900, new \DateTime('@1392387900')],
['2014-02-14', new \DateTime('2014-02-14')],
['2014-02-14 13:14:15', new \DateTime('2014-02-14 13:14:15')],
// valid array types
[
['year' => 2014, 'month' => 2, 'day' => 14, 'hour' => 13, 'minute' => 14, 'second' => 15],
new \DateTime('2014-02-14 13:14:15')
],
[
[
'year' => 2014, 'month' => 2, 'day' => 14,
'hour' => 1, 'minute' => 14, 'second' => 15,
'meridian' => 'am'
],
new \DateTime('2014-02-14 01:14:15')
],
[
[
'year' => 2014, 'month' => 2, 'day' => 14,
'hour' => 1, 'minute' => 14, 'second' => 15,
'meridian' => 'pm'
],
new \DateTime('2014-02-14 13:14:15')
],
];
}
/**
* test marshalling data.
*
* @dataProvider marshallProvider
* @return void
*/
public function testMarshall($value, $expected) {
$result = $this->type->marshall($value);
$this->assertEquals($expected, $result);
}
}

0 comments on commit 8d63374

Please sign in to comment.
You can’t perform that action at this time.