Skip to content

Commit 261197c

Browse files
committed
Allow to configure custom serializer groups
1 parent e176918 commit 261197c

File tree

11 files changed

+203
-16
lines changed

11 files changed

+203
-16
lines changed

composer.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@
6565
"scripts": {
6666
"phpmd": "./vendor/bin/phpmd src text phpmd.xml",
6767
"phpstan": "./vendor/bin/phpstan --memory-limit=1G --ansi",
68-
"test:unit": "./vendor/bin/phpunit --colors=always --verbose",
69-
"test:unit:coverage": "XDEBUG_MODE=coverage ./vendor/bin/phpunit --colors=always --coverage-html=tests/coverage",
68+
"test:unit": "./vendor/bin/simple-phpunit --colors=always --verbose",
69+
"test:unit:coverage": "XDEBUG_MODE=coverage ./vendor/bin/simple-phpunit --colors=always --coverage-html=tests/coverage",
7070
"lint:check": "./vendor/bin/php-cs-fixer fix -v --using-cache=no --dry-run",
7171
"lint:fix": "./vendor/bin/php-cs-fixer fix -v --using-cache=no"
7272
}

phpunit.xml.dist

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" bootstrap="vendor/autoload.php"
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" bootstrap="tests/bootstrap.php"
33
convertDeprecationsToExceptions="false"
4-
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd">
4+
xsi:noNamespaceSchemaLocation="vendor/bin/.phpunit/phpunit/phpunit.xsd">
55
<coverage>
66
<include>
77
<directory>src/</directory>

src/DependencyInjection/Configuration.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Meilisearch\Bundle\DependencyInjection;
66

7+
use Meilisearch\Bundle\Searchable;
78
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
89
use Symfony\Component\Config\Definition\ConfigurationInterface;
910

@@ -49,6 +50,11 @@ public function getConfigTreeBuilder(): TreeBuilder
4950
->info('When set to true, it will call normalize method with an extra groups parameter "groups" => [Searchable::NORMALIZATION_GROUP]')
5051
->defaultFalse()
5152
->end()
53+
->arrayNode('serializer_groups')
54+
->info('When setting a different value, normalization will be called with it instead of "Searchable::NORMALIZATION_GROUP".')
55+
->defaultValue([Searchable::NORMALIZATION_GROUP])
56+
->scalarPrototype()->end()
57+
->end()
5258
->scalarNode('index_if')
5359
->info('Property accessor path (like method or property name) used to decide if an entry should be indexed.')
5460
->defaultNull()

src/SearchableEntity.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ final class SearchableEntity
2525

2626
private ?NormalizerInterface $normalizer;
2727

28-
private bool $useSerializerGroups;
28+
/**
29+
* @var list<string>
30+
*/
31+
private array $normalizationGroups;
2932

3033
/** @var int|string */
3134
private $id;
@@ -47,7 +50,7 @@ public function __construct(
4750
$this->entity = $entity;
4851
$this->entityMetadata = $entityMetadata;
4952
$this->normalizer = $normalizer;
50-
$this->useSerializerGroups = isset($extra['useSerializerGroup']) && $extra['useSerializerGroup'];
53+
$this->normalizationGroups = $extra['normalizationGroups'] ?? [];
5154

5255
$this->setId();
5356
}
@@ -66,8 +69,8 @@ public function getSearchableArray(): array
6669
'fieldsMapping' => $this->entityMetadata->fieldMappings,
6770
];
6871

69-
if ($this->useSerializerGroups) {
70-
$context['groups'] = [Searchable::NORMALIZATION_GROUP];
72+
if (count($this->normalizationGroups) > 0) {
73+
$context['groups'] = $this->normalizationGroups;
7174
}
7275

7376
if ($this->entity instanceof NormalizableInterface && null !== $this->normalizer) {

src/Services/MeilisearchService.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ private function setClassToSerializerGroup(): void
257257

258258
/** @var array $indexDetails */
259259
foreach ($this->configuration->get('indices') as $indexDetails) {
260-
$mapping[$indexDetails['class']] = $indexDetails['enable_serializer_groups'];
260+
$mapping[$indexDetails['class']] = $indexDetails['enable_serializer_groups'] ? $indexDetails['serializer_groups'] : [];
261261
}
262262
$this->classToSerializerGroup = $mapping;
263263
}
@@ -320,7 +320,7 @@ private function makeSearchServiceResponseFrom(
320320
$entity,
321321
$objectManager->getClassMetadata($entityClassName),
322322
$this->normalizer,
323-
['useSerializerGroup' => $this->canUseSerializerGroup($entityClassName)]
323+
['normalizationGroups' => $this->getNormalizationGroups($entityClassName)]
324324
);
325325
}
326326

