Skip to content

Commit

Permalink
Merge pull request #9525 from fluffycondor/json-throw-on-error-full-s…
Browse files Browse the repository at this point in the history
…upport

Improve json_encode/json_decode functions signatures
  • Loading branch information
orklah committed Mar 16, 2023
2 parents 70a024f + cfe8651 commit d2428ac
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
10 changes: 5 additions & 5 deletions stubs/CoreGenericFunctions.phpstub
Expand Up @@ -1460,19 +1460,19 @@ function ldap_escape(string $value, string $ignore = "", int $flags = 0) : strin
/**
* @psalm-pure
*
* @param int<1, 2147483647> $depth
* @return mixed
* @psalm-flow ($json) -> return
*/
function json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0) {}

/**
* The conditional return type below relies on the fact that JSON_THROW_ON_ERROR is
* the highest-valued of JSON constants
* @psalm-pure
*
* @return (
* $flags is 4194304
* ? non-empty-string
* : ($flags is 4194560 ? non-empty-string : non-empty-string|false)
* )
* @param int<1, 2147483647> $depth
* @return ($flags is int<4194304, 8388607> ? non-empty-string : non-empty-string|false)
*
* @psalm-flow ($value) -> return
* @psalm-ignore-falsable-return
Expand Down
36 changes: 36 additions & 0 deletions tests/CoreStubsTest.php
Expand Up @@ -2,11 +2,13 @@

namespace Psalm\Tests;

use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;

class CoreStubsTest extends TestCase
{
use ValidCodeAnalysisTestTrait;
use InvalidCodeAnalysisTestTrait;

public function providerValidCodeParse(): iterable
{
Expand Down Expand Up @@ -131,5 +133,39 @@ function foo(string $foo): string
'$a===' => 'non-empty-string',
],
];
yield 'json_encode returns a non-empty-string with JSON_THROW_ON_ERROR' => [
'code' => '<?php
$a = json_encode([], JSON_THROW_ON_ERROR | JSON_HEX_TAG);
$b = json_encode([], JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
$c = json_encode([], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$d = json_encode([], JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION);
$e = json_encode([], JSON_PRESERVE_ZERO_FRACTION);
$f = json_encode([], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
',
'assertions' => [
'$a===' => 'non-empty-string',
'$b===' => 'non-empty-string',
'$c===' => 'non-empty-string',
'$d===' => 'non-empty-string',
'$e===' => 'false|non-empty-string',
'$f===' => 'false|non-empty-string',
],
];
}

public function providerInvalidCodeParse(): iterable
{
yield 'json_decode invalid depth' => [
'code' => '<?php
json_decode("true", depth: -1);
',
'error_message' => 'InvalidArgument',
];
yield 'json_encode invalid depth' => [
'code' => '<?php
json_encode([], depth: 439877348953739);
',
'error_message' => 'InvalidArgument',
];
}
}

0 comments on commit d2428ac

Please sign in to comment.