-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRequestHandler.php
80 lines (62 loc) · 1.54 KB
/
RequestHandler.php
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
<?php
namespace App;
use SQLite3;
abstract class RequestHandler {
const DB_FILE_NAME = '/db/appointments.sqlite';
/** @var SqLiteHandler $dbHandler */
private $dbHandler;
protected $method;
public static $currentRequest;
/**
* RequestHandler constructor.
*/
public function __construct() {
self::$currentRequest = $this;
$this->method = strtoupper($this->get('method', $this->get('_method', $_SERVER['REQUEST_METHOD'])));
$this->dbHandler = $this->initDb();
return $this;
}
/**
* "Routes" the request by verb.
*/
public abstract function handle();
private function initDb(): SqLiteHandler {
$dbConnection = new SQLite3(BASE_DIR . self::DB_FILE_NAME);
return SqLiteHandler::instance($dbConnection);
}
public function db() {
return $this->dbHandler;
}
/**
* @param string $name
*
* @return ViewHandler
*/
public function view(string $name) {
return new ViewHandler($name);
}
/**
* @param string $name
* @param null $default
*
* @return mixed|null
*/
public function get(string $name, $default = null) {
if (array_key_exists($name, $_GET)) $value = $_GET[$name];
if (array_key_exists($name, $_POST)) $value = $_POST[$name];
return isset($value) && $value ? $value : $default;
}
/**
* @return array
*/
public function all(): array {
$pairs = [];
foreach ($_GET as $key => $value) $pairs[$key] = $value;
foreach ($_POST as $key => $value) $pairs[$key] = $value;
return $pairs;
}
public function redirect($url) {
http_response_code(301);
header('Location: ' . $url);
}
}