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
52 lines (42 loc) · 1.28 KB
/
JSONFormatter.php
File metadata and controls
52 lines (42 loc) · 1.28 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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Format;
use CodeIgniter\Format\Exceptions\FormatException;
use Config\Format;
/**
* JSON data formatter
*
* @see \CodeIgniter\Format\JSONFormatterTest
*/
class JSONFormatter implements FormatterInterface
{
/**
* Takes the given data and formats it.
*
* @param array<array-key, mixed>|object|string $data
*
* @return false|non-empty-string
*/
public function format($data)
{
$config = new Format();
$options = $config->formatterOptions['application/json'] ?? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
$options |= JSON_PARTIAL_OUTPUT_ON_ERROR;
if (ENVIRONMENT !== 'production') {
$options |= JSON_PRETTY_PRINT;
}
$result = json_encode($data, $options, $config->jsonEncodeDepth ?? 512);
if (! in_array(json_last_error(), [JSON_ERROR_NONE, JSON_ERROR_RECURSION], true)) {
throw FormatException::forInvalidJSON(json_last_error_msg());
}
return $result;
}
}