stanislav-belichenko
@stanislav-belichenko
Backend PHP Developer

Как заставить PhpStorm воспринимать JsonException как выбрасываемое json_decode исключение?

Суть проста. Есть код, в нем есть такое:

try {
	$decoded_content = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
	...
}

Проблема в том, что PhpStorm не считает, что функция json_decode вызывает исключение JsonException, соответственно само исключение отмечено серым цветом шрифта, и подчеркнуто с таким вот текстом: Exception 'JsonException' is never thrown in the corresponding try block.

Вопрос: можно ли как-то заставить PhpStorm думать, без внесения изменений в исходные файлы его и php, естественно, что json_decode (да и любой другой участок кода, тут это просто пример) все же выбрасывает исключения? Некая phpDoc аннотация, может быть, или что-то еще.

PS: я знаю про jetbrains/phpstorm-stubs, я знаю про вкладку Analysis в настройках File | Settings | Languages & Frameworks | PHP. Стабы добавлены, расширения синхронизированы (среди них точно есть json), игнорируемых исключений нет, уровень вложенности анализа - 3, и ничего не помогло.

PPS: форкать и вносить изменения в jetbrains/phpstorm-stubs тоже не хочется.

PPPS: php указан в настройках как 7.3. Установлен локально той же версии. Указан как интерпретатор тоже он.
  • Вопрос задан
  • 369 просмотров
Решения вопроса 1
DevMan
@DevMan
или ждите пока поправят, или создайте свой стаб (работы на пару минут, ничего форкать не нужно).

создайте в проекте файл .phpstorm.meta.php и поместите в него
следующий код:
<?php

/**
 * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
 * Returns the JSON representation of a value
 *
 * @link https://php.net/manual/en/function.json-encode.php
 *
 * @param mixed $value   <p>
 *                       The <i>value</i> being encoded. Can be any type except
 *                       a resource.
 *                       </p>
 *                       <p>
 *                       All string data must be UTF-8 encoded.
 *                       </p>
 *                       <p>PHP implements a superset of
 *                       JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
 *                       only supports these values when they are nested inside an array or an object.
 *                       </p>
 * @param int   $options [optional] <p>
 *                       Bitmask consisting of <b>JSON_HEX_QUOT</b>,
 *                       <b>JSON_HEX_TAG</b>,
 *                       <b>JSON_HEX_AMP</b>,
 *                       <b>JSON_HEX_APOS</b>,
 *                       <b>JSON_NUMERIC_CHECK</b>,
 *                       <b>JSON_PRETTY_PRINT</b>,
 *                       <b>JSON_UNESCAPED_SLASHES</b>,
 *                       <b>JSON_FORCE_OBJECT</b>,
 *                       <b>JSON_UNESCAPED_UNICODE</b>.
 *                       <b>JSON_THROW_ON_ERROR</b> The behaviour of these
 *                       constants is described on
 *                       the JSON constants page.
 *                       </p>
 * @param int   $depth   [optional] <p>
 *                       Set the maximum depth. Must be greater than zero.
 *                       </p>
 *
 * @throws JsonException
 * @return string|false a JSON encoded string on success or <b>FALSE</b> on failure.
 */
function json_encode( $value, $options = 0, $depth = 512 ) {}

/**
 * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
 * Decodes a JSON string
 *
 * @link https://php.net/manual/en/function.json-decode.php
 *
 * @param string $json    <p>
 *                        The <i>json</i> string being decoded.
 *                        </p>
 *                        <p>
 *                        This function only works with UTF-8 encoded strings.
 *                        </p>
 *                        <p>PHP implements a superset of
 *                        JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
 *                        only supports these values when they are nested inside an array or an object.
 *                        </p>
 * @param bool   $assoc   [optional] <p>
 *                        When <b>TRUE</b>, returned objects will be converted into
 *                        associative arrays.
 *                        </p>
 * @param int    $depth   [optional] <p>
 *                        User specified recursion depth.
 *                        </p>
 * @param int    $options [optional] <p>
 *                        Bitmask of JSON decode options. Currently only
 *                        <b>JSON_BIGINT_AS_STRING</b>
 *                        is supported (default is to cast large integers as floats)
 *
 * <b>JSON_THROW_ON_ERROR</b> when passed this flag, the error behaviour of these functions is changed. The global error state is left untouched, and if an error occurs that would otherwise set it, these functions instead throw a JsonException
 * </p>
 *
 * @throws JsonException
 * @return mixed the value encoded in <i>json</i> in appropriate
 * PHP type. Values true, false and
 * null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b>
 * and <b>NULL</b> respectively. <b>NULL</b> is returned if the
 * <i>json</i> cannot be decoded or if the encoded
 * data is deeper than the recursion limit.
 */
function json_decode( $json, $assoc = false, $depth = 512, $options = 0 ) {}
результат:
5dc3166be08d0938887803.png
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы