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

Add support for object without JsonSerializable #505

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/Pecee/Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,23 @@ public function cache(string $eTag, int $lastModifiedTime = 2592000): self
*/
public function json($value, ?int $options = null, int $dept = 512): void
{
if (($value instanceof \JsonSerializable) === false && \is_array($value) === false) {
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
if(is_object($value)){
if(!$value instanceof \JsonSerializable){
$object_vars = array();
$class = new \ReflectionClass($value);
foreach($class->getProperties() as $property){
if($property->isStatic())
continue;
$property->setAccessible(true);
$object_vars[$property->getName()] = $property->getValue($value);
}
$value = $object_vars;
if(empty($object_vars)){
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface or object with variables.');
}
}
}else if(is_array($value) === false){
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface or object with variables.');
}

$this->header('Content-Type: application/json; charset=utf-8');
Expand Down