Skip to content

Commit 2c71b19

Browse files
author
TeleMessage
committed
added support to search first for getter to get value
1 parent f75509e commit 2c71b19

File tree

5 files changed

+32
-4
lines changed

5 files changed

+32
-4
lines changed

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ build/*
22
composer.lock
33
phpjsonable.iml
44
.idea/*
5-
vendor/*
5+
vendor/*
6+
index.php

grinfeld_phpjsonable.phar

1.02 KB
Binary file not shown.

src/transformers/BeanTransformer.php

+13-2
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,19 @@ public function transform($obj, OutputStream $output, Configuration $conf) {
4040
$clazzName = $conf->getString(Configuration::CLASS_PROPERTY, Configuration::DEFAULT_CLASS_PROPERTY_VALUE);
4141
$clazzStrategy = $conf->getString(Configuration::CLASS_TYPE_PROPERTY, LanguageStrategyFactory::LANG_PHP);
4242
foreach($props as $prop) {
43-
$prop->setAccessible(true);
44-
$val = $prop->getValue($obj);
43+
// check getter
44+
$val = null;
45+
try {
46+
$refMethod = new \ReflectionMethod($clazz, "get" . ucfirst($prop->getName()));
47+
if ($refMethod->isPublic())
48+
$val = $refMethod->invoke($obj);
49+
} catch (\Exception $e) {
50+
echo $e->getMessage();
51+
}
52+
if ($val == null) {
53+
$prop->setAccessible(true);
54+
$val = $prop->getValue($obj);
55+
}
4556
if ($excludeNull === false || ($val !== null || $val !== "")) {
4657
if ($prop->getName() != $clazzName) {
4758
if ($i != 0)

src/transformers/MapTransformer.php

+4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ class MapTransformer implements Transformer {
2020
public function match($obj) {
2121
if (!is_array($obj))
2222
return false;
23+
24+
if (is_object($obj))
25+
return false;
26+
2327
return true;
2428
}
2529

test/parsers/json/WriterTest.php

+13-1
Original file line numberDiff line numberDiff line change
@@ -127,5 +127,17 @@ public function testParse() {
127127
Json::encode($pair, $output, (new Configuration())->push(Configuration::INCLUDE_CLASS_NAME_PROPERTY, "true")->push(Configuration::EXCLUDE_NULL_PROPERTY, "false"));
128128
$this->assertEquals($expected, $output->toString(), "Should be $expected");
129129

130+
$output = new StringOutputStream();
131+
Json::encode(new SimpleBean(), $output, (new Configuration())->push(Configuration::INCLUDE_CLASS_NAME_PROPERTY, "false")->push(Configuration::EXCLUDE_NULL_PROPERTY, "false"));
132+
$this->assertEquals("{\"val\":\"123\"}", $output->toString(), "Should be 123");
130133
}
131-
}
134+
}
135+
136+
class SimpleBean {
137+
protected $val = "1";
138+
139+
/**
140+
* @return mixed
141+
*/
142+
public function getVal() { return "123"; }
143+
}

0 commit comments

Comments
 (0)