3 namespace Wikimedia\ParamValidator\TypeDef
;
5 use Wikimedia\ParamValidator\Callbacks
;
6 use Wikimedia\ParamValidator\TypeDef
;
7 use Wikimedia\ParamValidator\ValidationException
;
8 use Wikimedia\Timestamp\ConvertibleTimestamp
;
9 use Wikimedia\Timestamp\TimestampException
;
12 * Type definition for timestamp types
14 * This uses the wikimedia/timestamp library for parsing and formatting the
17 * The result from validate() is a ConvertibleTimestamp by default, but this
18 * may be changed by both a constructor option and a PARAM constant.
20 * ValidationException codes:
21 * - 'badtimestamp': The timestamp is not valid. No data, but the
22 * TimestampException is available via Exception::getPrevious().
23 * - 'unclearnowtimestamp': Non-fatal. The value is the empty string or "0".
24 * Use 'now' instead if you really want the current timestamp. No data.
29 class TimestampDef
extends TypeDef
{
32 * (string|int) Timestamp format to return from validate()
35 * - 'ConvertibleTimestamp': A ConvertibleTimestamp object.
36 * - 'DateTime': A PHP DateTime object
37 * - One of ConvertibleTimestamp's TS_* constants.
39 * This does not affect the format returned by stringifyValue().
41 const PARAM_TIMESTAMP_FORMAT
= 'param-timestamp-format';
43 /** @var string|int */
44 protected $defaultFormat;
47 protected $stringifyFormat;
50 * @param Callbacks $callbacks
51 * @param array $options Options:
52 * - defaultFormat: (string|int) Default for PARAM_TIMESTAMP_FORMAT.
53 * Default if not specified is 'ConvertibleTimestamp'.
54 * - stringifyFormat: (int) Format to use for stringifyValue().
55 * Default is TS_ISO_8601.
57 public function __construct( Callbacks
$callbacks, array $options = [] ) {
58 parent
::__construct( $callbacks );
60 $this->defaultFormat
= $options['defaultFormat'] ??
'ConvertibleTimestamp';
61 $this->stringifyFormat
= $options['stringifyFormat'] ?? TS_ISO_8601
;
64 public function validate( $name, $value, array $settings, array $options ) {
65 // Confusing synonyms for the current time accepted by ConvertibleTimestamp
67 $this->callbacks
->recordCondition(
68 new ValidationException( $name, $value, $settings, 'unclearnowtimestamp', [] ),
75 $timestamp = new ConvertibleTimestamp( $value === 'now' ?
false : $value );
76 } catch ( TimestampException
$ex ) {
77 throw new ValidationException( $name, $value, $settings, 'badtimestamp', [], $ex );
80 $format = $settings[self
::PARAM_TIMESTAMP_FORMAT
] ??
$this->defaultFormat
;
82 case 'ConvertibleTimestamp':
87 return $timestamp->timestamp
;
90 return $timestamp->getTimestamp( $format );
94 public function stringifyValue( $name, $value, array $settings, array $options ) {
95 if ( !$value instanceof ConvertibleTimestamp
) {
96 $value = new ConvertibleTimestamp( $value );
98 return $value->getTimestamp( $this->stringifyFormat
);