Skip to content

Commit a032e79

Browse files
authored
fix(jsonapi): sparse fieldset reads the resource properties (#8862)
* test(jsonapi): select resource-only fields with stateOptions * fix(jsonapi): sparse fieldset reads the resource properties
1 parent 824eaec commit a032e79

5 files changed

Lines changed: 148 additions & 6 deletions

File tree

‎src/JsonApi/Filter/SparseFieldsetParameterProvider.php‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ public function provide(Parameter $parameter, array $parameters = [], array $con
4242
return null;
4343
}
4444

45-
$allowedProperties = $parameter->getProperties() ?? [];
4645
$value = $parameter->getValue();
4746
$normalizationContext = $operation->getNormalizationContext();
4847

@@ -57,7 +56,7 @@ public function provide(Parameter $parameter, array $parameters = [], array $con
5756
foreach ($value as $resource => $fields) {
5857
if (strtolower($resource) === $shortName) {
5958
$p = &$properties;
60-
$resourceAllowedProperties = $allowedProperties;
59+
$resourceAllowedProperties = $this->getReadableProperties((string) $operation->getClass());
6160
} else {
6261
$resourceAllowedProperties = $this->getAllowedProperties((string) $resource);
6362

@@ -95,6 +94,14 @@ private function getAllowedProperties(string $type): array
9594
return [];
9695
}
9796

97+
return $this->getReadableProperties($resourceClass);
98+
}
99+
100+
/**
101+
* @return list<string>
102+
*/
103+
private function getReadableProperties(string $resourceClass): array
104+
{
98105
$allowedProperties = [];
99106
foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
100107
if ($this->propertyMetadataFactory->create($resourceClass, $property)->isReadable()) {

‎src/JsonApi/Tests/Filter/SparseFieldsetParameterProviderTest.php‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ public function testFieldsTypeKeyIsResolvedToItsHostPropertyName(): void
5858
$provider = $this->createProvider(authorShortName: 'SparseFieldsetIncludeAuthor');
5959

6060
$parameter = (new QueryParameter(key: 'fields'))
61-
->withProperties(['title'])
6261
->setValue(['SparseFieldsetIncludeAuthor' => 'name']);
6362

6463
$result = $provider->provide($parameter, [], ['operation' => $operation]);
@@ -80,7 +79,6 @@ public function testFieldsKeyMatchingThePropertyNameStillWorks(): void
8079
$provider = $this->createProvider(authorShortName: 'Author');
8180

8281
$parameter = (new QueryParameter(key: 'fields'))
83-
->withProperties(['title'])
8482
->setValue(['author' => 'name']);
8583

8684
$result = $provider->provide($parameter, [], ['operation' => $operation]);
@@ -99,7 +97,6 @@ public function testFieldsAreDenormalizedWithTheNameConverter(): void
9997
$provider = $this->createProvider(authorShortName: 'SparseFieldsetIncludeAuthor', nameConverter: new CamelCaseToSnakeCaseNameConverter());
10098

10199
$parameter = (new QueryParameter(key: 'fields'))
102-
->withProperties(['title', 'artistCredit'])
103100
->setValue(['SparseFieldsetIncludeArticle' => 'title,artist_credit,unknown_field']);
104101

105102
$result = $provider->provide($parameter, [], ['operation' => $operation]);
@@ -119,7 +116,7 @@ private function createProvider(string $authorShortName, ?NameConverterInterface
119116
$propertyNameCollectionFactory = $this->createStub(PropertyNameCollectionFactoryInterface::class);
120117
$propertyNameCollectionFactory->method('create')->willReturnCallback(
121118
static fn (string $class): PropertyNameCollection => match ($class) {
122-
$articleClass => new PropertyNameCollection(['author']),
119+
$articleClass => new PropertyNameCollection(['author', 'title', 'artistCredit']),
123120
$authorClass => new PropertyNameCollection(['name']),
124121
default => new PropertyNameCollection([]),
125122
},
@@ -135,6 +132,7 @@ private function createProvider(string $authorShortName, ?NameConverterInterface
135132
static fn (string $class, string $property): ApiProperty => match (true) {
136133
$articleClass === $class && 'author' === $property => $authorRelationProperty,
137134
$authorClass === $class && 'name' === $property => $authorNameProperty,
135+
$articleClass === $class && \in_array($property, ['title', 'artistCredit'], true) => $authorNameProperty,
138136
default => new ApiProperty(),
139137
},
140138
);
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\JsonApi;
15+
16+
use ApiPlatform\Doctrine\Orm\State\Options;
17+
use ApiPlatform\JsonApi\Filter\SparseFieldset;
18+
use ApiPlatform\Metadata\ApiProperty;
19+
use ApiPlatform\Metadata\ApiResource;
20+
use ApiPlatform\Metadata\Get;
21+
use ApiPlatform\Metadata\Operation;
22+
use ApiPlatform\Metadata\QueryParameter;
23+
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SparseFieldsetStateOptionsEntity;
24+
25+
#[ApiResource(
26+
shortName: 'SparseFieldsetStateOptions',
27+
stateOptions: new Options(entityClass: SparseFieldsetStateOptionsEntity::class),
28+
operations: [
29+
new Get(
30+
uriTemplate: '/sparse_fieldset_state_options/{id}',
31+
uriVariables: ['id'],
32+
provider: [self::class, 'provide'],
33+
),
34+
],
35+
parameters: ['fields' => new QueryParameter(filter: SparseFieldset::class)],
36+
)]
37+
final class SparseFieldsetStateOptions
38+
{
39+
public function __construct(
40+
#[ApiProperty(identifier: true)]
41+
public int $id,
42+
public string $title,
43+
public int $totalTracks,
44+
) {
45+
}
46+
47+
public static function provide(Operation $operation, array $uriVariables = []): self
48+
{
49+
$id = (int) ($uriVariables['id'] ?? 1);
50+
51+
return new self($id, 'Title #'.$id, 12);
52+
}
53+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;
15+
16+
use Doctrine\ORM\Mapping as ORM;
17+
18+
#[ORM\Entity]
19+
class SparseFieldsetStateOptionsEntity
20+
{
21+
public function __construct(
22+
#[ORM\Column(type: 'integer')]
23+
#[ORM\Id]
24+
#[ORM\GeneratedValue(strategy: 'AUTO')]
25+
public ?int $id = null,
26+
#[ORM\Column(type: 'string', nullable: true)]
27+
public ?string $title = null,
28+
) {
29+
}
30+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Tests\Functional\JsonApi;
15+
16+
use ApiPlatform\Test\ApiTestCase;
17+
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\JsonApi\SparseFieldsetStateOptions;
18+
use ApiPlatform\Tests\RecreateSchemaTrait;
19+
use ApiPlatform\Tests\SetupClassResourcesTrait;
20+
21+
final class SparseFieldsetStateOptionsTest extends ApiTestCase
22+
{
23+
use RecreateSchemaTrait;
24+
use SetupClassResourcesTrait;
25+
26+
protected static ?bool $alwaysBootKernel = false;
27+
28+
public static function getResources(): array
29+
{
30+
return [SparseFieldsetStateOptions::class];
31+
}
32+
33+
protected function setUp(): void
34+
{
35+
if ($this->isMongoDB()) {
36+
$this->markTestSkipped('The fixture maps to a Doctrine ORM entity.');
37+
}
38+
}
39+
40+
public function testComputedResourcePropertyCanBeSelected(): void
41+
{
42+
$response = self::createClient()->request(
43+
'GET',
44+
'/sparse_fieldset_state_options/1?fields[SparseFieldsetStateOptions]=title,totalTracks',
45+
['headers' => ['Accept' => 'application/vnd.api+json']],
46+
);
47+
48+
$this->assertResponseIsSuccessful();
49+
$this->assertSame(
50+
['title' => 'Title #1', 'totalTracks' => 12],
51+
$response->toArray()['data']['attributes'],
52+
);
53+
}
54+
}

0 commit comments

Comments
 (0)