-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseController.php
More file actions
70 lines (57 loc) · 2.03 KB
/
Copy pathBaseController.php
File metadata and controls
70 lines (57 loc) · 2.03 KB
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
<?php
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
// src/Libs/Italix/Mvc/BaseController.php
declare(strict_types=1);
namespace Italix\Mvc;
use Italix\Contracts\DataContainer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
abstract class BaseController
{
protected DataContainer $context;
protected function context(): DataContainer
{
return $this->context;
}
protected function input(ServerRequestInterface $request): RequestInput
{
return new RequestInput($request);
}
protected function redirect_to(string $url, int $status = 302): ResponseInterface
{
return Responses::redirect($url, $status);
}
/**
* Return a JSON response. $data may be a pre-encoded string or any
* value that will be passed through json_encode().
*/
/** @param mixed $data */
protected function json($data, int $status = 200): ResponseInterface
{
$body = is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
return Responses::with_type((string) $body, 'application/json', $status);
}
// Default fallback: If a controller doesn't define this, it needs nothing.
public static function depends_on(string $method = ''): array
{
return [];
}
// The magic constructor that maps the array to the properties
public function __construct(array $services = [])
{
$this->context = new DataContainer();
foreach ($services as $property_name => $service_instance)
{
if (!property_exists($this, $property_name)) {
throw new \LogicException(
static::class . "::depends_on() declares '\$$property_name' but the property is not defined."
);
}
$this->$property_name = $service_instance;
}
}
}