Split out ConvertableTimestamp class

* Make TimestampException a regular exception.
* Make DatabaseBase use ConvertableTimestamp.

Change-Id: I849737c9c187e8e0c6e080887ec0656e034f80d2
This commit is contained in:
Aaron Schulz 2016-09-15 15:46:01 -07:00
parent e5999cc51d
commit e10f272a05
10 changed files with 454 additions and 416 deletions

View file

@ -280,6 +280,7 @@ $wgAutoloadLocalClasses = [
'ConvertExtensionToRegistration' => __DIR__ . '/maintenance/convertExtensionToRegistration.php',
'ConvertLinks' => __DIR__ . '/maintenance/convertLinks.php',
'ConvertUserOptions' => __DIR__ . '/maintenance/convertUserOptions.php',
'ConvertableTimestamp' => __DIR__ . '/includes/libs/time/ConvertableTimestamp.php',
'ConverterRule' => __DIR__ . '/languages/ConverterRule.php',
'Cookie' => __DIR__ . '/includes/libs/Cookie.php',
'CookieJar' => __DIR__ . '/includes/libs/CookieJar.php',
@ -1410,7 +1411,7 @@ $wgAutoloadLocalClasses = [
'ThumbnailRenderJob' => __DIR__ . '/includes/jobqueue/jobs/ThumbnailRenderJob.php',
'TidyUpBug37714' => __DIR__ . '/maintenance/tidyUpBug37714.php',
'TiffHandler' => __DIR__ . '/includes/media/Tiff.php',
'TimestampException' => __DIR__ . '/includes/exception/TimestampException.php',
'TimestampException' => __DIR__ . '/includes/libs/time/TimestampException.php',
'Timing' => __DIR__ . '/includes/libs/Timing.php',
'Title' => __DIR__ . '/includes/Title.php',
'TitleArray' => __DIR__ . '/includes/TitleArray.php',

View file

@ -1992,56 +1992,7 @@ function wfRestoreWarnings() {
# Autodetect, convert and provide timestamps of various types
/**
* Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
*/
define( 'TS_UNIX', 0 );
/**
* MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
*/
define( 'TS_MW', 1 );
/**
* MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
*/
define( 'TS_DB', 2 );
/**
* RFC 2822 format, for E-mail and HTTP headers
*/
define( 'TS_RFC2822', 3 );
/**
* ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
*
* This is used by Special:Export
*/
define( 'TS_ISO_8601', 4 );
/**
* An Exif timestamp (YYYY:MM:DD HH:MM:SS)
*
* @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
* DateTime tag and page 36 for the DateTimeOriginal and
* DateTimeDigitized tags.
*/
define( 'TS_EXIF', 5 );
/**
* Oracle format time.
*/
define( 'TS_ORACLE', 6 );
/**
* Postgres format time.
*/
define( 'TS_POSTGRES', 7 );
/**
* ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
*/
define( 'TS_ISO_8601_BASIC', 9 );
require_once __DIR__ . '/libs/time/defines.php';
/**
* Get a timestamp string in one of various formats

View file

@ -28,171 +28,15 @@
*
* @since 1.20
*/
class MWTimestamp {
class MWTimestamp extends ConvertableTimestamp {
/**
* Standard gmdate() formats for the different timestamp types.
* Get a timestamp instance in GMT
*
* @param bool|string $ts Timestamp to set, or false for current time
* @return MWTimestamp The instance
*/
private static $formats = [
TS_UNIX => 'U',
TS_MW => 'YmdHis',
TS_DB => 'Y-m-d H:i:s',
TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
TS_ISO_8601_BASIC => 'Ymd\THis\Z',
TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
TS_RFC2822 => 'D, d M Y H:i:s',
TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
TS_POSTGRES => 'Y-m-d H:i:s',
];
/**
* The actual timestamp being wrapped (DateTime object).
* @var DateTime
*/
public $timestamp;
/**
* Make a new timestamp and set it to the specified time,
* or the current time if unspecified.
*
* @since 1.20
*
* @param bool|string|int|float|DateTime $timestamp Timestamp to set, or false for current time
*/
public function __construct( $timestamp = false ) {
if ( $timestamp instanceof DateTime ) {
$this->timestamp = $timestamp;
} else {
$this->setTimestamp( $timestamp );
}
}
/**
* Set the timestamp to the specified time, or the current time if unspecified.
*
* Parse the given timestamp into either a DateTime object or a Unix timestamp,
* and then store it.
*
* @since 1.20
*
* @param string|bool $ts Timestamp to store, or false for now
* @throws TimestampException
*/
public function setTimestamp( $ts = false ) {
$m = [];
$da = [];
$strtime = '';
// We want to catch 0, '', null... but not date strings starting with a letter.
if ( !$ts || $ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
$uts = time();
$strtime = "@$uts";
} elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
# TS_DB
} elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
# TS_EXIF
} elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
# TS_MW
} elseif ( preg_match( '/^(-?\d{1,13})(\.\d+)?$/D', $ts, $m ) ) {
# TS_UNIX
$strtime = "@{$m[1]}"; // http://php.net/manual/en/datetime.formats.compound.php
} elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
# TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
$strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
str_replace( '+00:00', 'UTC', $ts ) );
} elseif ( preg_match(
'/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
$ts,
$da
) ) {
# TS_ISO_8601
} elseif ( preg_match(
'/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
$ts,
$da
) ) {
# TS_ISO_8601_BASIC
} elseif ( preg_match(
'/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
$ts,
$da
) ) {
# TS_POSTGRES
} elseif ( preg_match(
'/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
$ts,
$da
) ) {
# TS_POSTGRES
} elseif ( preg_match(
# Day of week
'/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
# dd Mon yyyy
'\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
# hh:mm:ss
'[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
$ts
) ) {
# TS_RFC2822, accepting a trailing comment.
# See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
# The regex is a superset of rfc2822 for readability
$strtime = strtok( $ts, ';' );
} elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
# TS_RFC850
$strtime = $ts;
} elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
# asctime
$strtime = $ts;
} else {
throw new TimestampException( __METHOD__ . ": Invalid timestamp - $ts" );
}
if ( !$strtime ) {
$da = array_map( 'intval', $da );
$da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
$strtime = call_user_func_array( "sprintf", $da );
}
try {
$final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
} catch ( Exception $e ) {
throw new TimestampException( __METHOD__ . ': Invalid timestamp format.', $e->getCode(), $e );
}
if ( $final === false ) {
throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
}
$this->timestamp = $final;
}
/**
* Get the timestamp represented by this object in a certain form.
*
* Convert the internal timestamp to the specified format and then
* return it.
*
* @since 1.20
*
* @param int $style Constant Output format for timestamp
* @throws TimestampException
* @return string The formatted timestamp
*/
public function getTimestamp( $style = TS_UNIX ) {
if ( !isset( self::$formats[$style] ) ) {
throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
}
$output = $this->timestamp->format( self::$formats[$style] );
if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
$output .= ' GMT';
}
if ( $style == TS_MW && strlen( $output ) !== 14 ) {
throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
'the specified format' );
}
return $output;
public static function getInstance( $ts = false ) {
return new static( $ts );
}
/**
@ -329,52 +173,6 @@ class MWTimestamp {
return $ts;
}
/**
* @since 1.20
*
* @return string
*/
public function __toString() {
return $this->getTimestamp();
}
/**
* Calculate the difference between two MWTimestamp objects.
*
* @since 1.22
* @param MWTimestamp $relativeTo Base time to calculate difference from
* @return DateInterval|bool The DateInterval object representing the
* difference between the two dates or false on failure
*/
public function diff( MWTimestamp $relativeTo ) {
return $this->timestamp->diff( $relativeTo->timestamp );
}
/**
* Set the timezone of this timestamp to the specified timezone.
*
* @since 1.22
* @param string $timezone Timezone to set
* @throws TimestampException
*/
public function setTimezone( $timezone ) {
try {
$this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
} catch ( Exception $e ) {
throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
}
}
/**
* Get the timezone of this timestamp.
*
* @since 1.22
* @return DateTimeZone The timezone
*/
public function getTimezone() {
return $this->timestamp->getTimezone();
}
/**
* Get the localized timezone message, if available.
*
@ -395,17 +193,6 @@ class MWTimestamp {
}
}
/**
* Format the timestamp in a given format.
*
* @since 1.22
* @param string $format Pattern to format in
* @return string The formatted timestamp
*/
public function format( $format ) {
return $this->timestamp->format( $format );
}
/**
* Get a timestamp instance in the server local timezone ($wgLocaltimezone)
*
@ -419,15 +206,4 @@ class MWTimestamp {
$timestamp->setTimezone( $wgLocaltimezone );
return $timestamp;
}
/**
* Get a timestamp instance in GMT
*
* @since 1.22
* @param bool|string $ts Timestamp to set, or false for current time
* @return MWTimestamp The instance
*/
public static function getInstance( $ts = false ) {
return new self( $ts );
}
}

