Overview

Namespaces

  • Webmozart
    • Json

Classes

  • Webmozart\Json\JsonDecoder
  • Webmozart\Json\JsonEncoder
  • Webmozart\Json\JsonError
  • Webmozart\Json\JsonValidator

Exceptions

  • Webmozart\Json\DecodingFailedException
  • Webmozart\Json\EncodingFailedException
  • Webmozart\Json\FileNotFoundException
  • Webmozart\Json\InvalidSchemaException
  • Webmozart\Json\ValidationFailedException
  • Overview
  • Namespace
  • Class
  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: 313: 314: 315: 316: 
<?php

/*
 * This file is part of the Webmozart JSON package.
 *
 * (c) Bernhard Schussek <bschussek@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webmozart\Json;

use Seld\JsonLint\JsonParser;
use Seld\JsonLint\ParsingException;

/**
 * Decodes JSON strings/files and validates against a JSON schema.
 *
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class JsonDecoder
{
    /**
     * Decode a JSON value as PHP object.
     */
    const OBJECT = 0;

    /**
     * Decode a JSON value as associative array.
     */
    const ASSOC_ARRAY = 1;

    /**
     * Decode a JSON value as float.
     */
    const FLOAT = 2;

    /**
     * Decode a JSON value as string.
     */
    const STRING = 3;

    /**
     * @var JsonValidator
     */
    private $validator;

    /**
     * @var int
     */
    private $objectDecoding = self::OBJECT;

    /**
     * @var int
     */
    private $bigIntDecoding = self::FLOAT;

    /**
     * @var int
     */
    private $maxDepth = 512;

    /**
     * Creates a new decoder.
     */
    public function __construct()
    {
        $this->validator = new JsonValidator();
    }

    /**
     * Decodes and validates a JSON string.
     *
     * If a schema is passed, the decoded object is validated against that
     * schema. The schema may be passed as file path or as object returned from
     * `JsonDecoder::decodeFile($schemaFile)`.
     *
     * You can adjust the decoding with {@link setObjectDecoding()},
     * {@link setBigIntDecoding()} and {@link setMaxDepth()}.
     *
     * Schema validation is not supported when objects are decoded as
     * associative arrays.
     *
     * @param string        $json   The JSON string.
     * @param string|object $schema The schema file or object.
     *
     * @return mixed The decoded value.
     *
     * @throws DecodingFailedException   If the JSON string could not be decoded.
     * @throws ValidationFailedException If the decoded string fails schema
     *                                   validation.
     * @throws InvalidSchemaException    If the schema is invalid.
     */
    public function decode($json, $schema = null)
    {
        if (self::ASSOC_ARRAY === $this->objectDecoding && null !== $schema) {
            throw new \InvalidArgumentException(
                'Schema validation is not supported when objects are decoded '.
                'as associative arrays. Call '.
                'JsonDecoder::setObjectDecoding(JsonDecoder::JSON_OBJECT) to fix.'
            );
        }

        $decoded = $this->decodeJson($json);

        if (null !== $schema) {
            $errors = $this->validator->validate($decoded, $schema);

            if (count($errors) > 0) {
                throw ValidationFailedException::fromErrors($errors);
            }
        }

        return $decoded;
    }

    /**
     * Decodes and validates a JSON file.
     *
     * @param string        $file   The path to the JSON file.
     * @param string|object $schema The schema file or object.
     *
     * @return mixed The decoded file.
     *
     * @throws FileNotFoundException     If the file was not found.
     * @throws DecodingFailedException   If the file could not be decoded.
     * @throws ValidationFailedException If the decoded file fails schema
     *                                   validation.
     * @throws InvalidSchemaException    If the schema is invalid.
     *
     * @see decode
     */
    public function decodeFile($file, $schema = null)
    {
        if (!file_exists($file)) {
            throw new FileNotFoundException(sprintf(
                'The file %s does not exist.',
                $file
            ));
        }

        try {
            return $this->decode(file_get_contents($file), $schema);
        } catch (DecodingFailedException $e) {
            // Add the file name to the exception
            throw new DecodingFailedException(sprintf(
                'An error happened while decoding %s: %s',
                $file,
                $e->getMessage()
            ), $e->getCode(), $e);
        } catch (ValidationFailedException $e) {
            // Add the file name to the exception
            throw new ValidationFailedException(sprintf(
                "Validation of %s failed:\n%s",
                $file,
                $e->getErrorsAsString()
            ), $e->getErrors(), $e->getCode(), $e);
        } catch (InvalidSchemaException $e) {
            // Add the file name to the exception
            throw new InvalidSchemaException(sprintf(
                'An error happened while decoding %s: %s',
                $file,
                $e->getMessage()
            ), $e->getCode(), $e);
        }
    }

    /**
     * Returns the maximum recursion depth.
     *
     * A depth of zero means that objects are not allowed. A depth of one means
     * only one level of objects or arrays is allowed.
     *
     * @return int The maximum recursion depth.
     */
    public function getMaxDepth()
    {
        return $this->maxDepth;
    }

    /**
     * Sets the maximum recursion depth.
     *
     * If the depth is exceeded during decoding, an {@link DecodingnFailedException}
     * will be thrown.
     *
     * A depth of zero means that objects are not allowed. A depth of one means
     * only one level of objects or arrays is allowed.
     *
     * @param int $maxDepth The maximum recursion depth.
     *
     * @throws \InvalidArgumentException If the depth is not an integer greater
     *                                   than or equal to zero.
     */
    public function setMaxDepth($maxDepth)
    {
        if (!is_int($maxDepth)) {
            throw new \InvalidArgumentException(sprintf(
                'The maximum depth should be an integer. Got: %s',
                is_object($maxDepth) ? get_class($maxDepth) : gettype($maxDepth)
            ));
        }

        if ($maxDepth < 1) {
            throw new \InvalidArgumentException(sprintf(
                'The maximum depth should 1 or greater. Got: %s',
                $maxDepth
            ));
        }

        $this->maxDepth = $maxDepth;
    }

    /**
     * Returns the decoding of JSON objects.
     *
     * @return int One of the constants {@link JSON_OBJECT} and {@link ASSOC_ARRAY}.
     */
    public function getObjectDecoding()
    {
        return $this->objectDecoding;
    }

    /**
     * Sets the decoding of JSON objects.
     *
     * By default, JSON objects are decoded as instances of {@link \stdClass}.
     *
     * @param int $decoding One of the constants {@link JSON_OBJECT} and {@link ASSOC_ARRAY}.
     *
     * @throws \InvalidArgumentException If the passed decoding is invalid.
     */
    public function setObjectDecoding($decoding)
    {
        if (self::OBJECT !== $decoding && self::ASSOC_ARRAY !== $decoding) {
            throw new \InvalidArgumentException(sprintf(
                'Expected JsonDecoder::JSON_OBJECT or JsonDecoder::ASSOC_ARRAY. '.
                'Got: %s',
                $decoding
            ));
        }

        $this->objectDecoding = $decoding;
    }

    /**
     * Returns the decoding of big integers.
     *
     * @return int One of the constants {@link FLOAT} and {@link JSON_STRING}.
     */
    public function getBigIntDecoding()
    {
        return $this->bigIntDecoding;
    }

    /**
     * Sets the decoding of big integers.
     *
     * By default, big integers are decoded as floats.
     *
     * @param int $decoding One of the constants {@link FLOAT} and {@link JSON_STRING}.
     *
     * @throws \InvalidArgumentException If the passed decoding is invalid.
     */
    public function setBigIntDecoding($decoding)
    {
        if (self::FLOAT !== $decoding && self::STRING !== $decoding) {
            throw new \InvalidArgumentException(sprintf(
                'Expected JsonDecoder::FLOAT or JsonDecoder::JSON_STRING. '.
                'Got: %s',
                $decoding
            ));
        }

        $this->bigIntDecoding = $decoding;
    }

    private function decodeJson($json)
    {
        $assoc = self::ASSOC_ARRAY === $this->objectDecoding;

        if (PHP_VERSION_ID >= 50400 && !defined('JSON_C_VERSION')) {
            $options = self::STRING === $this->bigIntDecoding ? JSON_BIGINT_AS_STRING : 0;

            $decoded = json_decode($json, $assoc, $this->maxDepth, $options);
        } else {
            $decoded = json_decode($json, $assoc, $this->maxDepth);
        }

        // Data could not be decoded
        if (null === $decoded && 'null' !== $json) {
            $parser = new JsonParser();
            $e = $parser->lint($json);

            if ($e instanceof ParsingException) {
                throw new DecodingFailedException(sprintf(
                    'The JSON data could not be decoded: %s.',
                    $e->getMessage()
                ), 0, $e);
            }

            // $e is null if json_decode() failed, but the linter did not find
            // any problems. Happens for example when the max depth is exceeded.
            throw new DecodingFailedException(sprintf(
                'The JSON data could not be decoded: %s.',
                JsonError::getLastErrorMessage()
            ), json_last_error());
        }

        return $decoded;
    }
}
Webmozart JSON API API documentation generated by ApiGen