Skip to content

Commit

Permalink
[10.x] Avoid TypeError when using json validation rule when PHP < 8.3 (
Browse files Browse the repository at this point in the history
…#49474)

* test: validateJson should return false when value is null

Fails with Laravel Framework 10.38.2 in PHP < 8.3, introduced in #49413

* fix: validateJson should return false when value is null

Return false when $value is null.

Avoid TypeError: json_validate(): Argument #1 ($json) must be of type string, null given, when using symfony/polyfill-php83 in PHP < 8.3.

Avoid deprecation warning: json_validate(): Passing null to parameter #1 ($json) of type string is deprecated, when using PHP 8.3.

---------

Co-authored-by: Rogelio Jacinto <rogelio@elabmexico.com>
  • Loading branch information
Xint0 and Xint0-elab committed Dec 23, 2023
1 parent 6c53284 commit 8837c1f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1430,11 +1430,11 @@ public function validateMacAddress($attribute, $value)
*/
public function validateJson($attribute, $value)
{
if (is_array($value)) {
if (is_array($value) || is_null($value)) {
return false;
}

if (! is_scalar($value) && ! is_null($value) && ! method_exists($value, '__toString')) {
if (! is_scalar($value) && ! method_exists($value, '__toString')) {
return false;
}

Expand Down
9 changes: 9 additions & 0 deletions tests/Validation/ValidationValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Exceptions\MathException;
use Illuminate\Support\Stringable;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\DatabasePresenceVerifierInterface;
Expand Down Expand Up @@ -2817,6 +2818,14 @@ public function testValidateJson()
$trans = $this->getIlluminateArrayTranslator();
$v = new Validator($trans, ['foo' => ['array']], ['foo' => 'json']);
$this->assertFalse($v->passes());

$trans = $this->getIlluminateArrayTranslator();
$v = new Validator($trans, ['foo' => null], ['foo' => 'json']);
$this->assertFalse($v->passes());

$trans = $this->getIlluminateArrayTranslator();
$v = new Validator($trans, ['foo' => new Stringable('[]')], ['foo' => 'json']);
$this->assertTrue($v->passes());
}

public function testValidateBoolean()
Expand Down

0 comments on commit 8837c1f

Please sign in to comment.