Completed
Push — 2.0 ( bddbd0...6de983 )
by Vermeulen
02:57
created

Rest::getDatas()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 miex
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()
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
                ->getModuleForName('bfw-api')
117
                ->monolog
118
                ->getLogger()
119
                ->debug('No CONTENT_TYPE declared, so data is an empty array.')
120
            ;
121
            
122
            $this->datas = [];
123
            return;
124
        }
125
        
126
        if ($contentType === 'application/json') {
127
            $requestDatas = file_get_contents('php://input');
128
            $this->datas  = Secure::securise(
129
                json_decode($requestDatas, true),
130
                'string',
131
                true
132
            );
133
        } else {
134
            $this->datas = Secure::securise($_POST, 'string', true);
135
        }
136
    }
137
    
138
    /**
139
     * Get the response format to use from header "Accept" or
140
     * the get parameter "format"
141
     * 
142
     * The get parameter have the priority on the "Accept" header
143
     * 
144
     * @return void
145
     */
146
    protected function obtainResponseFormat()
147
    {
148
        $formatFromHeader = $this->obtainResponseFormatFromAcceptHeader();
149
        $formatFromGet    = $this->obtainResponseFormatFromGetParameter();
150
        
151
        if ($formatFromGet !== null) {
152
            $this->responseFormat = $formatFromGet;
153
        } elseif ($formatFromHeader !== null) {
154
            $this->responseFormat = $formatFromHeader;
155
        } else {
156
            http_response_code(406);
157
        }
158
    }
159
    
160
    /**
161
     * Get the format to use from the "Accept" http header
162
     * 
163
     * Header format : text/html,application/xhtml+xml,application/xml;q=0.9
164
     * 
165
     * @return null|string
166
     */
167
    protected function obtainResponseFormatFromAcceptHeader()
168
    {
169
        try {
170
            $acceptHeader = \BFW\Request::getServerValue('HTTP_ACCEPT');
171
        } catch (Exception $e) {
172
            return null;
173
        }
174
        
175
        $availableHeader = [
176
            'application/xml'  => 'xml',
177
            'application/json' => 'json'
178
        ];
179
        
180
        $allAcceptedFormat = explode(',', $acceptHeader);
181
        foreach ($allAcceptedFormat as $mimeTypeWithPreference) {
182
            $cutMimeAndPreference = explode(';', $mimeTypeWithPreference);
183
            $mimeType             = $cutMimeAndPreference[0];
184
            
185
            if (isset($availableHeader[$mimeType])) {
186
                return $availableHeader[$mimeType];
187
            }
188
        }
189
        
190
        return null;
191
    }
192
    
193
    /**
194
     * Get the response format to use from the get paramter "format"
195
     * 
196
     * @return string|null
197
     */
198
    protected function obtainResponseFormatFromGetParameter()
199
    {
200
        try {
201
            $format = Http::obtainGetKey('format', 'text');
202
            
203
            if ($format !== 'xml' && $format !== 'json') {
204
                return null;
205
            }
206
            
207
            return $format;
208
        } catch (Exception $ex) {
209
            return null;
210
        }
211
    }
212
    
213
    /**
214
     * Send a response for the api request with the correct format
215
     * 
216
     * @param mixed $response Datas to send
217
     * 
218
     * @return void
219
     */
220
    protected function sendResponse(&$response)
221
    {
222
        if ($this->responseFormat === 'json') {
223
            $this->sendJsonResponse($response);
224
        } elseif ($this->responseFormat === 'xml') {
225
            $this->sendXmlResponse($response);
226
        }
227
    }
228
    
229
    /**
230
     * Send the response for json format
231
     * 
232
     * @param mixed $response Datas to send
233
     * 
234
     * @return void
235
     */
236
    protected function sendJsonResponse(&$response)
237
    {
238
        header('Content-Type: application/json');
239
        echo json_encode($response);
240
    }
241
    
242
    /**
243
     * Send the response for xml format
244
     * 
245
     * @param mixed $response Datas to send
246
     * 
247
     * @return void
248
     */
249
    protected function sendXmlResponse(&$response)
250
    {
251
        header('Content-Type: application/xml');
252
        
253
        $phpToXml = new \bultonFr\PhpToXml\PhpToXml;
254
        echo $phpToXml->convert($response);
255
    }
256
}
257