@@ -330,7 +330,12 @@ private function makeSearchServiceResponseFrom(
330330
return $batch;
331331
}
332332

333-
private function canUseSerializerGroup(string $className): bool
333+
/**
334+
* @param class-string $className
335+
*
336+
* @return list<string>
337+
*/
338+
private function getNormalizationGroups(string $className): array
334339
{
335340
return $this->classToSerializerGroup[$className];
336341
}

tests/Entity/DummyCustomGroups.php

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Meilisearch\Bundle\Tests\Entity;
6+
7+
use Doctrine\DBAL\Types\Types;
8+
use Doctrine\ORM\Mapping as ORM;
9+
use Symfony\Component\Serializer\Annotation\Groups;
10+
11+
/**
12+
* @ORM\Entity
13+
*/
14+
#[ORM\Entity]
15+
class DummyCustomGroups
16+
{
17+
/**
18+
* @ORM\Id
19+
*
20+
* @ORM\Column(type="integer")
21+
*
22+
* @Groups("public")
23+
*/
24+
#[ORM\Id]
25+
#[ORM\Column(type: Types::INTEGER)]
26+
#[Groups('public')]
27+
private int $id;
28+
29+
/**
30+
* @ORM\Column(type="string")
31+
*
32+
* @Groups("public")
33+
*/
34+
#[ORM\Column(type: Types::STRING)]
35+
#[Groups('public')]
36+
private string $name;
37+
38+
/**
39+
* @ORM\Column(type="datetime_immutable")
40+
*
41+
* @Groups("private")
42+
*/
43+
#[ORM\Column(type: Types::DATETIME_IMMUTABLE)]
44+
#[Groups('private')]
45+
private \DateTimeImmutable $createdAt;
46+
47+
public function __construct(int $id, string $name, \DateTimeImmutable $createdAt)
48+
{
49+
$this->id = $id;
50+
$this->name = $name;
51+
$this->createdAt = $createdAt;
52+
}
53+
54+
public function getId(): int
55+
{
56+
return $this->id;
57+
}
58+
59+
public function getName(): string
60+
{
61+
return $this->name;
62+
}
63+
64+
public function getCreatedAt(): \DateTimeImmutable
65+
{
66+
return $this->createdAt;
67+
}
68+
}

tests/Integration/CommandsTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Meilisearch\Bundle\Tests\Integration;
66

77
use Meilisearch\Bundle\Tests\BaseKernelTestCase;
8+
use Meilisearch\Bundle\Tests\Entity\DummyCustomGroups;
89
use Meilisearch\Bundle\Tests\Entity\SelfNormalizable;
910
use Meilisearch\Client;
1011
use Meilisearch\Endpoints\Indexes;
@@ -87,6 +88,7 @@ public function testSearchImportAndClearAndDeleteWithoutIndices(): void
8788
Importing for index Meilisearch\Bundle\Tests\Entity\Page
8889
Indexed a batch of 6 / 6 Meilisearch\Bundle\Tests\Entity\Page entities into sf_phpunit__pages index (6 indexed since start)
8990
Importing for index Meilisearch\Bundle\Tests\Entity\SelfNormalizable
91+
Importing for index Meilisearch\Bundle\Tests\Entity\DummyCustomGroups
9092
Importing for index Meilisearch\Bundle\Tests\Entity\Post
9193
Indexed a batch of 6 / 6 Meilisearch\Bundle\Tests\Entity\Post entities into sf_phpunit__posts index (6 indexed since start)
9294
Indexed a batch of 6 / 6 Meilisearch\Bundle\Tests\Entity\Post entities into sf_phpunit__aggregated index (6 indexed since start)
@@ -111,6 +113,7 @@ public function testSearchImportAndClearAndDeleteWithoutIndices(): void
111113
Cleared sf_phpunit__tags index of Meilisearch\Bundle\Tests\Entity\Link
112114
Cleared sf_phpunit__pages index of Meilisearch\Bundle\Tests\Entity\Page
113115
Cleared sf_phpunit__self_normalizable index of Meilisearch\Bundle\Tests\Entity\SelfNormalizable
116+
Cleared sf_phpunit__dummy_custom_groups index of Meilisearch\Bundle\Tests\Entity\DummyCustomGroups
114117
Done!
115118

