Completed
Push — master ( a5086d...460020 )
by Mauro
02:28
created

BaseController::getTaskService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace App\Controller;
4
5
use App\Service\UserService;
6
7
/**
8
 * Base Controller.
9
 */
10
abstract class BaseController
11
{
12
    protected $logger;
13
14
    protected $database;
15
16
    protected $request;
17
18
    protected $response;
19
20
    protected $args;
21
22
    /**
23
     * @param Request $request
24
     * @param Response $response
25
     * @param array $args
26
     */
27
    protected function setParams($request, $response, $args)
28
    {
29
        $this->request = $request;
30
        $this->response = $response;
31
        $this->args = $args;
32
        $this->logRequest();
33
    }
34
35
    /**
36
     * @return UserService
37
     */
38
    protected function getUserService()
39
    {
40
        $service = new UserService($this->database);
41
42
        return $service;
43
    }
44
45
    /**
46
     * Send response with json as standard format.
47
     *
48
     * @param string $status
49
     * @param mixed $message
50
     * @param int $code
51
     * @return array $response
52
     */
53
    protected function jsonResponse($status, $message, $code)
54
    {
55
        $result = [
56
            'code' => $code,
57
            'status' => $status,
58
            'message' => $message,
59
        ];
60
        $this->logResponse($result);
61
62
        return $this->response->withJson($result, $code, JSON_PRETTY_PRINT);
63
    }
64
65
    /**
66
     * Log each request.
67
     */
68
    protected function logRequest()
69
    {
70
        if (!$this->logger) {
71
            return false;
72
        }
73
        $routeInfo = $this->request->getAttribute('routeInfo');
74
        $route = $this->request->getAttribute('route');
75
        $this->logger->info('************');
76
        $this->logger->info('* REQUEST: ' . $route->getCallable()[1]);
77
        $this->logger->info('* ' . $route->getMethods()[0] . ' ' . $routeInfo['request'][1]);
78
        $this->logger->info('* BODY: ' . json_encode($this->request->getParsedBody()));
79
    }
80
81
    /**
82
     * Log each response.
83
     *
84
     * @param array $response
85
     */
86
    protected function logResponse($response)
87
    {
88
        if (!$this->logger) {
89
            return false;
90
        }
91
        $this->logger->info('* RESPONSE: ' . json_encode($response));
92
        $this->logger->info('************');
93
    }
94
}
95