JsonSerializer.php 1.98 KB
Newer Older
Ketan's avatar
Ketan committed
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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\TestFramework\Helper;

/**
 * Encodes and decodes JSON and checks for errors on these operations
 */
class JsonSerializer
{
    /**
     * @var array JSON Error code to error message mapping
     */
    private $jsonErrorMessages = [
        JSON_ERROR_DEPTH => 'Maximum depth exceeded',
        JSON_ERROR_STATE_MISMATCH => 'State mismatch',
        JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
        JSON_ERROR_SYNTAX => 'Syntax error, invalid JSON',
    ];

    /**
     * Encode a string as a JSON object with error checking
     *
     * @param mixed $data
     * @return string
     * @throws \Exception
     */
    public function jsonEncode($data)
    {
        $ret = json_encode($data);
        $this->checkJsonError($data);

        // return the json String
        return $ret;
    }

    /**
     * Decode a JSON string with error checking
     *
     * @param string $data
     * @param bool $asArray
     * @throws \Exception
     * @return mixed
     */
    public function jsonDecode($data, $asArray = true)
    {
        $ret = json_decode($data, $asArray);
        $this->checkJsonError($data);

        // return the array
        return $ret;
    }

    /**
     * Checks for JSON error in the latest encoding / decoding and throws an exception in case of error
     *
     * @throws \Exception
     */
    private function checkJsonError()
    {
        $jsonError = json_last_error();
        if ($jsonError !== JSON_ERROR_NONE) {
            // find appropriate error message
            $message = 'Unknown JSON Error';
            if (isset($this->jsonErrorMessages[$jsonError])) {
                $message = $this->jsonErrorMessages[$jsonError];
            }

            throw new \Exception(
                'JSON Encoding / Decoding error: ' . $message . var_export(func_get_arg(0), true),
                $jsonError
            );
        }
    }
}