summaryrefslogtreecommitdiff
path: root/src/web/core/controller.php
blob: ca892e2b23b00320535378bef884d4e06fbe46fb (plain)
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
<?php /* Copyright (c) 2024 Freya Murphy */

abstract class Controller extends Component {

	/**
	 * Default index for a app, empty
	 */
	public function index(): void {}

	/**
	 * Redirectes to a link
	 */
	public function redirect(string $link): void
	{
		header('Location: '. $link, true, 301);
		die();
	}

	/**
	 * Lodas a view
	 */
	protected function view(string $__name, array $data = array()): void
	{
		$__path = WEB_ROOT . '/_views/' . $__name . '.php';
		if (is_file($__path)) {
			extract($data);
			require($__path);
		}
	}

	/**
	 * Loads a erorr page with a given
	 * error code
	 */
	protected function error(int $code): void
	{
		$error_controller = $this->load_controller('error');
		$error_controller->code($code);
		die();
	}

	/**
	 * Returns HTTP POST information if POST request.
	 * Returns 405 Method Not Allowed if not.
	 *
	 * If $key is specified, returns only that key. otherwise
	 * returns HTTP 400 Bad Request;
	 */
	protected function post_data(?string $key = NULL): array|string
	{
		// only post requests allowed
		if ($_SERVER['REQUEST_METHOD'] != 'POST')
			$this->error(405);

		// return entire $_POST array
		if (!$key)
			return $_POST;

		if (!isset($_POST[$key]))
			$this->error(400);

		return $_POST[$key];
	}

}