• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 16531587208

25 Jul 2025 09:05PM UTC coverage: 0.0% (-22.1%) from 22.07%
16531587208

Pull #7225

github

web-flow
Merge 23f449a58 into 02a764950
Pull Request #7225: feat: json streamer

0 of 294 new or added lines in 31 files covered. (0.0%)

11514 existing lines in 375 files now uncovered.

0 of 51976 relevant lines covered (0.0%)

0.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/Metadata/Resource/Factory/OperationDefaultsTrait.php
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\Metadata\Resource\Factory;
15

16
use ApiPlatform\Metadata\ApiResource;
17
use ApiPlatform\Metadata\CollectionOperationInterface;
18
use ApiPlatform\Metadata\Delete;
19
use ApiPlatform\Metadata\Exception\RuntimeException;
20
use ApiPlatform\Metadata\Get;
21
use ApiPlatform\Metadata\GetCollection;
22
use ApiPlatform\Metadata\GraphQl\DeleteMutation;
23
use ApiPlatform\Metadata\GraphQl\Mutation;
24
use ApiPlatform\Metadata\GraphQl\Operation as GraphQlOperation;
25
use ApiPlatform\Metadata\GraphQl\Query;
26
use ApiPlatform\Metadata\GraphQl\QueryCollection;
27
use ApiPlatform\Metadata\GraphQl\Subscription;
28
use ApiPlatform\Metadata\HttpOperation;
29
use ApiPlatform\Metadata\Operation;
30
use ApiPlatform\Metadata\Operations;
31
use ApiPlatform\Metadata\Patch;
32
use ApiPlatform\Metadata\Post;
33
use ApiPlatform\Metadata\Util\CamelCaseToSnakeCaseNameConverter;
34
use ApiPlatform\State\ApiResource\Error;
35
use ApiPlatform\State\CreateProvider;
36
use ApiPlatform\Validator\Exception\ValidationException;
37
use Psr\Log\LoggerInterface;
38

39
/**
40
 * @internal since api-platform 4.2
41
 */
