Completed
Push — master ( 38f1ea...fd6c7c )
by Matze
04:05
created

TimeParser::withModifier()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
3
namespace BrainExe\Core\Util;
4
5
use BrainExe\Annotations\Annotations\Service;
6
use BrainExe\Core\Application\UserException;
7
8
/**
9
 * Parse user input into an unix timestamp
10
 * @Service(public=false, shared=false)
11
 * @api
12
 */
13
class TimeParser
14
{
15
16
    /**
17
     * @var integer[]
18
     */
19
    private $timeModifier = [
20
        's' => 1,
21
        'm' => 60,
22
        'h' => 3600,
23
        'd' => 86400,
24
        'w' => 604800,
25
        'y' => 31536000,
26
    ];
27
28
    /**
29
     * @param string $string
30
     * @throws UserException
31
     * @return int
32
     */
33 10
    public function parseString(string $string)
34
    {
35 10
        $now = time();
36
37 10
        if (empty($string)) {
38 1
            return 0;
39 9
        } elseif (is_numeric($string)) {
40 3
            $timestamp = $now + (int)$string;
41 6
        } elseif (preg_match('/^(\d+)\s*(\w)$/', trim($string), $matches)) {
42 5
            $timestamp = $this->withModifier($matches, $now);
43
        } else {
44 1
            $timestamp = strtotime($string);
45
        }
46
47 8
        if ($timestamp < $now) {
48 1
            throw new UserException(sprintf('Time %s is invalid', $string));
49
        }
50
51 7
        return $timestamp;
52
    }
53
54
    /**
55
     * @param array $matches
56
     * @param int $now
57
     * @return int
58
     * @throws UserException
59
     */
60 5
    protected function withModifier(array $matches, int $now)
61
    {
62 5
        $modifier = strtolower($matches[2]);
63 5
        if (empty($this->timeModifier[$modifier])) {
64 1
            throw new UserException(sprintf('Invalid time modifier %s', $modifier));
65
        }
66
67 4
        return $now + $matches[1] * $this->timeModifier[$modifier];
68
    }
69
}
70