Skip to content

Commit 35f513d

Browse files
bpolaszeknorkunas
authored andcommitted
fix(serializer): properly normalize DateTimeInterface objects
1 parent fbda397 commit 35f513d

File tree

4 files changed

+30
-6
lines changed

4 files changed

+30
-6
lines changed

config/services.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,9 @@
6666
<argument type="service" id="meilisearch.client" />
6767
<tag name="console.command" />
6868
</service>
69+
70+
<service id="Meilisearch\Bundle\Services\UnixTimestampNormalizer">
71+
<tag name="serializer.normalizer" />
72+
</service>
6973
</services>
7074
</container>

src/SearchableEntity.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ public function getIndexUid(): string
6161
public function getSearchableArray(): array
6262
{
6363
$context = [
64+
'meilisearch' => true,
6465
'fieldsMapping' => $this->entityMetadata->fieldMappings,
6566
];
6667

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Meilisearch\Bundle\Services;
6+
7+
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
8+
9+
final class UnixTimestampNormalizer implements NormalizerInterface
10+
{
11+
/**
12+
* @param \DateTimeInterface $object
13+
*/
14+
public function normalize(mixed $object, string $format = null, array $context = []): int
15+
{
16+
return (int) $object->format('U');
17+
}
18+
19+
public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
20+
{
21+
return $data instanceof \DateTimeInterface && true === ($context['meilisearch'] ?? null);
22+
}
23+
}

tests/Unit/SerializationTest.php

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,6 @@ class SerializationTest extends KernelTestCase
1818
public function testSimpleEntityToSearchableArray(): void
1919
{
2020
$datetime = new \DateTime();
21-
$dateNormalizer = static::getContainer()->get('serializer.normalizer.datetime');
22-
// This way we can test that DateTime's are serialized with DateTimeNormalizer
23-
// And not the default ObjectNormalizer
24-
$serializedDateTime = $dateNormalizer->normalize($datetime, Searchable::NORMALIZATION_FORMAT);
2521

2622
$post = new Post(
2723
[
@@ -51,12 +47,12 @@ public function testSimpleEntityToSearchableArray(): void
5147
'id' => 12,
5248
'title' => 'a simple post',
5349
'content' => 'some text',
54-
'publishedAt' => $serializedDateTime,
50+
'publishedAt' => (int) $datetime->format('U'),
5551
'comments' => [
5652
[
5753
'id' => null,
5854
'content' => 'a great comment',
59-
'publishedAt' => $serializedDateTime,
55+
'publishedAt' => (int) $datetime->format('U'),
6056
],
6157
],
6258
];

0 commit comments

Comments
 (0)