116119
EOD, $clearOutput);
@@ -128,6 +131,7 @@ public function testSearchImportAndClearAndDeleteWithoutIndices(): void
128131
Deleted sf_phpunit__tags
129132
Deleted sf_phpunit__pages
130133
Deleted sf_phpunit__self_normalizable
134+
Deleted sf_phpunit__dummy_custom_groups
131135
Done!
132136

133137
EOD, $clearOutput);
@@ -326,6 +330,7 @@ public function testSearchCreateWithoutIndices(): void
326330
Creating index sf_phpunit__tags for Meilisearch\Bundle\Tests\Entity\Link
327331
Creating index sf_phpunit__pages for Meilisearch\Bundle\Tests\Entity\Page
328332
Creating index sf_phpunit__self_normalizable for Meilisearch\Bundle\Tests\Entity\SelfNormalizable
333+
Creating index sf_phpunit__dummy_custom_groups for Meilisearch\Bundle\Tests\Entity\DummyCustomGroups
329334
Creating index sf_phpunit__aggregated for Meilisearch\Bundle\Tests\Entity\Post
330335
Creating index sf_phpunit__aggregated for Meilisearch\Bundle\Tests\Entity\Tag
331336
Done!
@@ -395,4 +400,41 @@ public function testImportsSelfNormalizable(): void
395400
],
396401
], $this->client->index('sf_phpunit__self_normalizable')->getDocuments()->getResults());
397402
}
403+
404+
public function testImportsDummyWithCustomGroups(): void
405+
{
406+
for ($i = 1; $i <= 2; ++$i) {
407+
$this->entityManager->persist(new DummyCustomGroups($i, "Dummy $i", new \DateTimeImmutable('2024-04-04 07:32:0'.$i)));
408+
}
409+
410+
$this->entityManager->flush();
411+
412+
$importCommand = $this->application->find('meili:import');
413+
$importCommandTester = new CommandTester($importCommand);
414+
$importCommandTester->execute(['--indices' => 'dummy_custom_groups']);
415+
416+
$importOutput = $importCommandTester->getDisplay();
417+
418+
$this->assertSame(<<<'EOD'
419+
Importing for index Meilisearch\Bundle\Tests\Entity\DummyCustomGroups
420+
Indexed a batch of 2 / 2 Meilisearch\Bundle\Tests\Entity\DummyCustomGroups entities into sf_phpunit__dummy_custom_groups index (2 indexed since start)
421+
Done!
422+
423+
EOD, $importOutput);
424+
425+
self::assertSame([
426+
[
427+
'objectID' => 1,
428+
'id' => 1,
429+
'name' => 'Dummy 1',
430+
'createdAt' => '2024-04-04T07:32:01+00:00',
431+
],
432+
[
433+
'objectID' => 2,
434+
'id' => 2,
435+
'name' => 'Dummy 2',
436+
'createdAt' => '2024-04-04T07:32:02+00:00',
437+
],
438+
], $this->client->index('sf_phpunit__dummy_custom_groups')->getDocuments()->getResults());
439+
}
398440
}

