EncryptedTime::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
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): bool
46
    {
47
        if ((string) (int) $timestamp !== $timestamp) {
48
            return false;
49
        }
50
51
        if ($timestamp <= 0) {
52
            return false;
53
        }
54
55
        if ($timestamp >= PHP_INT_MAX) {
56
            return false;
57
        }
58
59
        return true;
60
    }
61
}
62