Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rfc 114 #116

Open
wants to merge 11 commits into
base: 4.15.x
Choose a base branch
from
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@
[![Psalm coverage](https://shepherd.dev/github/laminas/laminas-hydrator/coverage.svg?)](https://shepherd.dev/github/laminas/laminas-hydrator)

> ## 🇷🇺 Русским гражданам
>
>
> Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.
>
>
> У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.
>
>
> Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"
>
>
> ## 🇺🇸 To Citizens of Russia
>
>
> We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.
>
>
> One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.
>
>
> You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

`Laminas\Hydrator` provides utilities for mapping arrays to objects, and vice
Expand Down
49 changes: 25 additions & 24 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 14 additions & 11 deletions src/ReflectionHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ class ReflectionHydrator extends AbstractHydrator
*
* {@inheritDoc}
*/
public function extract(object $object): array
public function extract(object $object, bool $includeParentProperties = false): array
{
$result = [];
foreach (self::getReflProperties($object) as $property) {
foreach (self::getReflProperties($object, $includeParentProperties) as $property) {
$propertyName = $this->extractName($property->getName(), $object);
if (! $this->getCompositeFilter()->filter($propertyName)) {
continue;
Expand All @@ -42,9 +42,9 @@ public function extract(object $object): array
*
* {@inheritDoc}
*/
public function hydrate(array $data, object $object)
public function hydrate(array $data, object $object, bool $includeParentProperties = false)
{
$reflProperties = self::getReflProperties($object);
$reflProperties = self::getReflProperties($object, $includeParentProperties);
foreach ($data as $key => $value) {
$name = $this->hydrateName($key, $data);
if (isset($reflProperties[$name])) {
Expand All @@ -60,21 +60,24 @@ public function hydrate(array $data, object $object)
*
* @return ReflectionProperty[]
*/
protected static function getReflProperties(object $input): array
protected static function getReflProperties(object $input, bool $includeParentProperties): array
{
$class = $input::class;
$reflClass = new ReflectionClass($input);
$class = $reflClass->getName();

if (isset(static::$reflProperties[$class])) {
return static::$reflProperties[$class];
}

static::$reflProperties[$class] = [];
$reflClass = new ReflectionClass($class);
$reflProperties = $reflClass->getProperties();

foreach ($reflProperties as $property) {
static::$reflProperties[$class][$property->getName()] = $property;
}
do {
foreach ($reflClass->getProperties() as $property) {
/** @psalm-suppress UnusedMethodCall - Bizarre, this is a void return!!! */
$property->setAccessible(true);
static::$reflProperties[$class][$property->getName()] = $property;
}
} while ($includeParentProperties === true && ($reflClass = $reflClass->getParentClass()) !== false);

return static::$reflProperties[$class];
}
Expand Down
52 changes: 48 additions & 4 deletions test/ReflectionHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
namespace LaminasTest\Hydrator;

use Laminas\Hydrator\ReflectionHydrator;
use LaminasTest\Hydrator\TestAsset\ReflectionHydratorTestData;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use ReflectionProperty;
use stdClass;
use TypeError;

use function get_parent_class;

#[CoversClass(ReflectionHydrator::class)]
class ReflectionHydratorTest extends TestCase
{
Expand Down Expand Up @@ -61,10 +64,7 @@ public function testHydrateRaisesExceptionForInvalidArgument(): void

public function testCanExtractFromAnonymousClass(): void
{
$instance = new class {
private string $foo = 'bar';
private string $bar = 'baz';
};
$instance = new ReflectionHydratorTestData();
$this->assertSame([
'foo' => 'bar',
'bar' => 'baz',
Expand All @@ -83,4 +83,48 @@ public function testCanHydrateAnonymousObject(): void
$r = new ReflectionProperty($hydrated, 'foo');
$this->assertSame('bar', $r->getValue($hydrated));
}

public function testCanExtractFromExtendedClass(): void
{
$instance = new class extends ReflectionHydratorTestData {
};
$this->assertSame([
'foo' => 'bar',
'bar' => 'baz',
], $this->hydrator->extract($instance, true));
}

public function testFailToExtractFromExtendedClass(): void
{
$instance = new class extends ReflectionHydratorTestData {
};
$this->assertNotSame([
'foo' => 'bar',
'bar' => 'baz',
], $this->hydrator->extract($instance, false));
}

public function testCanHydrateExtendedClass(): void
{
$instance = new class extends ReflectionHydratorTestData {
};

$hydrated = $this->hydrator->hydrate(['foo' => 'foo-foo'], $instance, true);

$this->assertSame($instance, $hydrated);
$r = new ReflectionProperty(get_parent_class($hydrated), 'foo');
$this->assertSame('foo-foo', $r->getValue($hydrated));
}

public function testFailToHydrateExtendedClass(): void
{
$instance = new class extends ReflectionHydratorTestData {
};

$hydrated = $this->hydrator->hydrate(['foo' => 'foo-foo'], $instance, false);

$this->assertSame($instance, $hydrated);
$r = new ReflectionProperty(get_parent_class($hydrated), 'foo');
$this->assertSame('bar', $r->getValue($hydrated));
}
}
11 changes: 11 additions & 0 deletions test/TestAsset/ReflectionHydratorTestData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace LaminasTest\Hydrator\TestAsset;

class ReflectionHydratorTestData
{
private string $foo = 'bar';
private string $bar = 'baz';
}