tests/Unit/ConfigurationTest.php

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,15 @@ public function dataTestConfigurationTree(): array
8282
'name' => 'posts',
8383
'class' => 'App\Entity\Post',
8484
'enable_serializer_groups' => false,
85+
'serializer_groups' => ['searchable'],
8586
'index_if' => null,
8687
'settings' => [],
8788
],
8889
1 => [
8990
'name' => 'tags',
9091
'class' => 'App\Entity\Tag',
9192
'enable_serializer_groups' => true,
93+
'serializer_groups' => ['searchable'],
9294
'index_if' => null,
9395
'settings' => [],
9496
],
@@ -100,10 +102,18 @@ public function dataTestConfigurationTree(): array
100102
'prefix' => 'sf_',
101103
'indices' => [
102104
[
103-
'name' => 'items', 'class' => 'App\Entity\Post', 'enable_serializer_groups' => false, 'index_if' => null, 'settings' => [],
105+
'name' => 'items',
106+
'class' => 'App\Entity\Post',
107+
'enable_serializer_groups' => false,
108+
'index_if' => null,
109+
'settings' => [],
104110
],
105111
[
106-
'name' => 'items', 'class' => 'App\Entity\Tag', 'enable_serializer_groups' => false, 'index_if' => null, 'settings' => [],
112+
'name' => 'items',
113+
'class' => 'App\Entity\Tag',
114+
'enable_serializer_groups' => false,
115+
'index_if' => null,
116+
'settings' => [],
107117
],
108118
],
109119
'nbResults' => 20,
@@ -115,10 +125,50 @@ public function dataTestConfigurationTree(): array
115125
'prefix' => 'sf_',
116126
'indices' => [
117127
[
118-
'name' => 'items', 'class' => 'App\Entity\Post', 'enable_serializer_groups' => false, 'index_if' => null, 'settings' => [],
128+
'name' => 'items',
129+
'class' => 'App\Entity\Post',
130+
'enable_serializer_groups' => false,
131+
'serializer_groups' => ['searchable'],
132+
'index_if' => null, 'settings' => [],
119133
],
120134
[
121-
'name' => 'items', 'class' => 'App\Entity\Tag', 'enable_serializer_groups' => false, 'index_if' => null, 'settings' => [],
135+
'name' => 'items',
136+
'class' => 'App\Entity\Tag',
137+
'enable_serializer_groups' => false,
138+
'serializer_groups' => ['searchable'],
139+
'index_if' => null,
140+
'settings' => [],
141+
],
142+
],
143+
'nbResults' => 20,
144+
'batchSize' => 500,
145+
'serializer' => 'serializer',
146+
'doctrineSubscribedEvents' => ['postPersist', 'postUpdate', 'preRemove'],
147+
],
148+
],
149+
'Custom serializer groups' => [
150+
[
151+
'prefix' => 'sf_',
152+
'indices' => [
153+
[
154+
'name' => 'items',
155+
'class' => 'App\Entity\Post',
156+
'enable_serializer_groups' => true,
157+
'serializer_groups' => ['post.public', 'post.private'],
158+
'index_if' => null,
159+
'settings' => [],
160+
],
161+
],
162+
],
163+
[
164+
'prefix' => 'sf_',
165+
'indices' => [
166+
[
167+
'name' => 'items',
168+
'class' => 'App\Entity\Post',
169+
'enable_serializer_groups' => true,
170+
'serializer_groups' => ['post.public', 'post.private'],
171+
'index_if' => null, 'settings' => [],
122172
],
123173
],
124174
'nbResults' => 20,

tests/Unit/SerializationTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public function testSimpleEntityToSearchableArray(): void
4444
$post,
4545
$postMeta,
4646
static::getContainer()->get('serializer'),
47-
['useSerializerGroup' => true]
47+
['normalizationGroups' => [Searchable::NORMALIZATION_GROUP]]
4848
);
4949

5050
$expected = [

tests/bootstrap.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Symfony\Component\Filesystem\Filesystem;
6+
7+
require dirname(__DIR__).'/vendor/autoload.php';
8+
9+
(new Filesystem())->remove(dirname(__DIR__).'/var/cache/test');

tests/config/meilisearch.yaml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,7 @@ meilisearch:
3636
enable_serializer_groups: true
3737
- name: self_normalizable
3838
class: 'Meilisearch\Bundle\Tests\Entity\SelfNormalizable'
39+
- name: dummy_custom_groups
40+
class: 'Meilisearch\Bundle\Tests\Entity\DummyCustomGroups'
41+
enable_serializer_groups: true
42+
serializer_groups: ['public', 'private']

0 commit comments

Comments
 (0)