Browse Source

Merge pull request #3380 from cakephp/3.0-time-tweaks

3.0 time tweaks
Mark Story 12 years ago
parent
commit
642142529d
2 changed files with 49 additions and 1 deletions
  1. 24 1
      src/Utility/Time.php
  2. 25 0
      tests/TestCase/Utility/TimeTest.php

+ 24 - 1
src/Utility/Time.php

@@ -16,13 +16,14 @@ namespace Cake\Utility;
 
 use Carbon\Carbon;
 use IntlDateFormatter;
+use JsonSerializable;
 
 /**
  * Extends the built-in DateTime class to provide handy methods and locale-aware
  * formatting helpers
  *
  */
-class Time extends Carbon {
+class Time extends Carbon implements JsonSerializable {
 
 /**
  * The format to use when formatting a time using `Cake\Utility\Time::i18nFormat()`
@@ -637,4 +638,26 @@ class Time extends Carbon {
 		static::$_toStringFormat = $format;
 	}
 
+/**
+ * Returns a string that should be serialized when converting this object to json
+ *
+ * @return string
+ */
+	public function jsonSerialize() {
+		return $this->format(static::ISO8601);
+	}
+
+/**
+ * Returns the data that should be displayed when debugging this object
+ *
+ * @return array
+ */
+	public function __debugInfo() {
+		return [
+			'time' => $this->format(static::ISO8601),
+			'timezone' => $this->getTimezone()->getName(),
+			'fixedNowTime' => $this->hasTestNow() ? $this->getTestNow()->format(static::ISO8601) : false
+		];
+	}
+
 }

+ 25 - 0
tests/TestCase/Utility/TimeTest.php

@@ -567,6 +567,31 @@ class TimeTest extends TestCase {
 	}
 
 /**
+ * Tests encoding a Time object as json
+ *
+ * @return void
+ */
+	public function testJsonEnconde() {
+		$time = new Time('2014-04-20 10:10:10');
+		$this->assertEquals('"2014-04-20T10:10:10+0000"', json_encode($time));
+	}
+
+/**
+ * Tests debugInfo
+ *
+ * @return void
+ */
+	public function testDebugInfo() {
+		$time = new Time('2014-04-20 10:10:10');
+		$expected = [
+			'time' => '2014-04-20T10:10:10+0000',
+			'timezone' => 'UTC',
+			'fixedNowTime' => Time::getTestNow()->toISO8601String()
+		];
+		$this->assertEquals($expected, $time->__debugInfo());
+	}
+
+/**
  * Cusotm assert to allow for variation in the version of the intl library, where
  * some translations contain a few extra commas.
  *