Completed
Push — master ( 460020...c44764 )
by Mauro
02:34
created

BaseController   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 6
c 4
b 0
f 0
lcom 1
cbo 0
dl 0
loc 75
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setParams() 0 7 1
A jsonResponse() 0 11 1
A logRequest() 0 12 2
A logResponse() 0 8 2
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
     * Send response with json as standard format.
37
     *
38
     * @param string $status
39
     * @param mixed $message
40
     * @param int $code
41
     * @return array $response
42
     */
43
    protected function jsonResponse($status, $message, $code)
44
    {
45
        $result = [
46
            'code' => $code,
47
            'status' => $status,
48
            'message' => $message,
49
        ];
50
        $this->logResponse($result);
51
52
        return $this->response->withJson($result, $code, JSON_PRETTY_PRINT);
53
    }
54
55
    /**
56
     * Log each request.
57
     */
58
    protected function logRequest()
59
    {
60
        if (!$this->logger) {
61
            return false;
62
        }
63
        $routeInfo = $this->request->getAttribute('routeInfo');
64
        $route = $this->request->getAttribute('route');
65
        $this->logger->info('************');
66
        $this->logger->info('* REQUEST: ' . $route->getCallable()[1]);
67
        $this->logger->info('* ' . $route->getMethods()[0] . ' ' . $routeInfo['request'][1]);
68
        $this->logger->info('* BODY: ' . json_encode($this->request->getParsedBody()));
69
    }
70
71
    /**
72
     * Log each response.
73
     *
74
     * @param array $response
75
     */
76
    protected function logResponse($response)
77
    {
78
        if (!$this->logger) {
79
            return false;
80
        }
81
        $this->logger->info('* RESPONSE: ' . json_encode($response));
82
        $this->logger->info('************');
83
    }
84
}
85