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

TimeParser::parseString()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 8.8571
cc 5
eloc 13
nc 7
nop 1
crap 5
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