Check if property is initialized before getting its value

This commit also removed the use of "setAccessible", since it's not
neccessary after PHP 8.1.

Co-authored-by: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
Alan Taylor 2023-02-17 23:58:23 +09:00 committed by Henrique Moody
parent 6e3ed94076
commit 8d7d783698
No known key found for this signature in database
GPG key ID: 221E9281655813A6
4 changed files with 31 additions and 2 deletions

View file

@ -17,6 +17,7 @@ Fixes:
- `KeySet` now reports which extra keys are causing the rule to fail.
- Ensure empty strings are never a valid currency code
- Do not hide messages on EachException
- Dot not throw exception when validating an uninitialized property
Changes:

View file

@ -17,7 +17,7 @@ use function is_object;
use function property_exists;
/**
* Validates an object attribute, event private ones.
* Validates an object attribute, even private ones.
*
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
@ -38,7 +38,9 @@ final class Attribute extends AbstractRelated
public function getReferenceValue($input)
{
$propertyMirror = new ReflectionProperty($input, (string) $this->getReference());
$propertyMirror->setAccessible(true);
if ($propertyMirror->isInitialized($input) === false) {
return null;
}
return $propertyMirror->getValue($input);
}

View file

@ -0,0 +1,17 @@
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Test\Stubs;
final class WithUninitialized
{
public string $initialized = 'foo';
public string $uninitialized;
}

View file

@ -11,6 +11,7 @@ namespace Respect\Validation\Rules;
use Respect\Validation\Test\RuleTestCase;
use Respect\Validation\Test\Stubs\WithProperties;
use Respect\Validation\Test\Stubs\WithUninitialized;
/**
* @group rule
@ -47,6 +48,10 @@ final class AttributeTest extends RuleTestCase
new Attribute('public', new AlwaysValid()),
new WithProperties(),
],
'attribute is present but uninitialized' => [
new Attribute('uninitialized'),
new WithUninitialized(),
],
'non mandatory attribute is not present' => [
new Attribute('nonexistent', null, false),
new WithProperties(),
@ -55,6 +60,10 @@ final class AttributeTest extends RuleTestCase
new Attribute('nonexistent', new AlwaysValid(), false),
new WithProperties(),
],
'attribute is present but uninitialized with extra validator' => [
new Attribute('uninitialized', new AlwaysValid()),
new WithUninitialized(),
],
];
}