-
-
Notifications
You must be signed in to change notification settings - Fork 975
Expand file tree
/
Copy pathMappingTest.php
More file actions
521 lines (436 loc) · 19.2 KB
/
Copy pathMappingTest.php
File metadata and controls
521 lines (436 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Tests\Functional;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\BookStoreResource;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\FirstResource;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue7563\BookDto;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedPatchResource;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResource;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceNoMap;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceOdm;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceSourceOnly;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithInput;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithRelation;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithRelationRelated;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SecondResource;
use ApiPlatform\Tests\Fixtures\TestBundle\Document\MappedDocument;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Book;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\BookStore;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedEntity;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedEntityNoMap;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedEntitySourceOnly;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedPatchEntity;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationEntity;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationRelatedEntity;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SameEntity;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;
use Doctrine\ODM\MongoDB\DocumentManager;
final class MappingTest extends ApiTestCase
{
use RecreateSchemaTrait;
use SetupClassResourcesTrait;
protected static ?bool $alwaysBootKernel = false;
/**
* @return class-string[]
*/
public static function getResources(): array
{
return [
MappedResource::class,
MappedResourceOdm::class,
FirstResource::class,
SecondResource::class,
MappedResourceWithRelation::class,
MappedResourceWithRelationRelated::class,
MappedResourceWithInput::class,
MappedResourceSourceOnly::class,
MappedResourceNoMap::class,
BookDto::class,
BookStoreResource::class,
MappedPatchResource::class,
];
}
public function testShouldMapBetweenResourceAndEntity(): void
{
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([$this->isMongoDB() ? MappedDocument::class : MappedEntity::class]);
$this->loadFixtures();
$client = self::createClient();
$client->request('GET', $this->isMongoDB() ? 'mapped_resource_odms' : 'mapped_resources');
$this->assertArrayHasKey('mapped_data', $client->getKernelBrowser()->getRequest()->attributes->all());
$this->assertJsonContains(['member' => [
['username' => 'B0 A0'],
['username' => 'B1 A1'],
['username' => 'B2 A2'],
]]);
$client = self::createClient();
$r = $client->request('POST', $this->isMongoDB() ? 'mapped_resource_odms' : 'mapped_resources', ['json' => ['username' => 'so yuka']]);
$this->assertJsonContains(['username' => 'so yuka']);
$this->assertArrayHasKey('persisted_data', $client->getKernelBrowser()->getRequest()->attributes->all());
$manager = $this->getManager();
$repo = $manager->getRepository($this->isMongoDB() ? MappedDocument::class : MappedEntity::class);
$persisted = $repo->findOneBy(['id' => $r->toArray()['id']]);
$this->assertSame('so', $persisted->getFirstName());
$this->assertSame('yuka', $persisted->getLastName());
$uri = $r->toArray()['@id'];
self::createClient()->request('GET', $uri);
$this->assertJsonContains(['username' => 'so yuka']);
$r = self::createClient()->request('PATCH', $uri, ['json' => ['username' => 'ba zar'], 'headers' => ['content-type' => 'application/merge-patch+json']]);
$this->assertJsonContains(['username' => 'ba zar']);
$r = self::createClient()->request('DELETE', $uri);
$this->assertResponseStatusCodeSame(204);
}
/**
* When an API resource has multiple #[Map] targets (e.g. MappedEntity + AnotherMappedObject),
* the ObjectMapperInputProcessor must resolve the correct target using stateOptions during POST.
*/
public function testPostWithMultipleMapTargetsResolvesCorrectEntity(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested.');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([MappedEntity::class]);
$client = self::createClient();
$r = $client->request('POST', 'mapped_resources', ['json' => ['username' => 'multi target']]);
$this->assertResponseStatusCodeSame(201);
$this->assertJsonContains(['username' => 'multi target']);
// Verify the mapped_data is the entity from stateOptions, not AnotherMappedObject
$mappedData = $client->getKernelBrowser()->getRequest()->attributes->get('mapped_data');
$this->assertInstanceOf(MappedEntity::class, $mappedData, 'ObjectMapper should resolve to the stateOptions entity class, not the first #[Map] target.');
// Verify persistence
$repo = $this->getManager()->getRepository(MappedEntity::class);
$persisted = $repo->findOneBy(['id' => $r->toArray()['id']]);
$this->assertNotNull($persisted);
$this->assertSame('multi', $persisted->getFirstName());
$this->assertSame('target', $persisted->getLastName());
}
public function testShouldMapToTheCorrectResource(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested.');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([SameEntity::class]);
$manager = $this->getManager();
$e = new SameEntity();
$e->setName('foo');
$manager->persist($e);
$manager->flush();
self::createClient()->request('GET', '/seconds');
$this->assertJsonContains(['hydra:member' => [
['name' => 'foo', 'extra' => 'field'],
]]);
}
public function testMapPutAllowCreate(): void
{
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB is not tested');
}
$this->recreateSchema([MappedResourceWithRelationEntity::class, MappedResourceWithRelationRelatedEntity::class]);
$manager = $this->getManager();
$e = new MappedResourceWithRelationRelatedEntity();
$e->name = 'test';
$manager->persist($e);
$manager->flush();
self::createClient()->request('PUT', '/mapped_resource_with_relations/4', [
'json' => [
'@id' => '/mapped_resource_with_relations/4',
'relation' => '/mapped_resource_with_relation_relateds/'.$e->getId(),
],
'headers' => [
'content-type' => 'application/ld+json',
],
]);
$this->assertJsonContains([
'@context' => '/contexts/MappedResourceWithRelation',
'@id' => '/mapped_resource_with_relations/4',
'@type' => 'MappedResourceWithRelation',
'id' => '4',
'relationName' => 'test',
'relation' => '/mapped_resource_with_relation_relateds/1',
]);
}
public function testShouldNotMapWhenInput(): void
{
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested');
}
$this->recreateSchema([MappedEntity::class]);
$this->loadFixtures();
$r = self::createClient()->request('POST', 'mapped_resource_with_input', [
'headers' => [
'content-type' => 'application/ld+json',
],
'json' => ['name' => 'test', 'id' => '1'],
]);
$this->assertJsonContains(['username' => 'test']);
}
public function testShouldMapWithSourceOnly(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([MappedEntitySourceOnly::class]);
$manager = $this->getManager();
for ($i = 0; $i < 10; ++$i) {
$e = new MappedEntitySourceOnly();
$e->setLastName('A'.$i);
$e->setFirstName('B'.$i);
$manager->persist($e);
}
$manager->flush();
$r = self::createClient()->request('GET', '/mapped_resource_source_onlies');
$this->assertJsonContains(['member' => [
['username' => 'B0 A0'],
['username' => 'B1 A1'],
['username' => 'B2 A2'],
]]);
$r = self::createClient()->request('POST', 'mapped_resource_source_onlies', ['json' => ['username' => 'so yuka']]);
$this->assertJsonContains(['username' => 'so yuka']);
$manager = $this->getManager();
$repo = $manager->getRepository(MappedEntitySourceOnly::class);
$persisted = $repo->findOneBy(['id' => $r->toArray()['id']]);
$this->assertSame('so', $persisted->getFirstName());
$this->assertSame('yuka', $persisted->getLastName());
$uri = $r->toArray()['@id'];
self::createClient()->request('GET', $uri);
$this->assertJsonContains(['username' => 'so yuka']);
$r = self::createClient()->request('PATCH', $uri, ['json' => ['username' => 'ba zar'], 'headers' => ['content-type' => 'application/merge-patch+json']]);
$this->assertJsonContains(['username' => 'ba zar']);
}
public function testShouldNotMapWhenCanMapIsFalse(): void
{
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested');
}
$this->recreateSchema([MappedEntityNoMap::class]);
$client = self::createClient();
$client->request('POST', '/mapped_resource_no_maps', [
'json' => ['name' => 'test name', 'id' => 1],
'headers' => ['content-type' => 'application/ld+json'],
]);
$this->assertArrayNotHasKey('mapped_data', $client->getKernelBrowser()->getRequest()->attributes->all());
$this->assertResponseStatusCodeSame(201);
$this->assertJsonContains([
'@context' => '/contexts/MappedResourceNoMap',
'@id' => '/mapped_resource_no_maps/1',
'@type' => 'MappedResourceNoMap',
'id' => 1,
'name' => 'test name',
]);
$client = self::createClient();
$client->request('GET', '/mapped_resource_no_maps/1');
$this->assertArrayNotHasKey('persisted_data', $client->getKernelBrowser()->getRequest()->attributes->all());
$this->assertResponseStatusCodeSame(200);
$this->assertJsonContains([
'@context' => '/contexts/MappedResourceNoMap',
'@id' => '/mapped_resource_no_maps/1',
'@type' => 'MappedResourceNoMap',
'id' => 1,
'name' => 'test name',
]);
}
private function loadFixtures(): void
{
$manager = $this->getManager();
for ($i = 0; $i < 10; ++$i) {
$e = $manager instanceof DocumentManager ? new MappedDocument() : new MappedEntity();
$e->setLastName('A'.$i);
$e->setFirstName('B'.$i);
$manager->persist($e);
}
$manager->flush();
}
private function loadBookFixtures(): void
{
$manager = $this->getManager();
for ($i = 1; $i <= 5; ++$i) {
$book = new Book();
$book->name = 'Book '.$i;
$book->isbn = 'ISBN-'.$i;
$manager->persist($book);
}
$manager->flush();
}
public function testGetSingleBookDto(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested.');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([Book::class]);
$this->loadBookFixtures();
self::createClient()->request('GET', '/book_dtos/1');
self::assertResponseIsSuccessful();
self::assertJsonContains([
'@type' => 'BookDto',
'id' => 1,
'name' => 'Book 1',
'customIsbn' => 'customISBN-1',
]);
}
public function testGetCollectionBookDtoPaginated(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested.');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([Book::class]);
$this->loadBookFixtures();
$response = self::createClient()->request('GET', '/book_dtos');
self::assertResponseIsSuccessful();
$json = $response->toArray();
self::assertCount(3, $json['hydra:member']);
foreach ($response->toArray()['hydra:member'] as $member) {
self::assertStringStartsWith('customISBN-', $member['customIsbn']);
}
}
public function testGetCollectionBookDtoUnpaginated(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested.');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([Book::class]);
$this->loadBookFixtures();
$response = self::createClient()->request('GET', '/book_dtos?pagination=false');
self::assertResponseIsSuccessful();
$json = $response->toArray();
self::assertCount(5, $json['hydra:member']);
foreach ($json['hydra:member'] as $member) {
self::assertStringStartsWith('customISBN-', $member['customIsbn']);
}
}
public function testOutputDtoForCollectionRead(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested.');
}
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
$this->recreateSchema([BookStore::class]);
$manager = $this->getManager();
$book1 = new BookStore();
$book1->title = 'API Platform Guide';
$book1->isbn = '978-1234567890';
$book1->description = 'A comprehensive guide to API Platform';
$book1->author = 'John Doe';
$manager->persist($book1);
$book2 = new BookStore();
$book2->title = 'REST APIs Handbook';
$book2->isbn = '978-0987654321';
$book2->description = 'Everything about REST APIs';
$book2->author = 'Jane Smith';
$manager->persist($book2);
$manager->flush();
// Test GetCollection returns only the lighter DTO fields (id, name, isbn)
$response = self::createClient()->request('GET', '/book_store_resources');
self::assertResponseIsSuccessful();
self::assertJsonContains([
'@id' => '/book_store_resources',
'@type' => 'Collection',
'member' => [
[
'@id' => '/book_store_resources/1',
'@type' => 'BookStoreResource',
'id' => 1,
'name' => 'API Platform Guide',
'isbn' => '978-1234567890',
],
[
'@id' => '/book_store_resources/2',
'@type' => 'BookStoreResource',
'id' => 2,
'name' => 'REST APIs Handbook',
'isbn' => '978-0987654321',
],
],
]);
$json = $response->toArray();
// Verify that description and author are NOT present in collection output
foreach ($json['member'] as $member) {
self::assertArrayNotHasKey('description', $member);
self::assertArrayNotHasKey('author', $member);
self::assertArrayHasKey('id', $member);
self::assertArrayHasKey('name', $member);
self::assertArrayHasKey('isbn', $member);
}
// Test Get (single item) returns all fields from the full resource
$response = self::createClient()->request('GET', '/book_store_resources/1');
self::assertResponseIsSuccessful();
self::assertJsonContains([
'id' => 1,
'title' => 'API Platform Guide',
'isbn' => '978-1234567890',
'description' => 'A comprehensive guide to API Platform',
'author' => 'John Doe',
]);
}
/**
* Test PATCH with input DTO + ObjectMapper: only client-sent fields should be updated.
* The input DTO uses uninitialized properties so ObjectMapper skips unsent fields.
*/
public function testPatchWithInputDtoOnlyUpdatessentFields(): void
{
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}
if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB not tested');
}
$this->recreateSchema([MappedPatchEntity::class]);
$manager = $this->getManager();
$entity = new MappedPatchEntity();
$entity->name = 'original name';
$entity->description = 'original description';
$manager->persist($entity);
$manager->flush();
$id = $entity->id;
// PATCH only the name — description should remain unchanged
self::createClient()->request('PATCH', '/mapped_patch_resources/'.$id, [
'headers' => ['content-type' => 'application/merge-patch+json'],
'json' => ['name' => 'updated name'],
]);
self::assertResponseIsSuccessful();
self::assertJsonContains([
'name' => 'updated name',
'description' => 'original description',
]);
}
}