about summary refs log tree commit diff stats
path: root/classes/Request.php
blob: 3a8e696e4ebcceb53ea7d2b18e85704388753c51 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
<?php
/**
 * Typed parameter extraction wrapper around PHP superglobals.
 *
 * Provides clean, type-safe access to request parameters, replacing the
 * repetitive clean($_REQUEST['key'] ?? default) pattern throughout handlers.
 *
 * Usage:
 *   $request = new Request();
 *   $id   = $request->getInt('id', 0);
 *   $name = $request->getString('name', '');
 *   $flag = $request->getBool('flag', false);
 *   $ids  = $request->getArray('ids', []);
 *
 * Can also extract from specific superglobals:
 *   $request->fromPost()->getString('login');
 *   $request->fromGet()->getInt('limit', 20);
 */
class Request {

    public const SOURCE_REQUEST = 'request';
    public const SOURCE_GET     = 'get';
    public const SOURCE_POST    = 'post';
    public const SOURCE_BODY    = 'body';

    /** @var array<int|string, mixed>|null */
    private ?array $data = null;

    /** @var array<int|string, mixed>|null */
    private ?array $body = null;

    /** @var array<int|string, mixed> */
    private array $attributes = [];

    /** @var self::SOURCE_* */
    private string $source = self::SOURCE_REQUEST;

    /**
     * @param array<int|string, mixed>|null $data Optional explicit data source (e.g. from constructor arg)
     */
    public function __construct(?array $data = null) {
        $this->data = $data;
    }

    /**
     * Extract from the given superglobal.
     *
     * @param self::SOURCE_* $source
     * @return $this
     */
    public function from(string $source): self {
        $this->source = $source;
        return $this;
    }

    /**
     * Extract from $_POST.
     * @return $this
     */
    public function fromPost(): self {
        return $this->from(self::SOURCE_POST);
    }

    /**
     * Extract from $_GET.
     * @return $this
     */
    public function fromGet(): self {
        return $this->from(self::SOURCE_GET);
    }

    /**
     * Extract from $_REQUEST (default).
     * @return $this
     */
    public function fromRequest(): self {
        return $this->from(self::SOURCE_REQUEST);
    }

    /**
     * Extract from the raw request body (php://input).
     *
     * Inspects Content-Type to determine parsing strategy:
     *   - application/json / text/json  → JSON decode
     *   - application/x-www-form-urlencoded → parse_str (like $_POST)
     *   - anything else / missing        → empty array
     *
     * If JSON decoding fails, an empty array is returned so downstream
     * getters fall back to defaults.
     *
     * Useful for PATCH/PUT requests where $_POST is not populated.
     *
     * @return $this
     */
    public function fromBody(): self {
        if ($this->body !== null) {
            return $this;
        }

        $raw = file_get_contents('php://input');
        if ($raw === '') {
            $this->body = [];
            return $this;
        }

        // Determine content type, stripping charset etc.
        $contentType = strtolower(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0]);

        if (in_array($contentType, ['application/json', 'text/json'], true)) {
            $decoded = json_decode($raw, true);
            $this->body = is_array($decoded) ? $decoded : [];
        } elseif ($contentType === 'application/x-www-form-urlencoded') {
            parse_str($raw, $parsed);
            $this->body = $parsed;
        } else {
            $this->body = [];
        }

