Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.89% covered (warning)
88.89%
16 / 18
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
DurationManager
88.89% covered (warning)
88.89%
16 / 18
66.67% covered (warning)
66.67%
2 / 3
8.09
0.00% covered (danger)
0.00%
0 / 1
 getFromRequest
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getTimestampFromRequest
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 isValid
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace MediaWiki\CheckUser\Investigate\Utilities;
4
5use DateInterval;
6use DateTime;
7use Exception;
8use MediaWiki\Request\WebRequest;
9use MediaWiki\Utils\MWTimestamp;
10
11class DurationManager {
12
13    /**
14     * Retrieves a valid duration from the request.
15     *
16     * @param WebRequest $request
17     * @return string
18     */
19    public function getFromRequest( WebRequest $request ): string {
20        $value = $request->getVal( 'duration', '' );
21
22        if ( !$this->isValid( $value ) ) {
23            return '';
24        }
25
26        return $value;
27    }
28
29    /**
30     * Return the timestamp from the duration.
31     *
32     * @param WebRequest $request
33     * @return string
34     */
35    public function getTimestampFromRequest( WebRequest $request ): string {
36        $duration = $this->getFromRequest( $request );
37        if ( $duration === '' ) {
38            return $duration;
39        }
40
41        try {
42            $interval = new DateInterval( $duration );
43            $now = DateTime::createFromFormat( 'U', (string)MWTimestamp::time() );
44            return MWTimestamp::convert( TS_MW, $now->sub( $interval ) );
45        } catch ( Exception $e ) {
46            return '';
47        }
48    }
49
50    /**
51     * Determine if duration is valid.
52     *
53     * @param string $value
54     * @return bool
55     */
56    public function isValid( string $value ): bool {
57        // No value implies "all"
58        if ( $value === '' ) {
59            return true;
60        }
61
62        try {
63            // @phan-suppress-next-line PhanNoopNew
64            new DateInterval( $value );
65            return true;
66        } catch ( Exception $e ) {
67            return false;
68        }
69    }
70}