-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
312 lines (273 loc) · 11.2 KB
/
index.php
File metadata and controls
312 lines (273 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
<?php
/**
* JSONP Api
* --------
*/
class jsonApi {
/**
* PRIVATE DATA
*/
private $apiData;
private $apiResponses = array(
// errors messages
'data/missing' => array( 'status' => "error", 'msg' => "Missing ALL data." ),
'action/missing' => array( 'status' => "error", 'msg' => "Missing `action` data." ),
'action/invalid' => array( 'status' => "error", 'msg' => "Action requested isn't allowed." ),
'method/missing' => array( 'status' => "error", 'msg' => "Missing `method` data." ),
'method/invalid' => array( 'status' => "error", 'msg' => "Method requested doesn't exist." ),
'response/invalid' => array( 'status' => "error", 'msg' => "Invalid data passed to response method." ),
'database/config/missing' => array( 'status' => "error", 'msg' => "Database configuration file is missing." ),
'database/insert/error' => array( 'status' => "error", 'msg' => "Problem occured on insertion into database." ),
'lead/data/missing' => array( 'status' => "error", 'msg' => "Missing required data." ),
// success messages
'lead/insert/success' => array( 'status' => "success", 'msg' => "One of our consultants will contact you as soon as possible. Thank you!" )
);
private $apiValidActions = array( 'get', 'post', 'put', 'delete' );
private $databaseConfig = array();
private $environment;
private $db;
/**
* PUBLIC METHODS
*/
/**
* Class constructor
* @param array $data Data that the api will be using internally
* @public
*/
public function __construct( $data ) {
// set environment, validating and uppercasing as insurance
$this->setEnvironment();
// save data for later use
$this->apiData = $data;
// check for ANY data
if( count( $this->apiData ) == 0 ) {
$this->response( $this->apiResponses['data/missing'] );
}
// check for ACTION data
if( !array_key_exists( 'action', $this->apiData ) ) {
$this->response( $this->apiResponses['action/missing'] );
}
// check for METHOD data
if( !array_key_exists( 'method', $this->apiData ) ) {
$this->response( $this->apiResponses['method/missing'] );
}
// check action
if( !in_array( $this->apiData['action'], $this->apiValidActions ) ) {
$this->response( $this->apiResponses['action/invalid'] );
}
// connect database
$this->databaseInit();
// send to router
$this->router( $this->apiData['action'], $this->apiData['method'] );
}
/**
* PRIVATE METHODS
*/
/**
* Set correct environment for class instance
* @return void
* @private
*/
private function setEnvironment() {
// capitalize and set correct environment
$this->environment = getenv( 'ENVIRONMENT' );
if( empty( $this->environment ) ) {
$this->environment = 'DEVELOPMENT';
}
$this->environment = strtoupper( $this->environment );
// hide warnings on productions
if( $this->environment === 'PRODUCTION') {
error_reporting( E_ERROR | E_PARSE );
}
}
/**
* Response method for the api. Returns everything in json (or jsonp) format.
* @param array $responseData Response data in array format to be converted to JSON
* @return output Kills process with FINAL output
* @private
*/
private function response( $responseData ) {
// check integrity of data
if( !is_array( $responseData ) ) {
// override `responseData` with error message
$responseData = $this->apiResponses['response/invalid'];
}
// send data in JSONP format
if( array_key_exists( 'callback', $this->apiData ) && !empty( $this->apiData['callback'] ) ) {
die( $this->apiData['callback'].'('.json_encode( $responseData ).')' );
}
// send data in JSON format
else {
die( json_encode( $responseData ) );
}
}
/**
* Configure database and connect to it
* @return void
* @private
*/
private function databaseInit() {
// include database paths
require_once "paths.php";
// select correct db config
if( isset( $dbEnvironments ) ) {
$this->databaseConfig = $dbEnvironments[$this->environment];
} else {
// no db paths, error out
$this->response( $this->apiResponses['database/config/missing'] );
}
// start database connection
$this->db = new mysqli(
$this->databaseConfig['hostname'],
$this->databaseConfig['username'],
$this->databaseConfig['password'],
$this->databaseConfig['database']
);
// verify connection
if( $this->db->connect_error ) {
die( 'Connect Error ('.$this->db->connect_errno.') '.$this->db->connect_error );
}
}
/**
* Router method that routes request to correct destination
* @param string $action Name of action type requested
* @param string $method Name of method requested
* @return void
* @private
*/
private function router( $action, $method ) {
$action = strtolower( $action );
$method = '_'.$action.'_'.$method;
// validate method requested
if( !method_exists( 'jsonApi', $method ) ) {
$this->response( $this->apiResponses['method/invalid'] );
}
// call requested method
call_user_func( array( $this, $method ) );
}
/**
* Validate required fields against pool of possible data fields
* @param array $requiredFields Array of required fields
* @param array $availableFields Array of possible available fields
* @param string $errorToUse Error code to use on possible requirement infracture
* @return void
* @private
*/
private function validateFields( $requiredFields, $availableFields, $errorToUse = 'lead/data/missing' ) {
// check for missing required fields and log them
$isValid = TRUE;
$isMissing = array();
foreach( $requiredFields as $field ) {
if( !array_key_exists( $field, $availableFields ) || empty( $availableFields[$field] ) ) {
array_push( $isMissing, "`$field` is missing." );
$isValid = FALSE;
}
}
// if anything is missing, through output here and halt script execution
if( !$isValid ) {
$errorMsg = $this->apiResponses[$errorToUse];
$errorMsg['debug'] = $isMissing;
$this->response( $errorMsg );
}
}
/**
* Determine if a single field is available and has data
* @param array $dbData Array of data going in to the database
* @param string $field Name of field that will be checked
* @return array New array of data going into the database (possible with an extra field)
* @private
*/
private function filterForDbData( $dbData, $field ) {
if( array_key_exists( $field, $this->apiData ) && !empty( $this->apiData[$field] ) ) {
$dbData[strtoupper( $field )] = trim( $this->apiData[$field] );
}
return $dbData;
}
/**
* Build all data for database (required and extra fields)
* @param array $possibleFields Array of possible fields to add into database data
* @return array Complete database data array
*/
private function buildDbData( $possibleFields ) {
$dbData = array();
foreach( $possibleFields as $field ) {
$dbData = $this->filterForDbData( $dbData, $field );
}
return $dbData;
}
/**
* Handle all INSERT statements into database
* @param string $leadType Type of lead
* @param array $requiredFields List of required fields
* @param array $possibleFields List of all available fields
* @param array $responseKeys Custom response keys
* @param string $table Default db table to insert into
* @return void
* @private
*/
private function insertLeadSql( $leadType, $requiredFields, $possibleFields, $responseKeys, $table = 'leads' ) {
// validate required fields
$this->validateFields( $requiredFields, $this->apiData );
// prepare data for db
$dbData = $this->buildDbData( $possibleFields );
if( count( $dbData ) ) {
// set lead type
$dbData['LEAD_TYPE'] = $leadType;
// insert into db
$sql = "INSERT INTO `$table` ({FIELDS}) VALUES ({VALUES})";
$sql = str_replace( array( '{FIELDS}', '{VALUES}' ), array( '`'.implode( '`, `', array_keys( $dbData ) ).'`', "'".implode( "','", array_values( $dbData ) )."'" ), $sql );
// output request result
if( $this->db->query( $sql ) ) {
$successMsg = $this->apiResponses[$responseKeys['success']];
$successMsg['id'] = $this->db->insert_id;
$this->response( $successMsg );
}
// error occured, notify client
else {
$this->response( $this->apiResponses['database/insert/error'] );
}
}
// missing db data
$errorMsg = $this->apiResponses['lead/data/missing'];
$errorMsg['debug'] = array( 'No Database data present.' );
$this->response( $errorMsg );
}
/**
* Put NEW product lead in database
* @return string Result of request in JSON format
*/
private function _put_product_lead() {
// required variables
$requiredFields = array( 'domain', 'name', 'telephone', 'product' );
$possibleFields = array_merge( $requiredFields, array( 'email', 'message' ) );
$responseKeys = array( 'success' => 'lead/insert/success' );
// handle DB insertion
$this->insertLeadSql( 'product', $requiredFields, $possibleFields, $responseKeys );
}
/**
* Put NEW contact lead in database
* @return string Result of request in JSON format
*/
private function _put_contact_lead() {
// required variables
$requiredFields = array( 'domain', 'name', 'telephone' );
$possibleFields = array_merge( $requiredFields, array( 'email', 'message' ) );
$responseKeys = array( 'success' => 'lead/insert/success' );
// handle DB insertion
$this->insertLeadSql( 'contact', $requiredFields, $possibleFields, $responseKeys );
}
/**
* Put NEW consultant lead in database
* @return string Result of request in JSON format
*/
private function _put_consultant_lead() {
// required variables
$requiredFields = array( 'domain', 'name', 'telephone', 'email', 'message' );
$possibleFields = $requiredFields;
$responseKeys = array( 'success' => 'lead/insert/success' );
// handle DB insertion
$this->insertLeadSql( 'consultant', $requiredFields, $possibleFields, $responseKeys );
}
}
// initialie api and process request
$api = new jsonApi( count( $_GET ) ? $_GET : array() );