Reject out-of-range output when converting to TS_MW
authorBrad Jorsch <bjorsch@wikimedia.org>
Fri, 19 Dec 2014 22:06:38 +0000 (17:06 -0500)
committerBrad Jorsch <bjorsch@wikimedia.org>
Fri, 19 Dec 2014 22:06:38 +0000 (17:06 -0500)
TS_MW is a 14-character string "YYYYMMDDHHIISS", and thus cannot
represent timestamps earlier than 00000101000000 or later than
99991231235959.

MWTimestamp should throw an exception if asked to represent out-of-range
times in this format, rather than returning invalid values that are
likely to be truncated by the database.

Bug: T51580
Change-Id: I744e446356f3ed9193dfaaaec5dc81c611dab4a3

includes/MWTimestamp.php
tests/phpunit/includes/MWTimestampTest.php

index 4b3d36a..ea91470 100644 (file)
@@ -182,6 +182,11 @@ class MWTimestamp {
                        $output .= ' GMT';
                }
 
+               if ( $style == TS_MW && strlen( $output ) !== 14 ) {
+                       throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
+                               'the specified format' );
+               }
+
                return $output;
        }
 
index 05c1a66..3656254 100644 (file)
@@ -81,6 +81,17 @@ class MWTimestampTest extends MediaWikiLangTestCase {
                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
@@ -113,6 +124,18 @@ class MWTimestampTest extends MediaWikiLangTestCase {
                );
        }
 
+       /**
+        * Returns a list of out of range timestamps in the format:
+        * array( type, timestamp_of_type )
+        */
+       public static function provideOutOfRangeTimestamps() {
+               return array(
+                       // Various formats
+                       array( TS_MW, '-62167219201' ), // -0001-12-31T23:59:59Z
+                       array( TS_MW, '253402300800' ), // 10000-01-01T00:00:00Z
+               );
+       }
+
        /**
         * @dataProvider provideHumanTimestampTests
         * @covers MWTimestamp::getHumanTimestamp