Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/JsonApi/Filter/SparseFieldsetParameterProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public function provide(Parameter $parameter, array $parameters = [], array $con
return null;
}

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

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

Expand Down Expand Up @@ -95,6 +94,14 @@ private function getAllowedProperties(string $type): array
return [];
}

return $this->getReadableProperties($resourceClass);
}

/**
* @return list<string>
*/
private function getReadableProperties(string $resourceClass): array
{
$allowedProperties = [];
foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
if ($this->propertyMetadataFactory->create($resourceClass, $property)->isReadable()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ public function testFieldsTypeKeyIsResolvedToItsHostPropertyName(): void
$provider = $this->createProvider(authorShortName: 'SparseFieldsetIncludeAuthor');

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

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

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

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

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

$result = $provider->provide($parameter, [], ['operation' => $operation]);
Expand All @@ -119,7 +116,7 @@ private function createProvider(string $authorShortName, ?NameConverterInterface
$propertyNameCollectionFactory = $this->createStub(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactory->method('create')->willReturnCallback(
static fn (string $class): PropertyNameCollection => match ($class) {
$articleClass => new PropertyNameCollection(['author']),
$articleClass => new PropertyNameCollection(['author', 'title', 'artistCredit']),
$authorClass => new PropertyNameCollection(['name']),
default => new PropertyNameCollection([]),
},
Expand All @@ -135,6 +132,7 @@ private function createProvider(string $authorShortName, ?NameConverterInterface
static fn (string $class, string $property): ApiProperty => match (true) {
$articleClass === $class && 'author' === $property => $authorRelationProperty,
$authorClass === $class && 'name' === $property => $authorNameProperty,
$articleClass === $class && \in_array($property, ['title', 'artistCredit'], true) => $authorNameProperty,
default => new ApiProperty(),
},
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?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\Fixtures\TestBundle\ApiResource\JsonApi;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\JsonApi\Filter\SparseFieldset;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\SparseFieldsetStateOptionsEntity;

#[ApiResource(
shortName: 'SparseFieldsetStateOptions',
stateOptions: new Options(entityClass: SparseFieldsetStateOptionsEntity::class),
operations: [
new Get(
uriTemplate: '/sparse_fieldset_state_options/{id}',
uriVariables: ['id'],
provider: [self::class, 'provide'],
),
],
parameters: ['fields' => new QueryParameter(filter: SparseFieldset::class)],
)]
final class SparseFieldsetStateOptions
{
public function __construct(
#[ApiProperty(identifier: true)]
public int $id,
public string $title,
public int $totalTracks,
) {
}

public static function provide(Operation $operation, array $uriVariables = []): self
{
$id = (int) ($uriVariables['id'] ?? 1);

return new self($id, 'Title #'.$id, 12);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?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\Fixtures\TestBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class SparseFieldsetStateOptionsEntity
{
public function __construct(
#[ORM\Column(type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'AUTO')]
public ?int $id = null,
#[ORM\Column(type: 'string', nullable: true)]
public ?string $title = null,
) {
}
}
54 changes: 54 additions & 0 deletions tests/Functional/JsonApi/SparseFieldsetStateOptionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?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\JsonApi;

use ApiPlatform\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\JsonApi\SparseFieldsetStateOptions;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;

final class SparseFieldsetStateOptionsTest extends ApiTestCase
{
use RecreateSchemaTrait;
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

public static function getResources(): array
{
return [SparseFieldsetStateOptions::class];
}

protected function setUp(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('The fixture maps to a Doctrine ORM entity.');
}
}

public function testComputedResourcePropertyCanBeSelected(): void
{
$response = self::createClient()->request(
'GET',
'/sparse_fieldset_state_options/1?fields[SparseFieldsetStateOptions]=title,totalTracks',
['headers' => ['Accept' => 'application/vnd.api+json']],
);

$this->assertResponseIsSuccessful();
$this->assertSame(
['title' => 'Title #1', 'totalTracks' => 12],
$response->toArray()['data']['attributes'],
);
}
}
Loading