GoomerApi::requestLimit()   B
last analyzed

Complexity

Conditions 10
Paths 20

Size

Total Lines 57
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 35
c 1
b 0
f 0
dl 0
loc 57
rs 7.6666
cc 10
nc 20
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace WagnerMontanini\GoomerApi\Api;
4
5
use WagnerMontanini\GoomerApi\Core\Controller;
6
7
/**
8
 * Class GoomerApi
9
 * @package WagnerMontanini\GoomerApi\Api
10
 */
11
class GoomerApi extends Controller
12
{
13
    /** @var array|false */
14
    protected $headers;
15
16
    /** @var array|null */
17
    protected $response;
18
19
    /**
20
     * GoomerApi constructor.
21
     * @throws \Exception
22
     */
23
    public function __construct()
24
    {
25
        parent::__construct("/");
26
27
        header('Content-Type: application/json; charset=UTF-8');
28
        header("Access-Control-Allow-Origin: *");
29
        $this->headers = getallheaders();
0 ignored issues
show
Documentation Bug introduced by
It seems like getallheaders() can also be of type true. However, the property $headers is declared as type array|false. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
30
31
    }
32
33
    /**
34
     * @param int $code
35
     * @param string|null $type
36
     * @param string|null $message
37
     * @param string $rule
38
     * @return GoomerApi
39
     */
40
    protected function call(int $code, string $type = null, string $message = null, string $rule = "errors"): GoomerApi
41
    {
42
        http_response_code($code);
43
44
        if (!empty($type)) {
45
            $this->response = [
46
                $rule => [
47
                    "type" => $type,
48
                    "message" => (!empty($message) ? $message : null)
49
                ]
50
            ];
51
        }
52
        return $this;
53
    }
54
55
    /**
56
     * @param array|null $response
57
     * @return GoomerApi
58
     */
59
    protected function back(array $response = null): GoomerApi
60
    {
61
        if (!empty($response)) {
62
            $this->response = (!empty($this->response) ? array_merge($this->response, $response) : $response);
63
        }
64
65
        echo json_encode($this->response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
66
        return $this;
67
    }
68
69
    /**
70
     * @param string $endpoint
71
     * @param int $limit
72
     * @param int $seconds
73
     * @param bool $attempt
74
     * @return bool
75
     */
76
    protected function requestLimit(string $endpoint, int $limit, int $seconds, bool $attempt = false): bool
77
    {
78
        $userToken = base64_encode($_SERVER['REMOTE_ADDR']);
79
80
        $cacheDir = __DIR__ . "/../../" . CONF_UPLOAD_DIR . "/requests";
81
        if (!file_exists($cacheDir) || !is_dir($cacheDir)) {
82
            mkdir($cacheDir, 0755, true);
83
        }
84
85
        $cacheFile = "{$cacheDir}/{$userToken}.json";
86
        if (!file_exists($cacheFile) || !is_file($cacheFile)) {
87
            fopen($cacheFile, "w");
88
        }
89
90
        $userCache = json_decode(file_get_contents($cacheFile));
91
        $cache = (array)$userCache;
92
93
        $save = function ($cacheFile, $cache) {
94
            $saveCache = fopen($cacheFile, "w");
95
            fwrite($saveCache, json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
96
            fclose($saveCache);
97
        };
98
99
        if (empty($cache[$endpoint]) || $cache[$endpoint]->time <= time()) {
100
            if (!$attempt) {
101
                $cache[$endpoint] = [
102
                    "limit" => $limit,
103
                    "requests" => 1,
104
                    "time" => time() + $seconds
105
                ];
106
107
                $save($cacheFile, $cache);
108
            }
109
110
            return true;
111
        }
112
113
        if ($cache[$endpoint]->requests >= $limit) {
114
            $this->call(
115
                400,
116
                "request_limit",
117
                "Você exedeu o limite de requisições para essa ação"
118
            )->back();
119
120
            return false;
121
        }
122
123
        if (!$attempt) {
124
            $cache[$endpoint] = [
125
                "limit" => $limit,
126
                "requests" => $cache[$endpoint]->requests + 1,
127
                "time" => $cache[$endpoint]->time
128
            ];
129
130
            $save($cacheFile, $cache);
131
        }
132
        return true;
133
    }
134
}