42
trait OperationDefaultsTrait
43
{
44
    private CamelCaseToSnakeCaseNameConverter $camelCaseToSnakeCaseNameConverter;
45
    private array $defaults = [];
46
    private LoggerInterface $logger;
47

48
    private function addGlobalDefaults(ApiResource|Operation $operation): ApiResource|Operation
49
    {
50
        // Do not add global defaults for internal resources:
UNCOV
51
        if (\in_array($operation->getClass(), [Error::class, ValidationException::class], true)) {
×
UNCOV
52
            return $operation;
×
53
        }
54

UNCOV
55
        $extraProperties = $this->defaults['extra_properties'] ?? [];
×
56

UNCOV
57
        foreach ($this->defaults as $key => $value) {
×
UNCOV
58
            if ('operations' === $key) {
×
UNCOV
59
                continue;
×
60
            }
61

UNCOV
62
            $upperKey = ucfirst($this->camelCaseToSnakeCaseNameConverter->denormalize($key));
×
UNCOV
63
            $getter = 'get'.$upperKey;
×
64

UNCOV
65
            if (!method_exists($operation, $getter)) {
×
UNCOV
66
                if (!isset($extraProperties[$key])) {
×
UNCOV
67
                    $extraProperties[$key] = $value;
×
68
                }
69

UNCOV
70
                continue;
×
71
            }
72

UNCOV
73
            $currentValue = $operation->{$getter}();
×
74

UNCOV
75
            if (\is_array($currentValue) && $currentValue) {
×
UNCOV
76
                if (\is_string($value)) {
×
77
                    $value = [$value];
×
78
                }
79

UNCOV
80
                $operation = $operation->{'with'.$upperKey}(array_merge($value, $currentValue));
×
81
            }
82

UNCOV
83
            if (null !== $currentValue || null === $value) {
×
UNCOV
84
                continue;
×
85
            }
86

UNCOV
87
            $operation = $operation->{'with'.$upperKey}($value);
×
88
        }
89

UNCOV
90
        return $operation->withExtraProperties(array_merge($extraProperties, $operation->getExtraProperties()));
×
91
    }
92

93
    private function getResourceWithDefaults(string $resourceClass, string $shortName, ApiResource $resource): ApiResource
94
    {
UNCOV
95
        $resource = $resource
×
UNCOV
96
            ->withShortName($resource->getShortName() ?? $shortName)
×
UNCOV
97
            ->withClass($resourceClass);
×
98

UNCOV
99
        return $this->addGlobalDefaults($resource);
×
100
    }
101

102
    /**
103
     * @return Operations<HttpOperation>|array<int,HttpOperation>
104
     */
105
    private function getDefaultHttpOperations(ApiResource $resource): iterable
106
    {
UNCOV
107
        if (enum_exists($resource->getClass())) {
×
UNCOV
108
            return new Operations([new GetCollection(paginationEnabled: false), new Get()]);
×
109
        }
110

UNCOV
111
        if (($defaultOperations = $this->defaults['operations'] ?? null) && null === $resource->getOperations()) {
×
UNCOV
112
            $operations = [];
×
113

UNCOV
114
            foreach ($defaultOperations as $defaultOperation) {
×
UNCOV
115
                $operation = new $defaultOperation();
×
116

UNCOV
117
                if ($operation instanceof Post && $resource->getUriTemplate() && !$resource->getProvider()) {
×
UNCOV
118
                    $operation = $operation->withProvider(CreateProvider::class);
×
119
                }
120

UNCOV
121
                $operations[] = $operation;
×
122
            }
123

UNCOV
124
            return new Operations($operations);
×
125
        }
126

127
        $post = new Post();
×
128
        if ($resource->getUriTemplate() && !$resource->getProvider()) {
×
129
            $post = $post->withProvider(CreateProvider::class);
×
130
        }
131

132
        return [new Get(), new GetCollection(), $post, new Patch(), new Delete()];
×
133
    }
134

135
    private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
136
    {
UNCOV
137
        $operations = enum_exists($resource->getClass()) ? [new Query(), new QueryCollection(paginationEnabled: false)] : [new Query(), new QueryCollection(), (new Mutation())->withName('update'), (new DeleteMutation())->withName('delete'), (new Mutation())->withName('create')];
×
UNCOV
138
        $graphQlOperations = [];
×
UNCOV
139
        foreach ($operations as $operation) {
×
UNCOV
140
            [$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
×
UNCOV
141
            $graphQlOperations[$key] = $operation;
×
142
        }
143

UNCOV
144
        if ($resource->getMercure()) {
×
UNCOV
145
            [$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
×
UNCOV
146
            $graphQlOperations[$key] = $operation;
×
147
        }
148

UNCOV
149
        return $resource->withGraphQlOperations($graphQlOperations);
×
150
    }
151

152
    /**
153
     * Adds nested query operations if there are no existing query ones on the resource.
154
     * They are needed when the resource is queried inside a root query, using a relation.
155
     * Since the nested argument is used, root queries will not be generated for these operations.
156
     */
157
    private function completeGraphQlOperations(ApiResource $resource): ApiResource
158
    {
UNCOV
159
        $graphQlOperations = $resource->getGraphQlOperations();
×
160

UNCOV
161
        $hasQueryOperation = false;
×
UNCOV
162
        $hasQueryCollectionOperation = false;
×
UNCOV
163
        foreach ($graphQlOperations as $operation) {
×
UNCOV
164
            if ($operation instanceof Query && !$operation instanceof QueryCollection) {
×
UNCOV
165
                $hasQueryOperation = true;
×
166
            }
UNCOV
167
            if ($operation instanceof QueryCollection) {
×
UNCOV
168
                $hasQueryCollectionOperation = true;
×
169
            }
170
        }
171

UNCOV
172
        if (!$hasQueryOperation) {
×
UNCOV
173
            $queryOperation = (new Query())->withNested(true);
×
UNCOV
174
            $graphQlOperations[$queryOperation->getName()] = $queryOperation;
×
175
        }
UNCOV
176
        if (!$hasQueryCollectionOperation) {
×
UNCOV
177
            $queryCollectionOperation = (new QueryCollection())->withNested(true);
×
UNCOV
178
            $graphQlOperations[$queryCollectionOperation->getName()] = $queryCollectionOperation;
×
179
        }
180

UNCOV
181
        return $resource->withGraphQlOperations($graphQlOperations);
×
182
    }
183

184
    /**
185
     * @param list<string> $ignoredOptions
186
     *
187
     * @return array<int,mixed>
188
     */
189
    private function getOperationWithDefaults(ApiResource $resource, Operation $operation, bool $generated = false, array $ignoredOptions = []): array
190
    {
UNCOV
191
        $operation = $operation->cascadeFromResource($resource, $ignoredOptions)->withExtraProperties(array_merge(
×
UNCOV
192
            $resource->getExtraProperties(),
×
UNCOV
193
            $operation->getExtraProperties(),
×
UNCOV
194
            $generated ? ['generated_operation' => true] : []
×
UNCOV
195
        ));
×
196

197
        // Add global defaults attributes to the operation
UNCOV
198
        $operation = $this->addGlobalDefaults($operation);
×
199

UNCOV
200
        if ($operation instanceof GraphQlOperation) {
×
UNCOV
201
            if (!$operation->getName()) {
×
202
                throw new RuntimeException('No GraphQL operation name.');
×
203
            }
204

UNCOV
205
            if ($operation instanceof Mutation) {
×
UNCOV
206
                $operation = $operation->withDescription(ucfirst("{$operation->getName()}s a {$resource->getShortName()}."));
×
207
            }
208

UNCOV
209
            return [$operation->getName(), $operation];
×
210
        }
211

UNCOV
212
        if (!$operation instanceof HttpOperation) {
×
213
            throw new RuntimeException(\sprintf('Operation should be an instance of "%s"', HttpOperation::class));
×
214
        }
215

UNCOV
216
        if (!$operation->getName() && $operation->getRouteName()) {
×
217
            /** @var HttpOperation $operation */
218
            $operation = $operation->withName($operation->getRouteName());
×
219
        }
220

UNCOV
221
        $operationName = $operation->getName() ?? $this->getDefaultOperationName($operation, $resource->getClass());
×
222

UNCOV
223
        return [
×
UNCOV
224
            $operationName,
×
UNCOV
225
            $operation,
×
UNCOV
226
        ];
×
227
    }
228

229
    private function getDefaultShortname(string $resourceClass): string
230
    {
231
        return (false !== $pos = strrpos($resourceClass, '\\')) ? substr($resourceClass, $pos + 1) : $resourceClass;
×
232
    }
233

234
    private function getDefaultOperationName(HttpOperation $operation, string $resourceClass): string
235
    {
UNCOV
236
        $path = ($operation->getRoutePrefix() ?? '').($operation->getUriTemplate() ?? '');
×
237

UNCOV
238
        return \sprintf(
×
UNCOV
239
            '_api_%s_%s%s',
×
UNCOV
240
            $path ?: ($operation->getShortName() ?? $this->getDefaultShortname($resourceClass)),
×
UNCOV
241
            strtolower($operation->getMethod()),
×
UNCOV
242
            $operation instanceof CollectionOperationInterface ? '_collection' : ''
×
UNCOV
243
        );
×
244
    }
245
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc