Throttle::throttle()   B
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 8.5125
cc 5
eloc 16
nc 7
nop 1
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
                } else {
37
                    $pool[$ip][0] += 1;
38
                }
39
            } else {
40
                $pool[$ip] = [];
41
                $pool[$ip][0] = 1;
42
            }
43
            $pool[$ip][1] = (new DateTime())->format('Y-m-d H:i:s');
44
45
            self::save($pool);
46
47
            if ($pool[$ip][0] > 10) {
48
                sleep($pool[$ip][0] - 10);
49
            }
50
        }
51
    }
52
}
53