Completed
Push — master ( 757df8...636a7a )
by Derek Stephen
60:02 queued 58:57
created

Controller::initTranslator()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.7333
c 0
b 0
f 0
cc 4
nc 3
nop 0
crap 4
1
<?php
2
3
namespace Bone\Mvc;
4
5
use Bone\Db\Adapter\MySQL;
6
use Bone\Mvc\View\Extension\Plates\Translate;
7
use Bone\Mvc\View\ViewEngine;
8
use Bone\Mvc\View\PlatesEngine;
9
use Bone\Server\Environment;
10
use Bone\Service\LoggerFactory;
11
use Bone\Service\MailService;
12
use Bone\Service\TranslatorFactory;
13
use InvalidArgumentException;
14
use League\Plates\Engine;
15
use LogicException;
16
use Monolog\Logger;
17
use PDO;
18
use Psr\Http\Message\ServerRequestInterface;
19
use stdClass;
20
use Zend\Diactoros\Response\TextResponse;
21
use Zend\Mail\Transport\Smtp;
22
use Zend\Mail\Transport\SmtpOptions;
23
24
class Controller
25
{
26
    /** @var ServerRequestInterface */
27
    protected $request;
28
29
    /** @var ViewEngine $plates */
30
    protected $viewEngine;
31
32
    /** @var string $controller */
33
    protected $controller;
34
35
    /** @var string $action  */
36
    protected $action;
37
38
    /** @var stdClass $view */
39
    public $view;
40
41
    /** @var string $body */
42
    private $body;
43
44
    /** @var bool */
45
    private $layoutEnabled;
46
47
    /** @var bool */
48
    private $viewEnabled;
49
50
    /** @var array $headers */
51
    private $headers;
52
53
    /** @var int $statusCode */
54
    private $statusCode = 200;
55
56
    /** @var MailService $mailService */
57
    private $mailService;
58
59
    /** @var array $params */
60
    public $params;
61
62
    /** @var array $post */
63
    protected $post = [];
64
65
    /** @var MySQL */
66
    protected $_db;
67
68
    /** @var Environment $serverEnvironment */
69
    protected $serverEnvironment;
70
71
    /** @var Logger[] $log */
72
    protected $log;
73
74
    protected $translator;
75
76
    /**
77
     * Controller constructor.
78
     * @param ServerRequestInterface $request
79
     * @throws \Exception
80
     */
81 33
    public function __construct(ServerRequestInterface $request)
82 33
    {
83 33
        $this->request = $request;
84 33
        $this->headers = [];
85 33
        $this->params = $this->request->getQueryParams();
86
87 33
        if ($this->request->getMethod() == 'POST') {
88 21
            $body = $this->request->getParsedBody();
89 21
            $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...
90
        }
91
92 33
        $this->initViewEngine();
93 33
        $this->initTranslator();
94 33
        $this->initLogs();
95 33
        $this->view = new stdClass();
96 33
        $this->layoutEnabled = true;
97 33
        $this->viewEnabled = true;
98 33
    }
99
100
    /**
101
     * @return void
102
     */
103 1
    protected function setDB()
104 1
    {
105 1
        $config = Registry::ahoy()->get('db');
106 1
        $this->_db = new MySQL($config);
107 1
    }
108
109
    /**
110
     * @return void
111
     */
112 33
    protected function initViewEngine()
113 33
    {
114 33
        $viewPath = file_exists(APPLICATION_PATH.'/src/App/View/') ? APPLICATION_PATH.'/src/App/View/' : '.' ;
115 33
        $engine = new PlatesEngine($viewPath);
116 33
        $this->viewEngine = $engine;
117 33
    }
118
119 1
    public function setViewEngine(ViewEngine $engine)
120 1
    {
121 1
        $this->viewEngine = $engine;
122 1
    }
123
124
    /**
125
     * @return PDO
126
     */
127 1
    public function getDbAdapter()
128 1
    {
129 1
        if(!$this->_db)
130
        {
131 1
            $this->setDB();
132
        }
133 1
        return $this->_db->getConnection();
134
    }
135
136
    /**
137
     * @return MailService
138
     */
139 1
    public function getMailService()
140 1
    {
141 1
        if (!$this->mailService instanceof MailService) {
142 1
            $this->initMailService();
143
        }
144
145 1
        return $this->mailService;
146
    }
147
148 1
    private function initMailService()
149 1
    {
150 1
        $this->mailService = new MailService();
151 1
        $options = Registry::ahoy()->get('mail');
152 1
        if (isset($options['name']) && isset($options['host']) && isset($options['port']) ) {
153 1
            $transport = new Smtp();
154 1
            $options   = new SmtpOptions($options);
155 1
            $transport->setOptions($options);
156 1
            $this->mailService->setTransport($transport);
157
        }
158 1
    }
159
160
    /**
161
     * @return ViewEngine
162
     */
163 15
    public function getViewEngine()
164 15
    {
165 15
        return $this->viewEngine;
166
    }
167
168
169
    /**
170
     *  runs before th' controller action
171
     */
172 24
    public function init()
173 24
    {
174
        // extend this t' initialise th' controller
175 24
    }
176
177 1
    public function getParams()
178 1
    {
179 1
        return array_merge($this->params, $this->post);
180
    }
181
182
    /**
183
     * @param $param
184
     * @param null $default
185
     * @return mixed|null|string
186
     */
187 1
    public function getParam($param, $default = null)
188 1
    {
189 1
        $set = isset($this->params[$param]);
190 1
        if ($set && is_string($this->params[$param])) {
191 1
            return urldecode($this->params[$param]);
192 1
        } elseif ($set) {
193 1
            return $this->params[$param];
194
        }
195 1
        return $default;
196
    }
197
198
    /**
199
     * @param $key
200
     * @param $val
201
     * @return $this
202
     */
203 22
    public function setParam($key, $val)
204 22
    {
205 22
        $this->params[$key] = $val;
206 22
        return $this;
207
    }
208
209
    /**
210
     *  runs after yer work is done
211
     */
212 24
    public function postDispatch()
213 24
    {
214
        // extend this t' run code after yer controller is finished
215 24
    }
216
217
    /**
218
     *  For loadin' th' cannon, so t' speak
219
     *
220
     * @return array
221
     */
222 6
    public function getHeaders()
223 6
    {
224 6
        return $this->headers;
225
    }
226
227
    /**
228
     * @return bool
229
     */
230 4
    public function hasLayoutEnabled()
231 4
    {
232 4
        return ($this->layoutEnabled === true);
233
    }
234
235
    /**
236
     * Enables the layout
237
     */
238 1
    public function enableLayout()
239 1
    {
240 1
        $this->layoutEnabled = true;
241 1
    }
242
243
    /**
244
     * Disables the layout
245
     */
246 5
    public function disableLayout()
247 5
    {
248 5
        $this->layoutEnabled = false;
249 5
    }
250
251
    /**
252
     * @return bool
253
     */
254 4
    public function hasViewEnabled()
255 4
    {
256 4
        return ($this->viewEnabled === true);
257
    }
258
259
    /**
260
     * Enables the view
261
     */
262 1
    public function enableView()
263 1
    {
264 1
        $this->viewEnabled = true;
265 1
    }
266
267
    /**
268
     * Disables the view
269
     */
270 5
    public function disableView()
271 5
    {
272 5
        $this->viewEnabled = false;
273 5
    }
274
275
    /**
276
     * @return string
277
     */
278 5
    public function getBody()
279 5
    {
280 5
        return $this->body;
281
    }
282
283
    /**
284
     *  Only used if Layout & View disabled
285
     *
286
     * @param $body
287
     */
288 2
    public function setBody($body)
289 2
    {
290 2
        $this->body = $body;
291 2
    }
292
293
    /**
294
     * @return array
295
     */
296 1
    public function indexAction()
297 1
    {
298 1
        return ['message' => 'Override this method'];
299
    }
300
301 2
    public function errorAction()
302 2
    {
303 2
        $this->disableView();
304 2
        $this->disableLayout();
305 2
        $this->body = '500 Page Error.';
306 2
        return new TextResponse($this->body, 500);
307
    }
308
309 1
    public function notFoundAction()
310 1
    {
311 1
        $this->disableView();
312 1
        $this->disableLayout();
313 1
        $this->body = '404 Page Not Found.';
314 1
    }
315
316
    /**
317
     * @return ServerRequestInterface
318
     */
319 1
    public function getRequest()
320 1
    {
321 1
        return $this->request;
322
    }
323
324
    /**
325
     * @param ServerRequestInterface $request
326
     * @return Controller
327
     */
328 1
    public function setRequest(ServerRequestInterface $request)
329 1
    {
330 1
        $this->request = $request;
331 1
        return $this;
332
    }
333
334
    /**
335
     * @param string $key
336
     * @param string $value
337
     * @return $this
338
     */
339 3
    public function setHeader($key, $value)
340 3
    {
341 3
        $this->headers[$key] = $value;
342 3
        return $this;
343
    }
344
345
    /**
346
     * @param array $headers
347
     */
348 2
    public function setHeaders(array $headers)
349 2
    {
350 2
        $this->headers = $headers;
351 2
    }
352
353
    /**
354
     * @param int $statusCode
355
     */
356 2
    public function setStatusCode($statusCode)
357 2
    {
358 2
        $this->statusCode = $statusCode;
359 2
    }
360
361
    /**
362
     * @return int
363
     */
364 4
    public function getStatusCode()
365 4
    {
366 4
        return $this->statusCode;
367
    }
368
369
370
371
    /**
372
     * @param $key
373
     * @return string|null
374
     */
375 3
    public function getHeader($key)
376 3
    {
377 3
        return $this->headers[$key] ? $this->headers[$key] : null;
378
    }
379
380
    /**
381
     * @param array $data
382
     * @param int $statusCode
383
     */
384 1
    public function sendJsonResponse(array $data, $statusCode = 200)
385 1
    {
386 1
        $this->disableLayout();
387 1
        $this->disableView();
388 1
        $this->setHeader('Cache-Control', 'no-cache, must-revalidate');
389 1
        $this->setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT');
390 1
        $this->setHeader('Content-Type','application/json');
391 1
        $json = json_encode($data);
392 1
        $this->setBody($json);
393 1
        $this->setStatusCode($statusCode);
394 1
    }
395
396
    /**
397
     * @param null $key
398
     * @param string $default
399
     * @return array|string|null
400
     */
401 1
    public function getPost($key = null, $default = null)
402 1
    {
403 1
        if ($key) {
404 1
            return array_key_exists($key, $this->post) ? $this->post[$key] : $default;
405
        }
406
407 1
        return $this->post;
408
    }
409
410
    /**
411
     * @return Environment
412
     */
413
    public function getServerEnvironment(): Environment
414
    {
415
        return $this->serverEnvironment;
416
    }
417
418
    /**
419
     * @param Environment $serverEnvironment
420
     */
421 3
    public function setServerEnvironment(Environment $serverEnvironment)
422 3
    {
423 3
        $this->serverEnvironment = $serverEnvironment;
424 3
    }
425
426
    /**
427
     * @param string $channel
428
     * @return Logger
429
     */
430 2
    public function getLog($channel = 'default'): Logger
431 2
    {
432 2
        if (!$this->log) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->log of type Monolog\Logger[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
433 1
            throw new LogicException('No log config found');
434
        }
435
436 1
        if (!isset($this->log[$channel])) {
437
            throw new InvalidArgumentException('No log channel with that name found');
438
        }
439
440 1
        return $this->log[$channel];
441
    }
442
443
    /**
444
     * @throws \Exception
445
     */
446 33
    private function initLogs()
447 33
    {
448 33
        $config = Registry::ahoy()->get('log');
449 33
        if (is_array($config)) {
450 2
            $factory = new LoggerFactory();
451 2
            $logs = $factory->createLoggers($config);
452 1
            $this->log = $logs;
453
        }
454 33
    }
455
456
    /**
457
     * @return \Zend\I18n\Translator\Translator
458
     */
459 3
    public function getTranslator()
460 3
    {
461 3
        if (!$this->translator) {
462
            throw new LogicException('No i18n config found');
463
        }
464
465 3
        return $this->translator;
466
    }
467
468 33
    private function initTranslator()
469 33
    {
470 33
        $config = Registry::ahoy()->get('i18n');
471 33
        if (is_array($config) && !$this->translator) {
472
473 14
            $factory = new TranslatorFactory();
474 14
            $translator = $factory->createTranslator($config);
475
476 14
            $engine = $this->getViewEngine();
477 14
            if ($engine instanceof Engine) {
478 14
                $engine->loadExtension(new Translate($translator));
479
            }
480
481 14
            $this->translator = $translator;
482
        }
483 33
    }
484
}
485