Skip to content

Commit a598f39

Browse files
committed
feat(metadata): cascade resource to operation
1 parent 1b3ab0e commit a598f39

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Metadata/ApiResource.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
class ApiResource extends Metadata
3333
{
3434
use WithResourceTrait;
35+
use CascadeToOperationsTrait;
3536

3637
protected ?Operations $operations;
3738

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
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\Metadata;
15+
16+
/**
17+
* @phpstan-require-extends ApiResource
18+
*/
19+
trait CascadeToOperationsTrait
20+
{
21+
public function cascadeToOperations(): static
22+
{
23+
if (null === ($currentOperations = $this->getOperations())) {
24+
return $this;
25+
}
26+
27+
$newOperations = new Operations();
28+
foreach ($currentOperations as $key => $operation) {
29+
foreach (get_class_methods($operation) as $method) {
30+
if (!preg_match('/^(?:get|is|can)(.*)$/', $method, $matches)) {
31+
continue;
32+
}
33+
34+
$propertyName = $matches[1];
35+
$wither = 'with'.$propertyName;
36+
37+
if ($operation->{$method}() !== null) {
38+
continue;
39+
}
40+
41+
if (!method_exists($this, $method) || null === ($v = $this->{$method}())) {
42+
continue;
43+
}
44+
45+
$operation = $operation->{$wither}($v);
46+
}
47+
48+
$newOperations->add($key, $operation);
49+
}
50+
51+
$newResource = clone $this;
52+
53+
return $newResource->withOperations($newOperations);
54+
}
55+
}

0 commit comments

Comments
 (0)