Completed
Push — master ( 022616...175363 )
by Alex
08:53
created

CommonApplication::noRouteFoundErrorHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Mezon\Application;
3
4
use Mezon\HtmlTemplate\HtmlTemplate;
5
use Mezon\Rest;
6
7
/**
8
 * Class CommonApplication
9
 *
10
 * @package Mezon
11
 * @subpackage CommonApplication
12
 * @author Dodonov A.A.
13
 * @version v.1.0 (2019/08/07)
14
 * @copyright Copyright (c) 2019, aeon.org
15
 */
16
17
/**
18
 * Common application with any available template
19
 *
20
 * To load routes from the config call $this->load_routes_from_config('./conf/routes.json');
21
 *
22
 * The format of the *.json config must be like this:
23
 *
24
 * [
25
 * {
26
 * "route" : "/route1" ,
27
 * "callback" : "callback1" ,
28
 * "method" : "POST"
29
 * } ,
30
 * {
31
 * "route" : "/route2" ,
32
 * "callback" : "callback2" ,
33
 * "method" : ["GET" , "POST"]
34
 * }
35
 * ]
36
 */
37
class CommonApplication extends Application
38
{
39
40
    /**
41
     * Application's template
42
     *
43
     * @var HtmlTemplate
44
     */
45
    private $template = false;
46
47
    /**
48
     * Constructor
49
     *
50
     * @param HtmlTemplate $template
51
     *            Template
52
     */
53
    public function __construct(HtmlTemplate $template)
54
    {
55
        parent::__construct();
56
57
        $this->template = $template;
58
59
        $this->getRouter()->setNoProcessorFoundErrorHandler([
60
            $this,
61
            'noRouteFoundErrorHandler'
62
        ]);
63
    }
64
65
    /**
66
     * Method handles 404 errors
67
     *
68
     * @codeCoverageIgnore
69
     */
70
    public function noRouteFoundErrorHandler(): void
71
    {
72
        $this->redirectTo('/404');
73
    }
74
75
    /**
76
     * Method renders common parts of all pages.
77
     *
78
     * @return array List of common parts.
79
     */
80
    public function crossRender(): array
81
    {
82
        return [];
83
    }
84
85
    /**
86
     * Method formats exception object
87
     *
88
     * @param \Exception $e
89
     *            Exception
90
     * @return object Formatted exception object
91
     */
92
    protected function baseFormatter(\Exception $e): object
93
    {
94
        $error = new \stdClass();
95
        $error->message = $e->getMessage();
96
        $error->code = $e->getCode();
97
        $error->call_stack = $this->formatCallStack($e);
98
        if (isset($_SERVER['HTTP_HOST']) && $_SERVER['REQUEST_URI']) {
99
            $error->host = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
100
        } else {
101
            $error->host = 'undefined';
102
        }
103
        return $error;
104
    }
105
106
    /**
107
     * Method processes exception.
108
     *
109
     * @param Rest\Exception $e
110
     *            RestException object.
111
     */
112
    public function handleRestException(Rest\Exception $e): void
113
    {
114
        $error = $this->baseFormatter($e);
115
116
        $error->httpBody = $e->getHttpBody();
117
118
        print('<pre>' . json_encode($error, JSON_PRETTY_PRINT));
119
    }
120
121
    /**
122
     * Method processes exception.
123
     *
124
     * @param \Exception $e
125
     *            Exception object.
126
     */
127
    public function handleException(\Exception $e): void
128
    {
129
        $error = $this->baseFormatter($e);
130
131
        print('<pre>' . json_encode($error, JSON_PRETTY_PRINT));
132
    }
133
134
    /**
135
     * Method sets GET parameter as template var
136
     *
137
     * @param string $fieldName
138
     *            name of the GET parameter
139
     */
140
    protected function setGetVar(string $fieldName): void
141
    {
142
        if (isset($_GET[$fieldName])) {
143
            $this->template->setPageVar($fieldName, $_GET[$fieldName]);
144
        }
145
    }
146
147
    /**
148
     * Running application.
149
     */
150
    public function run(): void
151
    {
152
        try {
153
            $callRouteResult = $this->callRoute();
154
155
            if (is_array($callRouteResult) === false) {
156
                throw (new \Exception('Route was not called properly'));
157
            }
158
159
            $result = array_merge($callRouteResult, $this->crossRender());
0 ignored issues
show
Bug introduced by
It seems like $callRouteResult can also be of type null and string and true; however, parameter $array1 of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

159
            $result = array_merge(/** @scrutinizer ignore-type */ $callRouteResult, $this->crossRender());
Loading history...
160
161
            if (is_array($result)) {
0 ignored issues
show
introduced by
The condition is_array($result) is always true.
Loading history...
162
                foreach ($result as $key => $value) {
163
                    $content = $value instanceof ViewInterface ? $value->render() : $value;
164
165
                    $this->template->setPageVar($key, $content);
166
                }
167
            }
168
169
            $this->setGetVar('redirect-to');
170
171
            print($this->template->compile());
172
        } catch (Rest\Exception $e) {
173
            $this->handleRestException($e);
174
        } catch (\Exception $e) {
175
            $this->handleException($e);
176
        }
177
    }
178
179
    /**
180
     * Getting template
181
     *
182
     * @return HtmlTemplate Application's template
183
     * @codeCoverageIgnore
184
     */
185
    public function getTemplate(): HtmlTemplate
186
    {
187
        return $this->template;
188
    }
189
190
    /**
191
     * Setting template
192
     *
193
     * @param HtmlTemplate $template
194
     *            Template
195
     * @codeCoverageIgnore
196
     */
197
    public function setTemplate(HtmlTemplate $template): void
198
    {
199
        $this->template = $template;
200
    }
201
202
    /**
203
     * Method returns localized error message by it's key
204
     *
205
     * @param string $actionMessageCode
206
     *            key of the message
207
     * @return string localized error message by it's key
208
     */
209
    protected function getActionMessage(string $actionMessageCode): string
210
    {
211
        $classPath = $this->getClassPath();
212
213
        if (file_exists($classPath.'/res/action-messages.json')) {
214
            $messages = json_decode(file_get_contents($classPath . '/res/action-messages.json'), true);
215
216
            if (isset($messages[$actionMessageCode])) {
217
                return $messages[$actionMessageCode];
218
            } else {
219
                throw (new \Exception('The message with locator "' . $actionMessageCode . '" was not found', - 1));
220
            }
221
        }
222
223
        return '';
224
    }
225
226
    /**
227
     * Method returns action-message or '' if not set
228
     *
229
     * @return string
230
     */
231
    protected function getActionMessageCode(): string
232
    {
233
        return $_GET['action-message'] ?? '';
234
    }
235
236
    /**
237
     * Method sets message variable
238
     *
239
     * @param string $actionMessageCode
240
     *            message code
241
     */
242
    protected function setSuccessMessage(string $actionMessageCode): void
243
    {
244
        $this->getTemplate()->setPageVar('action-message', $this->getActionMessage($actionMessageCode));
245
    }
246
247
    /**
248
     * Method compiles result record
249
     *
250
     * @param mixed $controller
251
     *            main area controller
252
     * @return array result record
253
     */
254
    public function result($controller = null): void
255
    {
256
        if ($actionMessage = $this->getActionMessageCode()) {
257
            $this->setSuccessMessage($actionMessage);
258
        }
259
260
        if ($controller !== null) {
261
            $controller->run();
262
        }
263
    }
264
}
265