Skip to content

Commit afda5cd

Browse files
authored
Merge pull request #17 from karriereat/bugfix/transform-raw-private-properties
Transform private properties in transformRaw
2 parents e23c8e7 + 31fcab8 commit afda5cd

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

src/JsonDecoder.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Karriere\JsonDecoder;
44

5+
use Karriere\JsonDecoder\Bindings\RawBinding;
6+
57
class JsonDecoder
68
{
79
/**
@@ -97,12 +99,12 @@ protected function transformRaw($jsonArrayData, $instance)
9799
return null;
98100
}
99101

100-
foreach ($jsonArrayData as $key => $value) {
101-
if (property_exists($instance, $key)) {
102-
$instance->{$key} = $value;
103-
}
102+
$classBindings = new ClassBindings($this);
103+
104+
foreach (array_keys($jsonArrayData) as $property) {
105+
$classBindings->register(new RawBinding($property));
104106
}
105107

106-
return $instance;
108+
return $classBindings->decode($jsonArrayData, $instance);
107109
}
108110
}

tests/specs/JsonDecoderSpec.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,18 @@ public function it_should_be_able_to_transform_an_array_of_objects()
9191
$response[1]->id->shouldBe(2);
9292
$response[1]->name->shouldBe('Jane');
9393
}
94+
95+
public function it_should_be_able_to_transform_raw_with_private_properties()
96+
{
97+
$this->beConstructedWith(true, false);
98+
$jsonString = '{"id": 1, "name": "John Doe"}';
99+
100+
$response = $this->decode($jsonString, SampleWithPrivateProperties::class);
101+
102+
$response->shouldHaveType(SampleWithPrivateProperties::class);
103+
$response->getId()->shouldBe(1);
104+
$response->getName()->shouldReturn('John Doe');
105+
}
94106
}
95107

96108
class JsonDecoderSample
@@ -99,6 +111,22 @@ class JsonDecoderSample
99111
public $name;
100112
}
101113

114+
class SampleWithPrivateProperties
115+
{
116+
private $id;
117+
private $name;
118+
119+
public function getId()
120+
{
121+
return $this->id;
122+
}
123+
124+
public function getName()
125+
{
126+
return $this->name;
127+
}
128+
}
129+
102130
class SampleTransformer implements Transformer
103131
{
104132
public function register(ClassBindings $classBindings)

0 commit comments

Comments
 (0)