Completed
Pull Request — master (#36)
by
unknown
05:08
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 Carbon\Carbon;
6
use DateTimeInterface;
7
use Illuminate\Support\Facades\Date;
8
9
class EncryptedTime
10
{
11
    protected $carbon;
12
13
    /** @var string */
14
    protected $encryptedTime;
15
16
    public static function create(DateTimeInterface $dateTime)
17
    {
18
        $encryptedTime = app('encrypter')->encrypt($dateTime->getTimestamp());
19
20
        return new static($encryptedTime);
21
    }
22
23
    public function __construct(string $encryptedTime)
24
    {
25
        $this->encryptedTime = $encryptedTime;
26
27
        $timestamp = app('encrypter')->decrypt($encryptedTime);
28
        
29
        if (! $this->isValidTimeStamp($timestamp)) {
30
            throw new \Exception(sprintf('Timestamp %s is invalid', $timestamp));
31
        }
32
33
        $this->carbon = Date::createFromTimestamp($timestamp);
34
    }
35
36
    public function isFuture(): bool
37
    {
38
        return $this->carbon->isFuture();
39
    }
40
41
    public function __toString()
42
    {
43
        return $this->encryptedTime;
44
    }
45
46
    private function isValidTimeStamp(string $timestamp)
47
    {
48
        return ((string) (int) $timestamp === $timestamp)
49
            && ($timestamp >= 0)
50
            && ($timestamp <= PHP_INT_MAX);
51
    }
52
}
53