        return $this->from(self::SOURCE_BODY);
    }

    /**
     * Get a sanitized string value.
     *
     * @param string $key
     * @param string $default
     * @return string
     */
    public function getString(string $key, string $default = ''): string {
        $value = $this->getRaw($key);
        if ($value === null) {
            return $default;
        }
        return clean((string)$value);
    }

    /**
     * Get a sanitized integer value.
     *
     * @param string $key
     * @param int $default
     * @return int
     */
    public function getInt(string $key, int $default = 0): int {
        $value = $this->getRaw($key);
        if ($value === null) {
            return $default;
        }
        return (int) clean((string)$value);
    }

    /**
     * Get a sanitized float value.
     *
     * @param string $key
     * @param float $default
     * @return float
     */
    public function getFloat(string $key, float $default = 0.0): float {
        $value = $this->getRaw($key);
        if ($value === null) {
            return $default;
        }
        return (float) clean((string)$value);
    }

    /**
     * Get a sanitized boolean value.
     *
     * Treats the following as true: "1", "true", "t", "on", non-zero integers,
     * non-empty strings. All other values are treated as false.
     *
     * @param string $key
     * @param bool $default
     * @return bool
     */
    public function getBool(string $key, bool $default = false): bool {
        $value = $this->getRaw($key);
        if ($value === null) {
            return $default;
        }
        return self::_to_bool($value);
    }

    /**
     * Get a sanitized array value.
     *
     * If the value is a comma-separated string, it will be split into an array.
     * Each element is trimmed and HTML tags are stripped.
     *
     * @param string $key
     * @param array<int|string, mixed> $default
     * @return array<int|string, mixed>
     */
    public function getArray(string $key, array $default = []): array {
        $value = $this->getRaw($key);
        if ($value === null) {
            return $default;
        }

        if (is_array($value)) {
            return clean($value);
        }

        // Handle comma-separated string values
        $cleaned = clean((string)$value);
        if ($cleaned === '') {
            return [];
        }

        return array_map('trim', explode(',', $cleaned));
    }

    /**
     * Get the raw (unsanitized) value.
     *
     * @param string $key
     * @return mixed|null
     */
    public function getRaw(string $key): mixed {
        return match ($this->source) {
            self::SOURCE_POST => $_POST[$key] ?? null,
            self::SOURCE_GET  => $_GET[$key] ?? null,
            self::SOURCE_BODY => $this->body[$key] ?? null,
            default           => $this->data !== null ? ($this->data[$key] ?? null) : ($_REQUEST[$key] ?? null),
        };
    }

    /**
     * Check if a key exists in the current source.
     *
     * @param string $key
     * @return bool
     */
    public function has(string $key): bool {
        return match ($this->source) {
            self::SOURCE_POST => array_key_exists($key, $_POST),
            self::SOURCE_GET  => array_key_exists($key, $_GET),
            self::SOURCE_BODY => array_key_exists($key, $this->body),
            default           => $this->data !== null
                ? array_key_exists($key, $this->data)
                : array_key_exists($key, $_REQUEST),
        };
    }

    /**
     * Get all parameters from the current source.
     *
     * @return array<int|string, mixed>
     */
    public function all(): array {
        return match ($this->source) {
            self::SOURCE_POST   => $_POST,
            self::SOURCE_GET    => $_GET,
            self::SOURCE_BODY   => $this->body ?? [],
            default             => $this->data !== null ? $this->data : $_REQUEST,
        };
    }

    /**
     * Get all query parameters (\$_GET).
     *
     * @return array<int|string, mixed>
     */
    public function getQueryParams(): array {
        return $_GET;
    }

    /**
     * Get all server parameters (\$_SERVER).
     *
     * @return array<int|string, mixed>
     */
    public function getServerParams(): array {
        return $_SERVER;
    }

    /**
     * Get all cookie parameters (\$_COOKIE).
     *
     * @return array<int|string, mixed>
     */
    public function getCookieParams(): array {
        return $_COOKIE;
    }

    /**
     * Get a merged body from \$_GET and \$_POST, with \$_POST values
     * overriding \$_GET on key collision.
     *
     * @return array<int|string, mixed>
     */
    public function getParsedBody(): array {
        return array_merge($_GET, $_POST);
    }

    /**
     * Get an attribute or request parameter by key.
     *
     * Looks first in attributes set via withAttribute(), then in the
     * parsed body (\$_GET + \$_POST merged).
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public function getAttribute(string $key, mixed $default = null): mixed {
        // Check attributes first
        if (array_key_exists($key, $this->attributes)) {
            return $this->attributes[$key];
        }

        // Fall back to parsed body
        $body = $this->getParsedBody();
        return $body[$key] ?? $default;
    }

    /**
     * Return a clone of this request with a new attribute added.
     *
     * @param string $key
     * @param mixed $value
     * @return self
     */
    public function withAttribute(string $key, mixed $value): self {
        $clone = clone $this;
        $clone->attributes[$key] = $value;
        return $clone;
    }

    /**
     * Get a subset of parameters by key names.
     *
     * @param array<int, string> $keys
     * @return array<int|string, mixed>
     */
    public function only(array $keys): array {
        $result = [];
        foreach ($keys as $key) {
            $result[$key] = $this->getRaw($key);
        }
        return $result;
    }

    /**
     * Convert a value to boolean using the same logic as Handler::_param_to_bool().
     *
     * @param mixed $value
     * @return bool
     */
    public static function _to_bool(mixed $value): bool {
        $value = clean($value);

        if (is_bool($value)) {
            return $value;
        }

        if (is_int($value)) {
            return $value !== 0;
        }

        if (is_float($value)) {
            return $value != 0.0;
        }

        if (is_string($value)) {
            $lower = strtolower($value);
            return in_array($lower, ['1', 'true', 't', 'on'], true);
        }

        return (bool) $value;
    }
}