-
-
Notifications
You must be signed in to change notification settings - Fork 963
Expand file tree
/
Copy pathcomputed-field.php
More file actions
346 lines (299 loc) · 11.8 KB
/
computed-field.php
File metadata and controls
346 lines (299 loc) · 11.8 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
<?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);
// ---
// slug: computed-field
// name: Compute a field
// executable: true
// position: 10
// tags: doctrine, expert
// ---
// Computing and Sorting by a Derived Field in API Platform with Doctrine
// This recipe explains how to dynamically calculate a field for an API Platform/Doctrine entity
// by modifying the SQL query (via `stateOptions`/`handleLinks`), mapping the computed value
// to the entity object (via `processor`/`process`), and optionally enabling sorting on it
// using a custom filter configured via `parameters`.
namespace App\Filter {
use ApiPlatform\Doctrine\Orm\Filter\FilterInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\JsonSchemaFilterInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Parameter;
use ApiPlatform\State\ParameterNotFound;
use Doctrine\ORM\QueryBuilder;
// Custom API Platform filter to allow sorting by the computed 'totalQuantity' field.
// Works with the alias generated by Cart::handleLinks.
class SortComputedFieldFilter implements FilterInterface, JsonSchemaFilterInterface
{
// Applies the sorting logic to the Doctrine QueryBuilder.
// Called by API Platform when the associated query parameter ('sort[totalQuantity]') is present.
// Adds an ORDER BY clause to the query.
public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
{
if ($context['parameter']->getValue() instanceof ParameterNotFound) {
return;
}
// Extract the desired sort direction ('asc' or 'desc') from the parameter's value.
// IMPORTANT: 'totalQuantity' here MUST match the alias defined in Cart::handleLinks.
$queryBuilder->addOrderBy('totalQuantity', $context['parameter']->getValue()['totalQuantity'] ?? 'ASC');
}
/**
* @return array<string, mixed>
*/
// Defines the OpenAPI/Swagger schema for this filter parameter.
// Tells API Platform documentation generators that 'sort[totalQuantity]' expects 'asc' or 'desc'.
// This also add constraint violations to the parameter that will reject any wrong values.
public function getSchema(Parameter $parameter): array
{
return ['type' => 'string', 'enum' => ['asc', 'desc']];
}
public function getDescription(string $resourceClass): array
{
return [];
}
}
}
namespace App\Entity {
use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\NotExposed;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\QueryParameter;
use App\Filter\SortComputedFieldFilter;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\QueryBuilder;
#[ORM\Entity]
// Defines the GetCollection operation for Cart, including computed 'totalQuantity'.
// Recipe involves:
// 1. setup the repository method (modify query)
// 2. process (map result)
// 3. parameters (filters)
#[GetCollection(
normalizationContext: ['hydra_prefix' => false],
paginationItemsPerPage: 3,
paginationPartial: false,
// stateOptions: Uses repositoryMethod to modify the query *before* fetching. See App\Repository\CartRepository.
stateOptions: new Options(repositoryMethod: 'getCartsWithTotalQuantity'),
// processor: Uses process to map the result *after* fetching, *before* serialization.
processor: [self::class, 'process'],
write: true,
// parameters: Defines query parameters.
parameters: [
// Define the sorting parameter for 'totalQuantity'.
'sort[:property]' => new QueryParameter(
// Link this parameter definition to our custom filter.
filter: new SortComputedFieldFilter(),
// Specify which properties this filter instance should handle.
properties: ['totalQuantity'],
property: 'totalQuantity'
),
]
)]
class Cart
{
// Processor function called *after* fetching data, *before* serialization.
// Maps the raw 'totalQuantity' from Doctrine result onto the Cart entity's property.
// Handles Doctrine's array result structure: [0 => Entity, 'alias' => computedValue].
// Reshapes data back into an array of Cart objects.
public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
{
// Iterate through the raw results. $value will be like [0 => Cart Object, 'totalQuantity' => 15]
foreach ($data as &$value) {
// Get the Cart entity object.
$cart = $value[0];
// Get the computed totalQuantity value using the alias defined in handleLinks.
// Use null coalescing operator for safety.
$cart->totalQuantity = $value['totalQuantity'] ?? 0;
// Replace the raw array structure with just the processed Cart object.
$value = $cart;
}
// Return the collection of Cart objects with the totalQuantity property populated.
return $data;
}
// Public property to hold the computed total quantity.
// Not mapped by Doctrine (@ORM\Column) but populated by the 'process' method.
// API Platform will serialize this property.
public ?int $totalQuantity;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
/**
* @var Collection<int, CartProduct> the items in this cart
*/
#[ORM\OneToMany(targetEntity: CartProduct::class, mappedBy: 'cart', cascade: ['persist', 'remove'], orphanRemoval: true)]
private Collection $items;
public function __construct()
{
$this->items = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* @return Collection<int, CartProduct>
*/
public function getItems(): Collection
{
return $this->items;
}
public function addItem(CartProduct $item): self
{
if (!$this->items->contains($item)) {
$this->items[] = $item;
$item->setCart($this);
}
return $this;
}
public function removeItem(CartProduct $item): self
{
if ($this->items->removeElement($item)) {
// set the owning side to null (unless already changed)
if ($item->getCart() === $this) {
$item->setCart(null);
}
}
return $this;
}
}
#[NotExposed()]
#[ORM\Entity]
class CartProduct
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\ManyToOne(targetEntity: Cart::class, inversedBy: 'items')]
#[ORM\JoinColumn(nullable: false)]
private ?Cart $cart = null;
#[ORM\Column(type: 'integer')]
private int $quantity = 1;
public function getId(): ?int
{
return $this->id;
}
public function getCart(): ?Cart
{
return $this->cart;
}
public function setCart(?Cart $cart): self
{
$this->cart = $cart;
return $this;
}
public function getQuantity(): int
{
return $this->quantity;
}
public function setQuantity(int $quantity): self
{
$this->quantity = $quantity;
return $this;
}
}
}
namespace App\Repository {
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
/**
* @extends EntityRepository<Cart::class>
*/
class CartRepository extends EntityRepository
{
// This repository method is used via stateOptions to alter the QueryBuilder *before* data is fetched.
// Adds SQL logic (JOIN, SELECT aggregate, GROUP BY) to calculate 'totalQuantity' at the database level.
// The alias 'totalQuantity' created here is crucial for the filter and processor.
public function getCartsWithTotalQuantity(): QueryBuilder
{
$queryBuilder = $this->createQueryBuilder('o');
$queryBuilder->leftJoin('o.items', 'items')
->addSelect('COALESCE(SUM(items.quantity), 0) AS totalQuantity')
->addGroupBy('o.id');
return $queryBuilder;
}
}
}
namespace App\Playground {
use Symfony\Component\HttpFoundation\Request;
function request(): Request
{
return Request::create('/carts?sort[totalQuantity]=asc', 'GET');
}
}
namespace DoctrineMigrations {
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Migration extends AbstractMigration
{
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE cart (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)');
$this->addSql('CREATE TABLE cart_product (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, quantity INTEGER NOT NULL, cart_id INTEGER NOT NULL, CONSTRAINT FK_6DDC373A1AD5CDBF FOREIGN KEY (cart_id) REFERENCES cart (id) NOT DEFERRABLE INITIALLY IMMEDIATE)');
$this->addSql('CREATE INDEX IDX_6DDC373A1AD5CDBF ON cart_product (cart_id)');
}
}
}
namespace App\Tests {
use ApiPlatform\Playground\Test\TestGuideTrait;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
final class ComputedFieldTest extends ApiTestCase
{
use TestGuideTrait;
public function testCanSortByComputedField(): void
{
$ascReq = static::createClient()->request('GET', '/carts?sort[totalQuantity]=asc');
$this->assertResponseIsSuccessful();
$asc = $ascReq->toArray();
$this->assertGreaterThan(
$asc['member'][0]['totalQuantity'],
$asc['member'][1]['totalQuantity']
);
}
}
}
namespace App\Fixtures {
use App\Entity\Cart;
use App\Entity\CartProduct;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use function Zenstruck\Foundry\anonymous;
use function Zenstruck\Foundry\repository;
final class CartFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
$cartFactory = anonymous(Cart::class);
if (repository(Cart::class)->count()) {
return;
}
$cartFactory->many(10)->create(fn ($i) => [
'items' => $this->createCartProducts($i),
]);
}
/**
* @return array<CartProduct>
*/
private function createCartProducts($i): array
{
$cartProducts = [];
for ($j = 1; $j <= 10; ++$j) {
$cartProduct = new CartProduct();
$cartProduct->setQuantity((int) abs($j / $i) + 1);
$cartProducts[] = $cartProduct;
}
return $cartProducts;
}
}
}