Skip to content

Commit

Permalink
added support to search first for getter to get value
Browse files Browse the repository at this point in the history
  • Loading branch information
TeleMessage committed Oct 16, 2016
1 parent f75509e commit 2c71b19
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ build/*
composer.lock
phpjsonable.iml
.idea/*
vendor/*
vendor/*
index.php
Binary file modified grinfeld_phpjsonable.phar
Binary file not shown.
15 changes: 13 additions & 2 deletions src/transformers/BeanTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,19 @@ public function transform($obj, OutputStream $output, Configuration $conf) {
$clazzName = $conf->getString(Configuration::CLASS_PROPERTY, Configuration::DEFAULT_CLASS_PROPERTY_VALUE);
$clazzStrategy = $conf->getString(Configuration::CLASS_TYPE_PROPERTY, LanguageStrategyFactory::LANG_PHP);
foreach($props as $prop) {
$prop->setAccessible(true);
$val = $prop->getValue($obj);
// check getter
$val = null;
try {
$refMethod = new \ReflectionMethod($clazz, "get" . ucfirst($prop->getName()));
if ($refMethod->isPublic())
$val = $refMethod->invoke($obj);
} catch (\Exception $e) {
echo $e->getMessage();
}
if ($val == null) {
$prop->setAccessible(true);
$val = $prop->getValue($obj);
}
if ($excludeNull === false || ($val !== null || $val !== "")) {
if ($prop->getName() != $clazzName) {
if ($i != 0)
Expand Down
4 changes: 4 additions & 0 deletions src/transformers/MapTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ class MapTransformer implements Transformer {
public function match($obj) {
if (!is_array($obj))
return false;

if (is_object($obj))
return false;

return true;
}

Expand Down
14 changes: 13 additions & 1 deletion test/parsers/json/WriterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,5 +127,17 @@ public function testParse() {
Json::encode($pair, $output, (new Configuration())->push(Configuration::INCLUDE_CLASS_NAME_PROPERTY, "true")->push(Configuration::EXCLUDE_NULL_PROPERTY, "false"));
$this->assertEquals($expected, $output->toString(), "Should be $expected");

$output = new StringOutputStream();
Json::encode(new SimpleBean(), $output, (new Configuration())->push(Configuration::INCLUDE_CLASS_NAME_PROPERTY, "false")->push(Configuration::EXCLUDE_NULL_PROPERTY, "false"));
$this->assertEquals("{\"val\":\"123\"}", $output->toString(), "Should be 123");
}
}
}

class SimpleBean {
protected $val = "1";

/**
* @return mixed
*/
public function getVal() { return "123"; }
}

0 comments on commit 2c71b19

Please sign in to comment.