Skip to content

Commit 58b5be8

Browse files
committed
JSON Serialize Stop Recursion: Implementation
1 parent 1f2a3a4 commit 58b5be8

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

src/Utils/ObjectBeanPropertyDescriptor.php

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ public function getJsonSerializeCode(): string
202202
return '';
203203
}
204204
$isIncluded = false;
205-
$format = "jsonSerialize(true)";
205+
$format = 'jsonSerialize(true)';
206206
} else {
207207
$isIncluded = $this->findAnnotation(Annotation\JsonInclude::class) !== null;
208208
/** @var Annotation\JsonFormat|null $jsonFormat */
@@ -220,20 +220,37 @@ public function getJsonSerializeCode(): string
220220
$index = $jsonKey ? $jsonKey->key : $this->namingStrategy->getJsonProperty($this);
221221
$getter = $this->getGetterName();
222222
if (!$this->isCompulsory()) {
223-
$code = "\$array['$index'] = (\$object = \$this->$getter()) ? \$object->$format : null;";
223+
$recursiveCode = "\$array['$index'] = (\$object = \$this->$getter()) ? \$object->$format : null;";
224+
$lazyCode = "\$array['$index'] = (\$object = \$this->$getter()) ? {$this->getLazySerializeCode('$object')} : null;";
224225
} else {
225-
$code = "\$array['$index'] = \$this->$getter()->$format;";
226+
$recursiveCode = "\$array['$index'] = \$this->$getter()->$format;";
227+
$lazyCode = "\$array['$index'] = {$this->getLazySerializeCode("\$this->$getter()")};";
226228
}
227-
if (!$isIncluded) {
229+
230+
if ($isIncluded) {
231+
$code = $recursiveCode;
232+
} else {
228233
$code = <<<PHP
229-
if (!\$stopRecursion) {
230-
$code
231-
};
234+
if (\$stopRecursion) {
235+
$lazyCode
236+
} else {
237+
$recursiveCode
238+
}
232239
PHP;
233240
}
234241
return $code;
235242
}
236243

244+
private function getLazySerializeCode(string $propertyAccess): string
245+
{
246+
$rows = [];
247+
foreach ($this->getForeignKey()->getUnquotedForeignColumns() as $column) {
248+
$columnGetterName = 'get' . TDBMDaoGenerator::toCamelCase($column);
249+
$rows[] = "'$column' => $propertyAccess->$columnGetterName()";
250+
}
251+
return '[' . implode(', ', $rows) . ']';
252+
}
253+
237254
/**
238255
* The code to past in the __clone method.
239256
* @return null|string

0 commit comments

Comments
 (0)