forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONFormatter.php
More file actions
49 lines (42 loc) · 1.5 KB
/
Copy pathJSONFormatter.php
File metadata and controls
49 lines (42 loc) · 1.5 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
<?php namespace CodeIgniter\API;
class JSONFormatter implements FormatterInterface
{
/**
* The error strings to use if encoding hits an error.
*
* @var array
*/
protected $errors = [
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
];
//--------------------------------------------------------------------
/**
* Takes the given data and formats it.
*
* @todo Handle converting entity classes from db results, since we handle loading/saving those...
*
* @param $data
*
* @return mixed
*/
public function format(array $data)
{
$options = ENVIRONMENT == 'production'
? JSON_NUMERIC_CHECK
: JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT;
$result = json_encode($data, 512, $options);
// If result is NULL, then an error happened.
// Let them know.
if ($result === null)
{
throw new \RuntimeException($this->errors[json_last_error()]);
}
return utf8_encode($result);
}
//--------------------------------------------------------------------
}