Completed
Push — master ( 7d00bf...8e379c )
by Dante
10s
created

LogTrait::requestHeadersCleanup()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2018 ChannelWeb Srl, Chialab Srl
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 */
10
11
namespace BEdita\SDK;
12
13
use Monolog\Handler\StreamHandler;
14
use Monolog\Logger;
15
use Psr\Http\Message\RequestInterface;
16
use Psr\Http\Message\ResponseInterface;
17
18
/**
19
 * Basic SDK logging functions
20
 */
21
trait LogTrait
22
{
23
    /**
24
     * internal Logger
25
     *
26
     * @var null|Logger
27
     */
28
    protected $logger = null;
29
30
    /**
31
     * Initialize and configure logger
32
     *
33
     * @param array $options Configuration options, 'log_file' key with log file path is mandatory
34
     * @return bool True on successful initialization, false otherwise
35
     */
36
    public function initLogger(array $options): bool
37
    {
38
        // 'path' to log file is mandatory
39
        if (empty($options['log_file'])) {
40
            return false;
41
        }
42
43
        $this->logger = new Logger('be4-php-sdk');
44
        $this->logger->pushHandler(new StreamHandler($options['log_file'], Logger::DEBUG));
45
46
        return true;
47
    }
48
49
    /**
50
     * Perform request log
51
     *
52
     * @param RequestInterface $request The request to log
53
     * @return void
54
     */
55
    public function logRequest(RequestInterface $request) : void
56
    {
57
        if (!$this->logger) {
58
            return;
59
        }
60
61
        $msg = sprintf(
62
            'Request: %s %s - Headers %s - Body %s',
63
            $request->getMethod(),
64
            $request->getUri(),
65
            $this->requestHeadersCleanup($request),
66
            $this->requestBodyCleanup($request)
67
        );
68
        $this->logger->info($msg);
69
    }
70
71
    /**
72
     * Return request body without sensitive information.
73
     *
74
     * @param RequestInterface $request The request to log
75
     * @return string
76
     */
77
    protected function requestBodyCleanup(RequestInterface $request) : string
78
    {
79
        $body = $request->getBody();
80
        if (empty((string)$body)) {
81
            return '(empty)';
82
        }
83
84
        $data = json_decode($body, true);
85
        foreach (['password', 'old_password', 'confirm-password'] as $p) {
86
            if (!empty($data[$p])) {
87
                $data[$p] = '***************';
88
            }
89
            if (!empty($data['data']['attributes'][$p])) {
90
                $data['data']['attributes'][$p] = '***************';
91
            }
92
        }
93
94
        return json_encode($data);
95
    }
96
97
    /**
98
     * Return request headers as string without sensitive information.
99
     *
100
     * @param RequestInterface $request The request to log
101
     * @return string
102
     */
103
    protected function requestHeadersCleanup(RequestInterface $request) : string
104
    {
105
        $headers = $request->getHeaders();
106
        foreach (['Authorization', 'X-Api-Key'] as $h) {
107
            if (!empty($headers[$h]) && !empty(array_diff($headers[$h], ['']))) {
108
                $headers[$h] = ['***************'];
109
            }
110
        }
111
112
        return json_encode($headers);
113
    }
114
115
    /**
116
     * Perform response log
117
     *
118
     * @param ResponseInterface $response The response to log
119
     * @return void
120
     */
121
    public function logResponse(ResponseInterface $response) : void
122
    {
123
        if (!$this->logger) {
124
            return;
125
        }
126
127
        $msg = sprintf(
128
            'Response: %s %s - Headers %s - Body %s',
129
            $response->getStatusCode(),
130
            $response->getReasonPhrase(),
131
            json_encode($response->getHeaders()),
132
            $this->responseBodyCleanup($response)
133
        );
134
        $this->logger->info($msg);
135
    }
136
137
    /**
138
     * Return response body without sensitive information.
139
     *
140
     * @param ResponseInterface $response The response to log
141
     * @return string
142
     */
143
    protected function responseBodyCleanup(ResponseInterface $response) : string
144
    {
145
        $body = $response->getBody();
146
        if (empty((string)$body)) {
147
            return '(empty)';
148
        }
149
150
        $data = json_decode($body, true);
151
        foreach (['jwt', 'renew'] as $tok) {
152
            if (!empty($data['meta'][$tok])) {
153
                $data['meta'][$tok] = '***************';
154
            }
155
        }
156
157
        return json_encode($data);
158
    }
159
}
160