MediaWiki REL1_34
TimestampDef.php
Go to the documentation of this file.
1<?php
2
4
8use Wikimedia\Timestamp\ConvertibleTimestamp;
9use Wikimedia\Timestamp\TimestampException;
10
29class TimestampDef extends TypeDef {
30
41 const PARAM_TIMESTAMP_FORMAT = 'param-timestamp-format';
42
44 protected $defaultFormat;
45
48
57 public function __construct( Callbacks $callbacks, array $options = [] ) {
58 parent::__construct( $callbacks );
59
60 $this->defaultFormat = $options['defaultFormat'] ?? 'ConvertibleTimestamp';
61 $this->stringifyFormat = $options['stringifyFormat'] ?? TS_ISO_8601;
62 }
63
64 public function validate( $name, $value, array $settings, array $options ) {
65 // Confusing synonyms for the current time accepted by ConvertibleTimestamp
66 if ( !$value ) {
67 $this->callbacks->recordCondition(
68 new ValidationException( $name, $value, $settings, 'unclearnowtimestamp', [] ),
69 $options
70 );
71 $value = 'now';
72 }
73
74 try {
75 $timestamp = new ConvertibleTimestamp( $value === 'now' ? false : $value );
76 } catch ( TimestampException $ex ) {
77 throw new ValidationException( $name, $value, $settings, 'badtimestamp', [], $ex );
78 }
79
81 switch ( $format ) {
82 case 'ConvertibleTimestamp':
83 return $timestamp;
84
85 case 'DateTime':
86 // Eew, no getter.
87 return $timestamp->timestamp;
88
89 default:
90 return $timestamp->getTimestamp( $format );
91 }
92 }
93
94 public function stringifyValue( $name, $value, array $settings, array $options ) {
95 if ( !$value instanceof ConvertibleTimestamp ) {
96 $value = new ConvertibleTimestamp( $value );
97 }
98 return $value->getTimestamp( $this->stringifyFormat );
99 }
100
101}
Type definition for timestamp types.
validate( $name, $value, array $settings, array $options)
Validate the value.
__construct(Callbacks $callbacks, array $options=[])
stringifyValue( $name, $value, array $settings, array $options)
Convert a value to a string representation.
const PARAM_TIMESTAMP_FORMAT
(string|int) Timestamp format to return from validate()
Base definition for ParamValidator types.
Definition TypeDef.php:15
Interface defining callbacks needed by ParamValidator.
Definition Callbacks.php:20