View file

@ -3118,7 +3118,9 @@ abstract class DatabaseBase implements IDatabase, LoggerAwareInterface {
}
public function timestamp( $ts = 0 ) {
return wfTimestamp( TS_MW, $ts );
$t = new ConvertableTimestamp( $ts );
// Let errors bubble up to avoid putting garbage in the DB
return $t->getTimestamp( TS_MW );
}
public function timestampOrNull( $ts = null ) {
@ -3607,9 +3609,17 @@ abstract class DatabaseBase implements IDatabase, LoggerAwareInterface {
}
public function decodeExpiry( $expiry, $format = TS_MW ) {
return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
? 'infinity'
: wfTimestamp( $format, $expiry );
if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
return 'infinity';
}
try {
$t = new ConvertableTimestamp( $expiry );
return $t->getTimestamp( $format );
} catch ( TimestampException $e ) {
return false;
}
}
public function setBigSelects( $value = true ) {

View file

@ -1,7 +0,0 @@
<?php
/**
* @since 1.20
*/
class TimestampException extends MWException {
}

View file

@ -0,0 +1,243 @@
<?php
/**
* Creation, parsing, and conversion of timestamps.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @since 1.20
* @author Tyler Romeo, 2012
*/
/**
* Library for creating, parsing, and converting timestamps. Based on the JS
* library that does the same thing.
*
* @since 1.28
*/
class ConvertableTimestamp {
/**
* Standard gmdate() formats for the different timestamp types.
*/
private static $formats = [
TS_UNIX => 'U',
TS_MW => 'YmdHis',
TS_DB => 'Y-m-d H:i:s',
TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
TS_ISO_8601_BASIC => 'Ymd\THis\Z',
TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
TS_RFC2822 => 'D, d M Y H:i:s',
TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
TS_POSTGRES => 'Y-m-d H:i:s',
];
/**
* The actual timestamp being wrapped (DateTime object).
* @var DateTime
*/
public $timestamp;
/**
* Make a new timestamp and set it to the specified time,
* or the current time if unspecified.
*
* @param bool|string|int|float|DateTime $timestamp Timestamp to set, or false for current time
*/
public function __construct( $timestamp = false ) {
if ( $timestamp instanceof DateTime ) {
$this->timestamp = $timestamp;
} else {
$this->setTimestamp( $timestamp );
}
}
/**
* Set the timestamp to the specified time, or the current time if unspecified.
*
* Parse the given timestamp into either a DateTime object or a Unix timestamp,
* and then store it.
*
* @param string|bool $ts Timestamp to store, or false for now
* @throws TimestampException
*/
public function setTimestamp( $ts = false ) {
$m = [];
$da = [];
$strtime = '';
// We want to catch 0, '', null... but not date strings starting with a letter.
if ( !$ts || $ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
$uts = time();
$strtime = "@$uts";
} elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
# TS_DB
} elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
# TS_EXIF
} elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
# TS_MW
} elseif ( preg_match( '/^(-?\d{1,13})(\.\d+)?$/D', $ts, $m ) ) {
# TS_UNIX
$strtime = "@{$m[1]}"; // http://php.net/manual/en/datetime.formats.compound.php
} elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
# TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
$strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
str_replace( '+00:00', 'UTC', $ts ) );
} elseif ( preg_match(
'/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
$ts,
$da
) ) {
# TS_ISO_8601
} elseif ( preg_match(
'/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
$ts,
$da
) ) {
# TS_ISO_8601_BASIC
} elseif ( preg_match(
'/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
$ts,
$da
) ) {
# TS_POSTGRES
} elseif ( preg_match(
'/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
$ts,
$da
) ) {
# TS_POSTGRES
} elseif ( preg_match(
# Day of week
'/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
# dd Mon yyyy
'\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
# hh:mm:ss
'[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
$ts
) ) {
# TS_RFC2822, accepting a trailing comment.
# See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
# The regex is a superset of rfc2822 for readability
$strtime = strtok( $ts, ';' );
} elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
# TS_RFC850
$strtime = $ts;
} elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
# asctime
$strtime = $ts;
} else {
throw new TimestampException( __METHOD__ . ": Invalid timestamp - $ts" );
}
if ( !$strtime ) {
$da = array_map( 'intval', $da );
$da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
$strtime = call_user_func_array( "sprintf", $da );
}
try {
$final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
} catch ( Exception $e ) {
throw new TimestampException( __METHOD__ . ': Invalid timestamp format.', $e->getCode(), $e );
}
if ( $final === false ) {
throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
}
$this->timestamp = $final;
}
/**
* Get the timestamp represented by this object in a certain form.
*
* Convert the internal timestamp to the specified format and then
* return it.
*
* @param int $style Constant Output format for timestamp
* @throws TimestampException
* @return string The formatted timestamp
*/
public function getTimestamp( $style = TS_UNIX ) {
if ( !isset( self::$formats[$style] ) ) {
throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
}
$output = $this->timestamp->format( self::$formats[$style] );
if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
$output .= ' GMT';
}
if ( $style == TS_MW && strlen( $output ) !== 14 ) {
throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
'the specified format' );
}
return $output;
}
/**
* @return string
*/
public function __toString() {
return $this->getTimestamp();
}
/**
* Calculate the difference between two ConvertableTimestamp objects.
*
* @param ConvertableTimestamp $relativeTo Base time to calculate difference from
* @return DateInterval|bool The DateInterval object representing the
* difference between the two dates or false on failure
*/
public function diff( ConvertableTimestamp $relativeTo ) {
return $this->timestamp->diff( $relativeTo->timestamp );
}
/**
* Set the timezone of this timestamp to the specified timezone.
*
* @param string $timezone Timezone to set
* @throws TimestampException
*/
public function setTimezone( $timezone ) {
try {
$this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
} catch ( Exception $e ) {
throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
}
}
/**
* Get the timezone of this timestamp.
*
* @return DateTimeZone The timezone
*/
public function getTimezone() {
return $this->timestamp->getTimezone();
}
/**
* Format the timestamp in a given format.
*
* @param string $format Pattern to format in
* @return string The formatted timestamp
*/
public function format( $format ) {
return $this->timestamp->format( $format );
}
}

