Completed
Push — master ( dba47a...757df8 )
by Derek Stephen
63:42 queued 62:34
created

Controller::initViewEngine()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Bone\Mvc;
4
5
use Bone\Db\Adapter\MySQL;
6
use Bone\Mvc\View\ViewEngine;
7
use Bone\Mvc\View\PlatesEngine;
8
use Bone\Server\Environment;
9
use Bone\Service\LoggerFactory;
10
use Bone\Service\MailService;
11
use InvalidArgumentException;
12
use LogicException;
13
use PDO;
14
use Psr\Http\Message\ServerRequestInterface;
15
use stdClass;
16
use Zend\Diactoros\Response\TextResponse;
17
use Zend\Mail\Transport\Smtp;
18
use Zend\Mail\Transport\SmtpOptions;
19
20
class Controller
21
{
22
    /** @var ServerRequestInterface */
23
    protected $request;
24
25
    /** @var ViewEngine $plates */
26
    protected $viewEngine;
27
28
    /** @var string $controller */
29
    protected $controller;
30
31
    /** @var string $action  */
32
    protected $action;
33
34
    /** @var stdClass $view */
35
    public $view;
36
37
    /** @var string $body */
38
    private $body;
39
40
    /** @var bool */
41
    private $layoutEnabled;
42
43
    /** @var bool */
44
    private $viewEnabled;
45
46
    /** @var array $headers */
47
    private $headers;
48
49
    /** @var int $statusCode */
50
    private $statusCode = 200;
51
52
    /** @var MailService $mailService */
53
    private $mailService;
54
55
    /** @var array $params */
56
    public $params;
57
58
    /** @var array $post */
59
    protected $post = [];
60
61
    /** @var MySQL */
62
    protected $_db;
63
64
    /** @var Environment $serverEnvironment */
65
    protected $serverEnvironment;
66
67
    protected $log;
68
69
    /**
70
     * Controller constructor.
71
     * @param ServerRequestInterface $request
72
     */
73 30
    public function __construct(ServerRequestInterface $request)
74 30
    {
75 30
        $this->request = $request;
76 30
        $this->headers = [];
77 30
        $this->params = $this->request->getQueryParams();
78
79 30
        if ($this->request->getMethod() == 'POST') {
80 18
            $body = $this->request->getParsedBody();
81 18
            $this->post = $body ?: [];
0 ignored issues
show
Documentation Bug introduced by
It seems like $body ?: array() can also be of type object. However, the property $post is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
82
        }
83
84 30
        $this->initViewEngine();
85 30
        $this->view = new stdClass();
86 30
        $this->layoutEnabled = true;
87 30
        $this->viewEnabled = true;
88 30
    }
89
90
    /**
91
     * @return void
92
     */
93 1
    protected function setDB()
94 1
    {
95 1
        $config = Registry::ahoy()->get('db');
96 1
        $this->_db = new MySQL($config);
97 1
    }
98
99
    /**
100
     * @return void
101
     */
102 30
    protected function initViewEngine()
103 30
    {
104 30
        $viewPath = file_exists(APPLICATION_PATH.'/src/App/View/') ? APPLICATION_PATH.'/src/App/View/' : '.' ;
105 30
        $engine = new PlatesEngine($viewPath);
106 30
        $this->viewEngine = $engine;
107 30
    }
108
109 1
    public function setViewEngine(ViewEngine $engine)
110 1
    {
111 1
        $this->viewEngine = $engine;
112 1
    }
113
114
    /**
115
     * @return PDO
116
     */
117 1
    public function getDbAdapter()
118 1
    {
119 1
        if(!$this->_db)
120
        {
121 1
            $this->setDB();
122
        }
123 1
        return $this->_db->getConnection();
124
    }
125
126
    /**
127
     * @return MailService
128
     */
129 1
    public function getMailService()
130 1
    {
131 1
        if (!$this->mailService instanceof MailService) {
132 1
            $this->initMailService();
133
        }
134
135 1
        return $this->mailService;
136
    }
137
138 1
    private function initMailService()
139 1
    {
140 1
        $this->mailService = new MailService();
141 1
        $options = Registry::ahoy()->get('mail');
142 1
        if (isset($options['name']) && isset($options['host']) && isset($options['port']) ) {
143 1
            $transport = new Smtp();
144 1
            $options   = new SmtpOptions($options);
145 1
            $transport->setOptions($options);
146 1
            $this->mailService->setTransport($transport);
147
        }
148 1
    }
149
150
    /**
151
     * @return ViewEngine
152
     */
153 4
    public function getViewEngine()
154 4
    {
155 4
        return $this->viewEngine;
156
    }
157
158
159
    /**
160
     *  runs before th' controller action
161
     */
162 21
    public function init()
163 21
    {
164
        // extend this t' initialise th' controller
165 21
    }
166
167 1
    public function getParams()
168 1
    {
169 1
        return array_merge($this->params, $this->post);
170
    }
171
172
    /**
173
     * @param $param
174
     * @return mixed
175
     */
176 1
    public function getParam($param, $default = null)
177 1
    {
178 1
        $set = isset($this->params[$param]);
179 1
        if ($set && is_string($this->params[$param])) {
180 1
            return urldecode($this->params[$param]);
181 1
        } elseif ($set) {
182 1
            return $this->params[$param];
183
        }
184 1
        return $default;
185
    }
186
187
    /**
188
     * @param $key
189
     * @param $val
190
     * @return $this
191
     */
192 19
    public function setParam($key, $val)
193 19
    {
194 19
        $this->params[$key] = $val;
195 19
        return $this;
196
    }
197
198
    /**
199
     *  runs after yer work is done
200
     */
201 21
    public function postDispatch()
202 21
    {
203
        // extend this t' run code after yer controller is finished
204 21
    }
205
206
    /**
207
     *  For loadin' th' cannon, so t' speak
208
     *
209
     * @return array
210
     */
211 6
    public function getHeaders()
212 6
    {
213 6
        return $this->headers;
214
    }
215
216
    /**
217
     * @return bool
218
     */
219 4
    public function hasLayoutEnabled()
220 4
    {
221 4
        return ($this->layoutEnabled === true);
222
    }
223
224
    /**
225
     * Enables the layout
226
     */
227 1
    public function enableLayout()
228 1
    {
229 1
        $this->layoutEnabled = true;
230 1
    }
231
232
    /**
233
     * Disables the layout
234
     */
235 5
    public function disableLayout()
236 5
    {
237 5
        $this->layoutEnabled = false;
238 5
    }
239
240
    /**
241
     * @return bool
242
     */
243 4
    public function hasViewEnabled()
244 4
    {
245 4
        return ($this->viewEnabled === true);
246
    }
247
248
    /**
249
     * Enables the view
250
     */
251 1
    public function enableView()
252 1
    {
253 1
        $this->viewEnabled = true;
254 1
    }
255
256
    /**
257
     * Disables the view
258
     */
259 5
    public function disableView()
260 5
    {
261 5
        $this->viewEnabled = false;
262 5
    }
263
264
    /**
265
     * @return string
266
     */
267 5
    public function getBody()
268 5
    {
269 5
        return $this->body;
270
    }
271
272
    /**
273
     *  Only used if Layout & View disabled
274
     *
275
     * @param $body
276
     */
277 2
    public function setBody($body)
278 2
    {
279 2
        $this->body = $body;
280 2
    }
281
282
    /**
283
     * @return array
284
     */
285 1
    public function indexAction()
286 1
    {
287 1
        return ['message' => 'Override this method'];
288
    }
289
290 2
    public function errorAction()
291 2
    {
292 2
        $this->disableView();
293 2
        $this->disableLayout();
294 2
        $this->body = '500 Page Error.';
295 2
        return new TextResponse($this->body, 500);
296
    }
297
298 1
    public function notFoundAction()
299 1
    {
300 1
        $this->disableView();
301 1
        $this->disableLayout();
302 1
        $this->body = '404 Page Not Found.';
303 1
    }
304
305
    /**
306
     * @return ServerRequestInterface
307
     */
308 1
    public function getRequest()
309 1
    {
310 1
        return $this->request;
311
    }
312
313
    /**
314
     * @param ServerRequestInterface $request
315
     * @return Controller
316
     */
317 1
    public function setRequest(ServerRequestInterface $request)
318 1
    {
319 1
        $this->request = $request;
320 1
        return $this;
321
    }
322
323
    /**
324
     * @param string $key
325
     * @param string $value
326
     * @return $this
327
     */
328 3
    public function setHeader($key, $value)
329 3
    {
330 3
        $this->headers[$key] = $value;
331 3
        return $this;
332
    }
333
334
    /**
335
     * @param array $headers
336
     */
337 2
    public function setHeaders(array $headers)
338 2
    {
339 2
        $this->headers = $headers;
340 2
    }
341
342
    /**
343
     * @param int $statusCode
344
     */
345 2
    public function setStatusCode($statusCode)
346 2
    {
347 2
        $this->statusCode = $statusCode;
348 2
    }
349
350
    /**
351
     * @return int
352
     */
353 4
    public function getStatusCode()
354 4
    {
355 4
        return $this->statusCode;
356
    }
357
358
359
360
    /**
361
     * @param $key
362
     * @return string|null
363
     */
364 3
    public function getHeader($key)
365 3
    {
366 3
        return $this->headers[$key] ? $this->headers[$key] : null;
367
    }
368
369
    /**
370
     * @param array $data
371
     * @param int $statusCode
372
     */
373 1
    public function sendJsonResponse(array $data, $statusCode = 200)
374 1
    {
375 1
        $this->disableLayout();
376 1
        $this->disableView();
377 1
        $this->setHeader('Cache-Control', 'no-cache, must-revalidate');
378 1
        $this->setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT');
379 1
        $this->setHeader('Content-Type','application/json');
380 1
        $json = json_encode($data);
381 1
        $this->setBody($json);
382 1
        $this->setStatusCode($statusCode);
383 1
    }
384
385
    /**
386
     * @param null $key
387
     * @param string $default
388
     * @return array|string|null
389
     */
390 1
    public function getPost($key = null, $default = null)
391 1
    {
392 1
        if ($key) {
393 1
            return array_key_exists($key, $this->post) ? $this->post[$key] : $default;
394
        }
395
396 1
        return $this->post;
397
    }
398
399
    /**
400
     * @return Environment
401
     */
402
    public function getServerEnvironment(): Environment
403
    {
404
        return $this->serverEnvironment;
405
    }
406
407
    /**
408
     * @param Environment $serverEnvironment
409
     */
410 3
    public function setServerEnvironment(Environment $serverEnvironment)
411 3
    {
412 3
        $this->serverEnvironment = $serverEnvironment;
413 3
    }
414
415
    /**
416
     * @return array|\Monolog\Logger[]
417
     * @throws \Exception
418
     */
419 3
    public function getLog($channel = 'default')
420 3
    {
421 3
        if (!$this->log) {
422 3
            $this->log = $this->initLogs();
423
        }
424
425 1
        if (!isset($this->log[$channel])) {
426
            throw new InvalidArgumentException('No log channel with that name found');
427
        }
428
429 1
        return $this->log[$channel];
430
    }
431
432
    /**
433
     * @return array|\Monolog\Logger[]
434
     * @throws \Exception
435
     */
436 3
    private function initLogs()
437 3
    {
438 3
        $config = Registry::ahoy()->get('log');
439 3
        if (!is_array($config)) {
440 1
            throw new LogicException('No config found');
441
        }
442 2
        $factory = new LoggerFactory();
443 2
        $logs = $factory->createLoggers($config);
444 1
        return $logs;
445
446
    }
447
}
448