Passed
Push — master ( 3065e0...a16e98 )
by Mauro
02:33
created

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