Skip to content

JsonEncodingApiUsage ​

info on by default quick-fix

Group: Type compatibility · PhpStorm name: JsonEncodingApiUsageInspection

json_decode() without its second argument silently returns stdClass objects, which readers often confuse with arrays; and both json_decode() and json_encode() report failures only through json_last_error() unless the JSON_THROW_ON_ERROR flag (PHP 7.3+) is passed. This rule asks for an explicit decoding target and for exception-based error handling.

Example ​

Configuration (a): T only, decode as array.

php
<?php
namespace Feed;

function load(string $body, string $alt) {
    $a = json_decode($body);
    $b = \json_decode(trim($alt));
    $c = json_decode($body, false);
    $d = json_decode($body, associative: true);
    $e = json_decode();
    return [$a, $b, $c, $d, $e];
}
php
<?php
namespace Feed;

function load(string $body, string $alt) {
    $a = json_decode($body, true);
    $b = \json_decode(trim($alt), true);
    $c = json_decode($body, false);
    $d = json_decode($body, associative: true);
    $e = json_decode();
    return [$a, $b, $c, $d, $e];
}

Reported:

  • line 5: Pass the second argument to state whether JSON decodes to arrays or objects.
  • line 6: Pass the second argument to state whether JSON decodes to arrays or objects.

Options ​

OptionTypeDefaultEffect
HARDEN_DECODING_RESULT_TYPEbooltrueEnables kind T (D1). Also affects <assoc> in F2.
DECODE_AS_ARRAYboolfalseFixes insert true (decode to arrays) instead of false.
DECODE_AS_OBJECTbooltrueRadio-button companion of DECODE_AS_ARRAY; has no effect on detection or fixes by itself.
HARDEN_ERRORS_HANDLINGbooltrueEnables kind E (D2–D5).

Upstream fixture configurations: (a) T only — HARDEN_DECODING_RESULT_TYPE on, DECODE_AS_ARRAY on, HARDEN_ERRORS_HANDLING off, default PHP level; (b) E only — HARDEN_DECODING_RESULT_TYPE off, HARDEN_ERRORS_HANDLING on, PHP 7.3.

Configure ​

In custos.json:

json
{
  "rules": {
    "JsonEncodingApiUsage": {
      "enabled": false,
      "options": {
        "HARDEN_DECODING_RESULT_TYPE": true,
        "DECODE_AS_ARRAY": false,
        "DECODE_AS_OBJECT": true,
        "HARDEN_ERRORS_HANDLING": true
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore JsonEncodingApiUsage

/**
 * @noinspection JsonEncodingApiUsageInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.