Skip to content

Commit 3ea4946

Browse files
authored
fix calling __toString() on null values (acseo#109)
1 parent 3db5dc1 commit 3ea4946

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/Transformer/DoctrineToTypesenseTransformer.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ public function castValue(string $entityClass, string $propertyName, $value)
8989
$originalType = $collectionFieldsDefinitions[$key]['type'];
9090
$castedType = $this->castType($originalType);
9191

92+
$isOptional = $collectionFieldsDefinitions[$key]['optional'] ?? false;
93+
9294
switch ($originalType.$castedType) {
9395
case self::TYPE_DATETIME.self::TYPE_INT_64:
9496
if ($value instanceof \DateTimeInterface) {
@@ -97,10 +99,16 @@ public function castValue(string $entityClass, string $propertyName, $value)
9799

98100
return null;
99101
case self::TYPE_OBJECT.self::TYPE_STRING:
102+
if ($isOptional == true && $value == null) {
103+
return null;
104+
}
100105
return $value->__toString();
101106
case self::TYPE_COLLECTION.self::TYPE_ARRAY_STRING:
102107
return array_values(
103-
$value->map(function ($v) {
108+
$value->map(function ($v) use($isOptional) {
109+
if ($isOptional == true && $v == null) {
110+
return null;
111+
}
104112
return $v->__toString();
105113
})->toArray()
106114
);

tests/Unit/Transformer/DoctrineToTypesenseTransformerTest.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,13 @@ public function bookData()
3535
{
3636
return [
3737
[
38-
new Book(1, 'test', new Author('Nicolas Potier', 'France'), new \Datetime('01/01/1984 00:00:00')),
38+
new Book(1, 'test', null, new \Datetime('01/01/1984 00:00:00')),
3939
[
4040
"id" => "1",
4141
"sortable_id" => 1,
4242
"title" => "test",
43-
"author" => "Nicolas Potier",
44-
"author_country" => "France",
43+
"author" => null,
44+
"author_country" => null,
4545
"published_at" => 441763200,
4646
"active" => false,
4747
"cover_image_url" => "http://fake.image/1"
@@ -238,6 +238,7 @@ private function getCollectionDefinitions($entityClass)
238238
'name' => 'author',
239239
'type' => 'object',
240240
'entity_attribute' => 'author',
241+
'optional' => true
241242
],
242243
'michel' => [
243244
'name' => 'author_country',

0 commit comments

Comments
 (0)