Example #1
0
File: Json.php Project: youhey/Json
 /**
  * JSON形式の文字列をデコード
  *
  * <p>UTF-8のみBOMを無視するよう対応<br>
  * PHPのバージョンが5.4.0以上であれば以下の動作に対応</p>
  * <dl>
  * <dt>JSON_BIGINT_AS_STRING</dt>
  * <dd>大きな整数値を文字列としてエンコード(公式ドキュメントまま)</dd>
  * </dl>
  *
  * @param string $json デコードするJSON形式の文字列
  * @param bool $assoc オブジェクトを連想配列で返すか?
  *
  * @return mixed デコードした結果
  *
  * @throws \Json\Exception\Decoding JSONデータが不正
  * @throws \Json\Exception\SyntaxError JSONデータが不正
  *
  * @see json_decode()
  */
 public static function parse($json, $assoc = false)
 {
     // Strip off BOM (UTF-8)
     if (strpos($json, "") === 0) {
         $json = substr($json, 3);
     }
     // 性能に影響のない範囲で単純なデコードのみ自前対応
     if ($json === '') {
         return null;
     }
     if ($json === 'null') {
         return null;
     }
     if ($json === 'true') {
         return true;
     }
     if ($json === 'false') {
         return false;
     }
     if ($json === '{}') {
         if ($assoc) {
             return array();
         }
         return new \stdClass();
     }
     if ($json === '[]') {
         return array();
     }
     if ($json === '""') {
         return '';
     }
     if (static::isSupportedOptions()) {
         $decoded = @json_decode($json, $assoc, self::$max_depth, self::$decode_option);
     } else {
         $decoded = @json_decode($json, $assoc);
     }
     if (!is_null($decoded)) {
         return $decoded;
     }
     $last_error = new LastError();
     if (!$last_error->exists()) {
         return $decoded;
     }
     if ($last_error->getCode() === JSON_ERROR_DEPTH) {
         throw \Json\Exception\Decoding::errorDepth();
     }
     throw new \Json\Exception\SyntaxError($last_error);
 }