Skip to content

Commit 71e9c7e

Browse files
authored
Merge pull request #59 from pwsdotru/issue-54
Fix issue for call toJson on a non-object
2 parents d6f8383 + 178dda6 commit 71e9c7e

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

src/BaseType.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,16 @@ public function toJson($inner = false)
6868
foreach (static::$map as $key => $item) {
6969
$property = lcfirst(self::toCamelCase($key));
7070
if (!is_null($this->$property)) {
71-
$output[$key] = $item === true ? $this->$property : $this->$property->toJson(true);
71+
if (is_array($this->$property)) {
72+
$output[$key] = array_map(
73+
function ($v) {
74+
return is_object($v) ? $v->toJson(true) : $v;
75+
},
76+
$this->$property
77+
);
78+
} else {
79+
$output[$key] = $item === true ? $this->$property : $this->$property->toJson(true);
80+
}
7281
}
7382
}
7483

tests/MessageTest.php

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,4 +797,57 @@ public function testGetMigrateFromChatId()
797797

798798
$this->assertEquals(3, $item->getMigrateFromChatId());
799799
}
800+
801+
public function testToJson1()
802+
{
803+
$data = array(
804+
'message_id' => 1,
805+
'from' => array(
806+
'first_name' => 'Ilya',
807+
'last_name' => 'Gusev',
808+
'id' => 123456,
809+
'username' => 'iGusev'
810+
),
811+
'date' => 2,
812+
'chat' => array(
813+
'id' => 1,
814+
'type' => 'group',
815+
'title' => 'test chat'
816+
),
817+
'migrate_from_chat_id' => 3
818+
);
819+
820+
$item = Message::fromResponse($data);
821+
$this->assertJson(json_encode($data), $item->toJson());
822+
}
823+
824+
public function testToJson2()
825+
{
826+
$data = array(
827+
'message_id' => 1,
828+
'from' => array(
829+
'first_name' => 'Ilya',
830+
'last_name' => 'Gusev',
831+
'id' => 123456,
832+
'username' => 'iGusev'
833+
),
834+
'date' => 2,
835+
'chat' => array(
836+
'id' => 1,
837+
'type' => 'group',
838+
'title' => 'test chat'
839+
),
840+
'entities' => array(
841+
array(
842+
"type" => "bot_command",
843+
"offset" => 0,
844+
"length" => 7,
845+
)
846+
),
847+
'migrate_from_chat_id' => 3
848+
);
849+
850+
$item = Message::fromResponse($data);
851+
$this->assertJson(json_encode($data), $item->toJson());
852+
}
800853
}

0 commit comments

Comments
 (0)