diff options
Diffstat (limited to 'CheckUser/src/DurationManager.php')
-rw-r--r-- | CheckUser/src/DurationManager.php | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/CheckUser/src/DurationManager.php b/CheckUser/src/DurationManager.php new file mode 100644 index 00000000..8755bb98 --- /dev/null +++ b/CheckUser/src/DurationManager.php @@ -0,0 +1,63 @@ +<?php + +namespace MediaWiki\CheckUser; + +class DurationManager { + + /** + * Retrieves a valid duration from the request. + * + * @param \WebRequest $request + * @return string + */ + public function getFromRequest( \WebRequest $request ) : string { + $value = $request->getVal( 'duration', '' ); + + if ( !$this->isValid( $value ) ) { + return ''; + } + + return $value; + } + + /** + * Return the timestamp from the duration. + * + * @param \WebRequest $request + * @return string + */ + public function getTimestampFromRequest( \WebRequest $request ) : string { + $duration = $this->getFromRequest( $request ); + if ( $duration === '' ) { + return $duration; + } + + try { + $interval = new \DateInterval( $duration ); + $now = \DateTime::createFromFormat( 'U', (string)\MWTimestamp::time() ); + return \MWTimestamp::convert( TS_MW, $now->sub( $interval ) ); + } catch ( \Exception $e ) { + return ''; + } + } + + /** + * Determine if duration is valid. + * + * @param string $value + * @return bool + */ + public function isValid( string $value ) : bool { + // No value implies "all" + if ( $value === '' ) { + return true; + } + + try { + $interval = new \DateInterval( $value ); + return true; + } catch ( \Exception $e ) { + return false; + } + } +} |