Completed
Push — master ( 025e52...863689 )
by Gabriel
02:50
created

Throttle::pool()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 4
nop 0
1
<?php
2
3
namespace Sinergi\Users\Throttle;
4
5
use DateTime;
6
7
class Throttle
8
{
9
    private static function file(): string
10
    {
11
        return sys_get_temp_dir() . '/sinergi_users_throttle.json';
12
    }
13
14
    private static function pool(): array
15
    {
16
        if (!file_exists(self::file())) {
17
            touch(self::file());
18
        }
19
        $content = json_decode(file_get_contents(self::file()), true);
20
        return is_array($content) ? $content : [];
21
    }
22
23
    private static function save(array $pool)
24
    {
25
        file_put_contents(self::file(), json_encode($pool));
26
    }
27
28
    public static function throttle(string $ip)
0 ignored issues
show
Coding Style Best Practice introduced by
Please use __construct() instead of a PHP4-style constructor that is named after the class.
Loading history...
29
    {
30
        if ($ip) {
31
            $pool = self::pool();
32
            if (isset($pool[$ip])) {
33
                $lastAttempt = ((new Datetime())->getTimestamp() - (new DateTime($pool[$ip][1]))->getTimestamp());
34
                if ($lastAttempt > 300) {
35
                    $pool[$ip][0] = 1;
36
                    $pool[$ip][1] = (new DateTime())->format('Y-m-d H:i:s');
37
                } else {
38
                    $pool[$ip][0] += 1;
39
                    $pool[$ip][1] = (new DateTime())->format('Y-m-d H:i:s');
40
                }
41
            } else {
42
                $pool[$ip] = [];
43
                $pool[$ip][0] = 1;
44
                $pool[$ip][1] = (new DateTime())->format('Y-m-d H:i:s');
45
            }
46
47
            self::save($pool);
48
49
            if ($pool[$ip][0] > 10) {
50
                sleep($pool[$ip][0] - 10);
51
            }
52
        }
53
    }
54
}
55