View file

@ -0,0 +1,7 @@
<?php
/**
* @since 1.20
*/
class TimestampException extends Exception {
}

View file

@ -0,0 +1,52 @@
<?php
/**
* Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
*/
define( 'TS_UNIX', 0 );
/**
* MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
*/
define( 'TS_MW', 1 );
/**
* MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
*/
define( 'TS_DB', 2 );
/**
* RFC 2822 format, for E-mail and HTTP headers
*/
define( 'TS_RFC2822', 3 );
/**
* ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
*
* This is used by Special:Export
*/
define( 'TS_ISO_8601', 4 );
/**
* An Exif timestamp (YYYY:MM:DD HH:MM:SS)
*
* @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
* DateTime tag and page 36 for the DateTimeOriginal and
* DateTimeDigitized tags.
*/
define( 'TS_EXIF', 5 );
/**
* Oracle format time.
*/
define( 'TS_ORACLE', 6 );
/**
* Postgres format time.
*/
define( 'TS_POSTGRES', 7 );
/**
* ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
*/
define( 'TS_ISO_8601_BASIC', 9 );

View file

@ -4,7 +4,6 @@
* Tests timestamp parsing and output.
*/
class MWTimestampTest extends MediaWikiLangTestCase {
protected function setUp() {
parent::setUp();
@ -12,128 +11,6 @@ class MWTimestampTest extends MediaWikiLangTestCase {
$this->setMwGlobals( 'wgHooks', [] );
}
/**
* @covers MWTimestamp::__construct
*/
public function testConstructWithNoTimestamp() {
$timestamp = new MWTimestamp();
$this->assertInternalType( 'string', $timestamp->getTimestamp() );
$this->assertNotEmpty( $timestamp->getTimestamp() );
$this->assertNotEquals( false, strtotime( $timestamp->getTimestamp( TS_MW ) ) );
}
/**
* @covers MWTimestamp::__toString
*/
public function testToString() {
$timestamp = new MWTimestamp( '1406833268' ); // Equivalent to 20140731190108
$this->assertEquals( '1406833268', $timestamp->__toString() );
}
public static function provideValidTimestampDifferences() {
return [
[ '1406833268', '1406833269', '00 00 00 01' ],
[ '1406833268', '1406833329', '00 00 01 01' ],
[ '1406833268', '1406836929', '00 01 01 01' ],
[ '1406833268', '1406923329', '01 01 01 01' ],
];
}
/**
* @dataProvider provideValidTimestampDifferences
* @covers MWTimestamp::diff
*/
public function testDiff( $timestamp1, $timestamp2, $expected ) {
$timestamp1 = new MWTimestamp( $timestamp1 );
$timestamp2 = new MWTimestamp( $timestamp2 );
$diff = $timestamp1->diff( $timestamp2 );
$this->assertEquals( $expected, $diff->format( '%D %H %I %S' ) );
}
/**
* Test parsing of valid timestamps and outputing to MW format.
* @dataProvider provideValidTimestamps
* @covers MWTimestamp::getTimestamp
*/
public function testValidParse( $format, $original, $expected ) {
$timestamp = new MWTimestamp( $original );
$this->assertEquals( $expected, $timestamp->getTimestamp( TS_MW ) );
}
/**
* Test outputting valid timestamps to different formats.
* @dataProvider provideValidTimestamps
* @covers MWTimestamp::getTimestamp
*/
public function testValidOutput( $format, $expected, $original ) {
$timestamp = new MWTimestamp( $original );
$this->assertEquals( $expected, (string)$timestamp->getTimestamp( $format ) );
}
/**
* Test an invalid timestamp.
* @expectedException TimestampException
* @covers MWTimestamp
*/
public function testInvalidParse() {
new MWTimestamp( "This is not a timestamp." );
}
/**
* Test an out of range timestamp
* @dataProvider provideOutOfRangeTimestamps
* @expectedException TimestampException
* @covers MWTimestamp
*/
public function testOutOfRangeTimestamps( $format, $input ) {
$timestamp = new MWTimestamp( $input );
$timestamp->getTimestamp( $format );
}
/**
* Test requesting an invalid output format.
* @expectedException TimestampException
* @covers MWTimestamp::getTimestamp
*/
public function testInvalidOutput() {
$timestamp = new MWTimestamp( '1343761268' );
$timestamp->getTimestamp( 98 );
}
/**
* Returns a list of valid timestamps in the format:
* [ type, timestamp_of_type, timestamp_in_MW ]
*/
public static function provideValidTimestamps() {
return [
// Various formats
[ TS_UNIX, '1343761268', '20120731190108' ],
[ TS_MW, '20120731190108', '20120731190108' ],
[ TS_DB, '2012-07-31 19:01:08', '20120731190108' ],
[ TS_ISO_8601, '2012-07-31T19:01:08Z', '20120731190108' ],
[ TS_ISO_8601_BASIC, '20120731T190108Z', '20120731190108' ],
[ TS_EXIF, '2012:07:31 19:01:08', '20120731190108' ],
[ TS_RFC2822, 'Tue, 31 Jul 2012 19:01:08 GMT', '20120731190108' ],
[ TS_ORACLE, '31-07-2012 19:01:08.000000', '20120731190108' ],
[ TS_POSTGRES, '2012-07-31 19:01:08 GMT', '20120731190108' ],
// Some extremes and weird values
[ TS_ISO_8601, '9999-12-31T23:59:59Z', '99991231235959' ],
[ TS_UNIX, '-62135596801', '00001231235959' ]
];
}
/**
* Returns a list of out of range timestamps in the format:
* [ type, timestamp_of_type ]
*/
public static function provideOutOfRangeTimestamps() {
return [
// Various formats
[ TS_MW, '-62167219201' ], // -0001-12-31T23:59:59Z
[ TS_MW, '253402300800' ], // 10000-01-01T00:00:00Z
];
}
/**
* @dataProvider provideHumanTimestampTests
* @covers MWTimestamp::getHumanTimestamp

View file

@ -0,0 +1,128 @@
<?php
/**
* Tests timestamp parsing and output.
*/
class ConvertableTimestampTest extends PHPUnit_Framework_TestCase {
/**
* @covers ConvertableTimestamp::__construct
*/
public function testConstructWithNoTimestamp() {
$timestamp = new ConvertableTimestamp();
$this->assertInternalType( 'string', $timestamp->getTimestamp() );
$this->assertNotEmpty( $timestamp->getTimestamp() );
$this->assertNotEquals( false, strtotime( $timestamp->getTimestamp( TS_MW ) ) );
}
/**
* @covers ConvertableTimestamp::__toString
*/
public function testToString() {
$timestamp = new ConvertableTimestamp( '1406833268' ); // Equivalent to 20140731190108
$this->assertEquals( '1406833268', $timestamp->__toString() );
}
public static function provideValidTimestampDifferences() {
return [
[ '1406833268', '1406833269', '00 00 00 01' ],
[ '1406833268', '1406833329', '00 00 01 01' ],
[ '1406833268', '1406836929', '00 01 01 01' ],
[ '1406833268', '1406923329', '01 01 01 01' ],
];
}
/**
* @dataProvider provideValidTimestampDifferences
* @covers ConvertableTimestamp::diff
*/
public function testDiff( $timestamp1, $timestamp2, $expected ) {
$timestamp1 = new ConvertableTimestamp( $timestamp1 );
$timestamp2 = new ConvertableTimestamp( $timestamp2 );
$diff = $timestamp1->diff( $timestamp2 );
$this->assertEquals( $expected, $diff->format( '%D %H %I %S' ) );
}
/**
* Test parsing of valid timestamps and outputing to MW format.
* @dataProvider provideValidTimestamps
* @covers ConvertableTimestamp::getTimestamp
*/
public function testValidParse( $format, $original, $expected ) {
$timestamp = new ConvertableTimestamp( $original );
$this->assertEquals( $expected, $timestamp->getTimestamp( TS_MW ) );
}
/**
* Test outputting valid timestamps to different formats.
* @dataProvider provideValidTimestamps
* @covers ConvertableTimestamp::getTimestamp
*/
public function testValidOutput( $format, $expected, $original ) {
$timestamp = new ConvertableTimestamp( $original );
$this->assertEquals( $expected, (string)$timestamp->getTimestamp( $format ) );
}
/**
* Test an invalid timestamp.
* @expectedException TimestampException
* @covers ConvertableTimestamp
*/
public function testInvalidParse() {
new ConvertableTimestamp( "This is not a timestamp." );
}
/**
* Test an out of range timestamp
* @dataProvider provideOutOfRangeTimestamps
* @expectedException TimestampException
* @covers ConvertableTimestamp
*/
public function testOutOfRangeTimestamps( $format, $input ) {
$timestamp = new ConvertableTimestamp( $input );
$timestamp->getTimestamp( $format );
}
/**
* Test requesting an invalid output format.
* @expectedException TimestampException
* @covers ConvertableTimestamp::getTimestamp
*/
public function testInvalidOutput() {
$timestamp = new ConvertableTimestamp( '1343761268' );
$timestamp->getTimestamp( 98 );
}
/**
* Returns a list of valid timestamps in the format:
* [ type, timestamp_of_type, timestamp_in_MW ]
*/
public static function provideValidTimestamps() {
return [
// Various formats
[ TS_UNIX, '1343761268', '20120731190108' ],
[ TS_MW, '20120731190108', '20120731190108' ],
[ TS_DB, '2012-07-31 19:01:08', '20120731190108' ],
[ TS_ISO_8601, '2012-07-31T19:01:08Z', '20120731190108' ],
[ TS_ISO_8601_BASIC, '20120731T190108Z', '20120731190108' ],
[ TS_EXIF, '2012:07:31 19:01:08', '20120731190108' ],
[ TS_RFC2822, 'Tue, 31 Jul 2012 19:01:08 GMT', '20120731190108' ],
[ TS_ORACLE, '31-07-2012 19:01:08.000000', '20120731190108' ],
[ TS_POSTGRES, '2012-07-31 19:01:08 GMT', '20120731190108' ],
// Some extremes and weird values
[ TS_ISO_8601, '9999-12-31T23:59:59Z', '99991231235959' ],
[ TS_UNIX, '-62135596801', '00001231235959' ]
];
}
/**
* Returns a list of out of range timestamps in the format:
* [ type, timestamp_of_type ]
*/
public static function provideOutOfRangeTimestamps() {
return [
// Various formats
[ TS_MW, '-62167219201' ], // -0001-12-31T23:59:59Z
[ TS_MW, '253402300800' ], // 10000-01-01T00:00:00Z
];
}
}