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:
<?php
namespace Baguette\Serializer;
final class PhpJsonSerializer implements SerializerInterface
{
const CONTENT_TYPE = 'application/json; charset=utf-8';
private static $JSON_ERROR_CODES = [
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8',
JSON_ERROR_RECURSION => 'JSON_ERROR_RECURSION',
JSON_ERROR_INF_OR_NAN => 'JSON_ERROR_INF_OR_NAN',
JSON_ERROR_UNSUPPORTED_TYPE => 'JSON_ERROR_UNSUPPORTED_TYPE',
];
public $json_encode_option;
public $empty_as_object;
public function __construct($json_encode_option = null)
{
$this->json_encode_option
= ($json_encode_option !== null) ? $json_encode_option
: JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
}
public function setEmptyAsObject($value = true)
{
$this->empty_as_object = $value;
return $this;
}
public function getContentType()
{
return self::CONTENT_TYPE;
}
public function serialize($value)
{
if ($this->empty_as_object && $value === []) {
$json = json_encode([], $this->json_encode_option | JSON_FORCE_OBJECT);
} else {
$json = json_encode($value, $this->json_encode_option);
}
if ($json !== false) { return $json; }
$error_code = json_last_error();
if ($error_code === JSON_ERROR_NONE) { return false; }
$message = isset(self::$JSON_ERROR_CODES[$error_code])
? self::$JSON_ERROR_CODES[$error_code]
: 'Unknown JSON Error' ;
throw new \DomainException($message);
}
}