Skip to content

Commit 1f44711

Browse files
committed
test(doctrine): runtime resources stored in MongoDB
1 parent 2e938ad commit 1f44711

11 files changed

Lines changed: 859 additions & 0 deletions

File tree

‎phpstan.neon.dist‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,13 @@ parameters:
211211
identifier: symfonyContainer.serviceNotFound
212212
path: tests/Functional/RuntimeResourceEavTest.php
213213
count: 2
214+
-
215+
message: '#Service "ApiPlatform\\Tests\\Fixtures\\TestBundle\\RuntimeResource\\DefinitionProvider" is not registered in the container\.#'
216+
identifier: symfonyContainer.serviceNotFound
217+
path: tests/Functional/RuntimeResourceMongoDbTest.php
218+
count: 4
219+
-
220+
message: '#Service "ApiPlatform\\Tests\\Fixtures\\TestBundle\\RuntimeResource\\RuntimeResources" is not registered in the container\.#'
221+
identifier: symfonyContainer.serviceNotFound
222+
path: tests/Functional/RuntimeResourceMongoDbTest.php
223+
count: 2
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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\Document\RuntimeResource;
15+
16+
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
17+
18+
#[ODM\EmbeddedDocument]
19+
class AttributeDefinition
20+
{
21+
/**
22+
* @param array<string, mixed> $options
23+
*/
24+
public function __construct(
25+
#[ODM\Field]
26+
private string $name,
27+
#[ODM\Field]
28+
private string $type,
29+
#[ODM\Field(type: 'bool')]
30+
private bool $required = false,
31+
#[ODM\Field(type: 'bool')]
32+
private bool $collection = false,
33+
#[ODM\Field(type: 'hash')]
34+
private array $options = [],
35+
#[ODM\Field(type: 'bool')]
36+
private bool $filterable = false,
37+
) {
38+
}
39+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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\Document\RuntimeResource;
15+
16+
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
17+
18+
#[ODM\Document(collection: 'runtime_document')]
19+
#[ODM\Index(keys: ['resource' => 'asc'])]
20+
class Document
21+
{
22+
#[ODM\Id(strategy: 'INCREMENT', type: 'int')]
23+
private ?int $id = null;
24+
25+
/**
26+
* @param array<string, mixed> $values
27+
*/
28+
public function __construct(
29+
#[ODM\Field]
30+
private string $resource,
31+
#[ODM\Field(type: 'hash')]
32+
private array $values = [],
33+
) {
34+
}
35+
36+
public function getId(): ?int
37+
{
38+
return $this->id;
39+
}
40+
41+
/**
42+
* @param array<string, mixed> $values
43+
*/
44+
public function setValues(array $values): void
45+
{
46+
$this->values = $values;
47+
}
48+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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\Document\RuntimeResource;
15+
16+
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
17+
18+
#[ODM\Document(collection: 'runtime_generation')]
19+
class Generation
20+
{
21+
#[ODM\Id(strategy: 'NONE', type: 'int')]
22+
private int $id = 1;
23+
24+
#[ODM\Field(type: 'int')]
25+
private int $value = 0;
26+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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\Document\RuntimeResource;
15+
16+
use Doctrine\Common\Collections\ArrayCollection;
17+
use Doctrine\Common\Collections\Collection;
18+
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
19+
20+
#[ODM\Document(collection: 'runtime_resource_definition')]
21+
class ResourceDefinition
22+
{
23+
#[ODM\Id(strategy: 'INCREMENT', type: 'int')]
24+
private ?int $id = null;
25+
26+
/** @var Collection<int, AttributeDefinition> */
27+
#[ODM\EmbedMany(targetDocument: AttributeDefinition::class)]
28+
private Collection $attributes;
29+
30+
public function __construct(
31+
#[ODM\Field]
32+
#[ODM\UniqueIndex]
33+
private string $name,
34+
#[ODM\Field]
35+
private string $label = '',
36+
#[ODM\Field(nullable: true)]
37+
private ?string $security = null,
38+
) {
39+
$this->attributes = new ArrayCollection();
40+
}
41+
42+
/**
43+
* @param array<string, mixed> $options
44+
*/
45+
public function addAttribute(string $name, string $type, bool $required = false, bool $collection = false, array $options = [], bool $filterable = false): self
46+
{
47+
$this->attributes->add(new AttributeDefinition($name, $type, $required, $collection, $options, $filterable));
48+
49+
return $this;
50+
}
51+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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\RuntimeResource\Odm;
15+
16+
use ApiPlatform\Doctrine\Odm\Filter\FilterInterface;
17+
use ApiPlatform\Metadata\IriConverterInterface;
18+
use ApiPlatform\Metadata\Operation;
19+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper;
20+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources;
21+
use Doctrine\ODM\MongoDB\Aggregation\Builder;
22+
use MongoDB\BSON\UTCDateTime;
23+
24+
final class DocumentFilter implements FilterInterface
25+
{
26+
public function __construct(
27+
private readonly RuntimeResources $resources,
28+
private readonly IriConverterInterface $iriConverter,
29+
) {
30+
}
31+
32+
public function apply(Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void
33+
{
34+
$parameter = $context['parameter'];
35+
$attribute = $this->resources->get((string) $operation?->getClass())->attributes[$parameter->getProperty()] ?? null;
36+
$value = null === $attribute ? null : RuntimeMapper::filterValue($attribute, $parameter->getValue(), $this->iriConverter);
37+
$match = $aggregationBuilder->match()->field('values.'.$parameter->getProperty());
38+
39+
null === $value ? $match->in([]) : $match->equals($value instanceof \DateTimeInterface ? new UTCDateTime($value->getTimestamp() * 1000 + (int) $value->format('v')) : $value);
40+
}
41+
42+
public function getDescription(string $resourceClass): array
43+
{
44+
return [];
45+
}
46+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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\RuntimeResource\Odm;
15+
16+
use ApiPlatform\Metadata\DeleteOperationInterface;
17+
use ApiPlatform\Metadata\Operation;
18+
use ApiPlatform\Metadata\Post;
19+
use ApiPlatform\State\ProcessorInterface;
20+
use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Document;
21+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper;
22+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObject;
23+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources;
24+
use Doctrine\ODM\MongoDB\DocumentManager;
25+
use Doctrine\Persistence\ManagerRegistry;
26+
use MongoDB\BSON\UTCDateTime;
27+
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
28+
29+
/**
30+
* @implements ProcessorInterface<RuntimeObject, RuntimeObject|null>
31+
*/
32+
final class DocumentProcessor implements ProcessorInterface
33+
{
34+
public function __construct(
35+
private readonly ManagerRegistry $registry,
36+
private readonly RuntimeMapper $mapper,
37+
private readonly DocumentProvider $provider,
38+
) {
39+
}
40+
41+
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?RuntimeObject
42+
{
43+
$manager = $this->registry->getManagerForClass(Document::class);
44+
\assert($manager instanceof DocumentManager && $data instanceof RuntimeObject);
45+
46+
$name = (string) RuntimeResources::nameOf($data::class);
47+
$document = $operation instanceof Post
48+
? new Document($name)
49+
: $manager->getRepository(Document::class)->findOneBy(['id' => (int) ($uriVariables['id'] ?? 0), 'resource' => $name]) ?? throw new NotFoundHttpException();
50+
51+
if ($operation instanceof DeleteOperationInterface) {
52+
$manager->remove($document);
53+
$manager->flush();
54+
55+
return null;
56+
}
57+
58+
$document->setValues(array_map(static fn (mixed $value): mixed => $value instanceof \DateTimeInterface ? new UTCDateTime($value->getTimestamp() * 1000 + (int) $value->format('v')) : $value, $this->mapper->extract($data)));
59+
$manager->persist($document);
60+
$manager->flush();
61+
62+
return $this->provider->find($name, (int) $document->getId());
63+
}
64+
}
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
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\RuntimeResource\Odm;
15+
16+
use ApiPlatform\Doctrine\Odm\State\Options;
17+
use ApiPlatform\Metadata\CollectionOperationInterface;
18+
use ApiPlatform\Metadata\Operation;
19+
use ApiPlatform\State\Pagination\PaginatorInterface;
20+
use ApiPlatform\State\Pagination\TraversablePaginator;
21+
use ApiPlatform\State\ProviderInterface;
22+
use ApiPlatform\Tests\Fixtures\TestBundle\Document\RuntimeResource\Document;
23+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeMapper;
24+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeObject;
25+
use ApiPlatform\Tests\Fixtures\TestBundle\RuntimeResource\RuntimeResources;
26+
use Doctrine\ODM\MongoDB\Aggregation\Builder;
27+
use Doctrine\ODM\MongoDB\DocumentManager;
28+
use Doctrine\Persistence\ManagerRegistry;
29+
use MongoDB\BSON\UTCDateTime;
30+
31+
final class DocumentProvider implements ProviderInterface
32+
{
33+
public function __construct(
34+
private readonly ProviderInterface $itemProvider,
35+
private readonly ProviderInterface $collectionProvider,
36+
private readonly ManagerRegistry $registry,
37+
private readonly RuntimeMapper $mapper,
38+
) {
39+
}
40+
41+
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
42+
{
43+
$name = RuntimeResources::nameOf((string) $operation->getClass());
44+
if (null === $name) {
45+
return null;
46+
}
47+
48+
$operation = $operation->withStateOptions(new Options(documentClass: Document::class, handleLinks: [self::class, 'handleLinks']));
49+
if (!$operation instanceof CollectionOperationInterface) {
50+
$document = $this->itemProvider->provide($operation, $uriVariables, $context);
51+
52+
return $document instanceof Document ? $this->find($name, (int) $document->getId()) : null;
53+
}
54+
55+
$documents = $this->collectionProvider->provide($operation, $uriVariables, $context);
56+
$objects = $this->mapper->hydrate($name, array_map(static fn (Document $document): int => (int) $document->getId(), iterator_to_array($documents, false)), $this->load(...));
57+
58+
return $documents instanceof PaginatorInterface ? new TraversablePaginator(new \ArrayIterator($objects), $documents->getCurrentPage(), $documents->getItemsPerPage(), $documents->getTotalItems()) : $objects;
59+
}
60+
61+
/**
62+
* @param array<string, mixed> $uriVariables
63+
* @param array<string, mixed> $context
64+
*/
65+
public static function handleLinks(Builder $aggregationBuilder, array $uriVariables, array $context): void
66+
{
67+
$aggregationBuilder->match()->field('resource')->equals(RuntimeResources::nameOf((string) $context['operation']->getClass()));
68+
if (isset($uriVariables['id'])) {
69+
$aggregationBuilder->match()->field('id')->equals((int) $uriVariables['id']);
70+
}
71+
}
72+
73+
public function find(string $name, int $id): ?RuntimeObject
74+
{
75+
return $this->mapper->hydrate($name, [$id], $this->load(...))[0] ?? null;
76+
}
77+
78+
/**
79+
* @param list<int> $ids
80+
*
81+
* @return array<int, array<string, mixed>>
82+
*/
83+
private function load(string $name, array $ids): array
84+
{
85+
$manager = $this->registry->getManagerForClass(Document::class);
86+
\assert($manager instanceof DocumentManager);
87+
88+
$values = [];
89+
foreach ($manager->getDocumentCollection(Document::class)->find(['resource' => $name, '_id' => ['$in' => $ids]], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]) as $row) {
90+
$values[$row['_id']] = array_map(static fn (mixed $value): mixed => $value instanceof UTCDateTime ? \DateTimeImmutable::createFromInterface($value->toDateTime()) : $value, $row['values'] ?? []);
91+
}
92+
93+
return $values;
94+
}
95+
}

0 commit comments

Comments
 (0)