Rest   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 239
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 68
dl 0
loc 239
rs 10
c 0
b 0
f 0
wmc 26

14 Methods

Rating   Name   Duplication   Size   Complexity  
A sendXmlResponse() 0 6 1
A sendJsonResponse() 0 4 1
A obtainResponseFormat() 0 11 3
A getRequest() 0 4 1
A postRequest() 0 4 1
A deleteRequest() 0 4 1
A getResponseFormat() 0 3 1
A obtainDatasFromRequest() 0 26 3
A putRequest() 0 4 1
A sendResponse() 0 6 3
A __construct() 0 4 1
A obtainResponseFormatFromGetParameter() 0 12 4
A getDatas() 0 3 1
A obtainResponseFormatFromAcceptHeader() 0 24 4
1
<?php
2
/**
3
 * @author Vermeulen Maxime <[email protected]>
4
 * @version 2.0
5
 */
6
7
namespace BfwApi;
8
9
use \Exception;
10
use \BFW\Helpers\Http;
11
use \BFW\Helpers\Secure;
12
13
/**
14
 * Abstract class for Rest API user class
15
 * @package bfw-api
16
 */
17
abstract class Rest implements RestInterface
18
{
19
    /**
20
     * @var mixed $datas Datas receive by request
21
     */
22
    protected $datas;
23
    
24
    /**
25
     * @var string $responseFormat (json|xml) The response format to use
26
     */
27
    protected $responseFormat = '';
28
    
29
    /**
30
     * Constructor
31
     * Get datas from the request
32
     */
33
    public function __construct()
34
    {
35
        $this->obtainDatasFromRequest();
36
        $this->obtainResponseFormat();
37
    }
38
    
39
    /**
40
     * Getter accessor for datas property
41
     * 
42
     * @return mixed
43
     */
44
    public function getDatas()
45
    {
46
        return $this->datas;
47
    }
48
49
    /**
50
     * Getter accessor for responseFormat property
51
     * 
52
     * @return string
53
     */
54
    public function getResponseFormat(): string
55
    {
56
        return $this->responseFormat;
57
    }
58
    
59
    /**
60
     * Method called for GET request
61
     * 
62
     * @return void
63
     */
64
    public function getRequest()
65
    {
66
        //Not Implemented
67
        http_response_code(501);
68
    }
69
    
70
    /**
71
     * Method called for POST request
72
     * 
73
     * @return void
74
     */
75
    public function postRequest()
76
    {
77
        //Not Implemented
78
        http_response_code(501);
79
    }
80
    
81
    /**
82
     * Method called for PUT request
83
     * 
84
     * @return void
85
     */
86
    public function putRequest()
87
    {
88
        //Not Implemented
89
        http_response_code(501);
90
    }
91
    
92
    /**
93
     * Method called for DELETE request
94
     * 
95
     * @return void
96
     */
97
    public function deleteRequest()
98
    {
99
        //Not Implemented
100
        http_response_code(501);
101
    }
102
    
103
    /**
104
     * Get datas receive from the request
105
     * 
106
     * @link http://stackoverflow.com/questions/8945879/how-to-get-body-of-a-post-in-php
107
     * 
108
     * @return void
109
     */
110
    protected function obtainDatasFromRequest()
111
    {
112
        try {
113
            $contentType = \BFW\Request::getServerValue('CONTENT_TYPE');
114
        } catch (Exception $e) {
115
            \BFW\Application::getInstance()
116
                ->getModuleList()
117
                ->getModuleByName('bfw-api')
118
                ->monolog
119
                ->getLogger()
120
                ->debug('No CONTENT_TYPE declared, so data is an empty array.')
121
            ;
122
            
123
            $this->datas = [];
124
            return;
125
        }
126
        
127
        if ($contentType === 'application/json') {
128
            $requestDatas = file_get_contents('php://input');
129
            $this->datas  = Secure::secureData(
130
                json_decode($requestDatas, true),
131
                'string',
132
                true
133
            );
134
        } else {
135
            $this->datas = Secure::secureData($_POST, 'string', true);
136
        }
137
    }
138
    
139
    /**
140
     * Get the response format to use from header "Accept" or
141
     * the get parameter "format"
142
     * 
143
     * The get parameter have the priority on the "Accept" header
144
     * 
145
     * @return void
146
     */
147
    protected function obtainResponseFormat()
148
    {
149
        $formatFromHeader = $this->obtainResponseFormatFromAcceptHeader();
150
        $formatFromGet    = $this->obtainResponseFormatFromGetParameter();
151
        
152
        if ($formatFromGet !== null) {
153
            $this->responseFormat = $formatFromGet;
154
        } elseif ($formatFromHeader !== null) {
155
            $this->responseFormat = $formatFromHeader;
156
        } else {
157
            http_response_code(406);
158
        }
159
    }
160
    
161
    /**
162
     * Get the format to use from the "Accept" http header
163
     * 
164
     * Header format : text/html,application/xhtml+xml,application/xml;q=0.9
165
     * 
166
     * @return null|string
167
     */
168
    protected function obtainResponseFormatFromAcceptHeader()
169
    {
170
        try {
171
            $acceptHeader = \BFW\Request::getServerValue('HTTP_ACCEPT');
172
        } catch (Exception $e) {
173
            return null;
174
        }
175
        
176
        $availableHeader = [
177
            'application/xml'  => 'xml',
178
            'application/json' => 'json'
179
        ];
180
        
181
        $allAcceptedFormat = explode(',', $acceptHeader);
182
        foreach ($allAcceptedFormat as $mimeTypeWithPreference) {
183
            $cutMimeAndPreference = explode(';', $mimeTypeWithPreference);
184
            $mimeType             = $cutMimeAndPreference[0];
185
            
186
            if (isset($availableHeader[$mimeType])) {
187
                return $availableHeader[$mimeType];
188
            }
189
        }
190
        
191
        return null;
192
    }
193
    
194
    /**
195
     * Get the response format to use from the get paramter "format"
196
     * 
197
     * @return string|null
198
     */
199
    protected function obtainResponseFormatFromGetParameter()
200
    {
201
        try {
202
            $format = Http::obtainGetKey('format', 'text');
203
            
204
            if ($format !== 'xml' && $format !== 'json') {
205
                return null;
206
            }
207
            
208
            return $format;
209
        } catch (Exception $ex) {
210
            return null;
211
        }
212
    }
213
    
214
    /**
215
     * Send a response for the api request with the correct format
216
     * 
217
     * @param mixed $response Datas to send
218
     * 
219
     * @return void
220
     */
221
    protected function sendResponse(&$response)
222
    {
223
        if ($this->responseFormat === 'json') {
224
            $this->sendJsonResponse($response);
225
        } elseif ($this->responseFormat === 'xml') {
226
            $this->sendXmlResponse($response);
227
        }
228
    }
229
    
230
    /**
231
     * Send the response for json format
232
     * 
233
     * @param mixed $response Datas to send
234
     * 
235
     * @return void
236
     */
237
    protected function sendJsonResponse(&$response)
238
    {
239
        header('Content-Type: application/json');
240
        echo json_encode($response);
241
    }
242
    
243
    /**
244
     * Send the response for xml format
245
     * 
246
     * @param mixed $response Datas to send
247
     * 
248
     * @return void
249
     */
250
    protected function sendXmlResponse(&$response)
251
    {
252
        header('Content-Type: application/xml');
253
        
254
        $phpToXml = new \bultonFr\PhpToXml\PhpToXml;
255
        echo $phpToXml->convert($response);
256
    }
257
}
258