Completed
Push — master ( 3b6b78...0dd9ce )
by Freek
13s
created

EncryptedTime::isValidTimeStamp()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace Spatie\Honeypot;
4
5
use DateTimeInterface;
6
use Illuminate\Support\Facades\Date;
7
8
class EncryptedTime
9
{
10
    protected $carbon;
11
12
    /** @var string */
13
    protected $encryptedTime;
14
15
    public static function create(DateTimeInterface $dateTime)
16
    {
17
        $encryptedTime = app('encrypter')->encrypt($dateTime->getTimestamp());
18
19
        return new static($encryptedTime);
20
    }
21
22
    public function __construct(string $encryptedTime)
23
    {
24
        $this->encryptedTime = $encryptedTime;
25
26
        $timestamp = app('encrypter')->decrypt($encryptedTime);
27
28
        if (! $this->isValidTimeStamp($timestamp)) {
29
            throw new \Exception(sprintf('Timestamp %s is invalid', $timestamp));
30
        }
31
32
        $this->carbon = Date::createFromTimestamp($timestamp);
33
    }
34
35
    public function isFuture(): bool
36
    {
37
        return $this->carbon->isFuture();
38
    }
39
40
    public function __toString()
41
    {
42
        return $this->encryptedTime;
43
    }
44
45
    private function isValidTimeStamp(string $timestamp)
46
    {
47
        return ((string) (int) $timestamp === $timestamp)
48
            && ($timestamp >= 0)
49
            && ($timestamp <= PHP_INT_MAX);
50
    }
51
}
52