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

api-platform / core / 14992745685

13 May 2025 09:09AM UTC coverage: 27.459% (+3.8%) from 23.685%
14992745685

push

github

web-flow
fix(metadata): xml PHPize HTTP cache headers (#7140)

0 of 1 new or added line in 1 file covered. (0.0%)

2013 existing lines in 145 files now uncovered.

13449 of 48979 relevant lines covered (27.46%)

74.47 hits per line

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

92.08
/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
trait OperationDefaultsTrait
40
{
41
    private CamelCaseToSnakeCaseNameConverter $camelCaseToSnakeCaseNameConverter;
42
    private array $defaults = [];
43
    private LoggerInterface $logger;
44

45
    private function addGlobalDefaults(ApiResource|Operation $operation): ApiResource|Operation
46
    {
47
        // Do not add global defaults for internal resources:
48
        if (\in_array($operation->getClass(), [Error::class, ValidationException::class], true)) {
138✔
49
            return $operation;
6✔
50
        }
51

52
        $extraProperties = $this->defaults['extra_properties'] ?? [];
135✔
53

54
        foreach ($this->defaults as $key => $value) {
135✔
55
            if ('operations' === $key) {
129✔
56
                continue;
129✔
57
            }
58

59
            $upperKey = ucfirst($this->camelCaseToSnakeCaseNameConverter->denormalize($key));
129✔
60
            $getter = 'get'.$upperKey;
129✔
61

62
            if (!method_exists($operation, $getter)) {
129✔
63
                if (!isset($extraProperties[$key])) {
104✔
64
                    $extraProperties[$key] = $value;
104✔
65
                }
66

67
                continue;
104✔
68
            }
69

70
            $currentValue = $operation->{$getter}();
129✔
71

72
            if (\is_array($currentValue) && $currentValue) {
129✔
73
                if (\is_string($value)) {
129✔
74
                    $value = [$value];
×
75
                }
76

77
                $operation = $operation->{'with'.$upperKey}(array_merge($value, $currentValue));
129✔
78
            }
79

80
            if (null !== $currentValue || null === $value) {
129✔
81
                continue;
129✔
82
            }
83

84
            $operation = $operation->{'with'.$upperKey}($value);
129✔
85
        }
86

87
        return $operation->withExtraProperties(array_merge($extraProperties, $operation->getExtraProperties()));
135✔
88
    }
89

90
    private function getResourceWithDefaults(string $resourceClass, string $shortName, ApiResource $resource): ApiResource
91
    {
92
        $resource = $resource
138✔
93
            ->withShortName($resource->getShortName() ?? $shortName)
138✔
94
            ->withClass($resourceClass);
138✔
95

96
        return $this->addGlobalDefaults($resource);
138✔
97
    }
98

99
    private function getDefaultHttpOperations($resource): iterable
100
    {
101
        if (enum_exists($resource->getClass())) {
57✔
102
            return new Operations([new GetCollection(paginationEnabled: false), new Get()]);
7✔
103
        }
104

105
        if (($defaultOperations = $this->defaults['operations'] ?? null) && null === $resource->getOperations()) {
53✔
106
            $operations = [];
53✔
107

108
            foreach ($defaultOperations as $defaultOperation) {
53✔
109
                $operation = new $defaultOperation();
53✔
110

111
                if ($operation instanceof Post && $resource->getUriTemplate() && !$resource->getProvider()) {
53✔
UNCOV
112
                    $operation = $operation->withProvider(CreateProvider::class);
2✔
113
                }
114

115
                $operations[] = $operation;
53✔
116
            }
117

118
            return new Operations($operations);
53✔
119
        }
120

121
        $post = new Post();
×
122
        if ($resource->getUriTemplate() && !$resource->getProvider()) {
×
123
            $post = $post->withProvider(CreateProvider::class);
×
124
        }
125

126
        return [new Get(), new GetCollection(), $post, new Patch(), new Delete()];
×
127
    }
128

129
    private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
130
    {
131
        $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')];
92✔
132
        $graphQlOperations = [];
92✔
133
        foreach ($operations as $operation) {
92✔
134
            [$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
92✔
135
            $graphQlOperations[$key] = $operation;
92✔
136
        }
137

138
        if ($resource->getMercure()) {
92✔
139
            [$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
4✔
140
            $graphQlOperations[$key] = $operation;
4✔
141
        }
142

143
        return $resource->withGraphQlOperations($graphQlOperations);
92✔
144
    }
145

146
    /**
147
     * Adds nested query operations if there are no existing query ones on the resource.
148
     * They are needed when the resource is queried inside a root query, using a relation.
149
     * Since the nested argument is used, root queries will not be generated for these operations.
150
     */
151
    private function completeGraphQlOperations(ApiResource $resource): ApiResource
152
    {
153
        $graphQlOperations = $resource->getGraphQlOperations();
22✔
154

155
        $hasQueryOperation = false;
22✔
156
        $hasQueryCollectionOperation = false;
22✔
157
        foreach ($graphQlOperations as $operation) {
22✔
158
            if ($operation instanceof Query && !$operation instanceof QueryCollection) {
15✔
159
                $hasQueryOperation = true;
13✔
160
            }
161
            if ($operation instanceof QueryCollection) {
15✔
162
                $hasQueryCollectionOperation = true;
10✔
163
            }
164
        }
165

166
        if (!$hasQueryOperation) {
22✔
167
            $queryOperation = (new Query())->withNested(true);
11✔
168
            $graphQlOperations[$queryOperation->getName()] = $queryOperation;
11✔
169
        }
170
        if (!$hasQueryCollectionOperation) {
22✔
171
            $queryCollectionOperation = (new QueryCollection())->withNested(true);
18✔
172
            $graphQlOperations[$queryCollectionOperation->getName()] = $queryCollectionOperation;
18✔
173
        }
174

175
        return $resource->withGraphQlOperations($graphQlOperations);
22✔
176
    }
177

178
    private function getOperationWithDefaults(ApiResource $resource, Operation $operation, bool $generated = false, array $ignoredOptions = []): array
179
    {
180
        // Inherit from resource defaults
181
        foreach (get_class_methods($resource) as $methodName) {
138✔
182
            if (!str_starts_with($methodName, 'get')) {
138✔
183
                continue;
138✔
184
            }
185

186
            if (\in_array(lcfirst(substr($methodName, 3)), $ignoredOptions, true)) {
138✔
187
                continue;
40✔
188
            }
189

190
            if (!method_exists($operation, $methodName) || null !== $operation->{$methodName}()) {
138✔
191
                continue;
138✔
192
            }
193

194
            if (null === ($value = $resource->{$methodName}())) {
138✔
195
                continue;
138✔
196
            }
197

198
            $operation = $operation->{'with'.substr($methodName, 3)}($value);
138✔
199
        }
200

201
        $operation = $operation->withExtraProperties(array_merge(
138✔
202
            $resource->getExtraProperties(),
138✔
203
            $operation->getExtraProperties(),
138✔
204
            $generated ? ['generated_operation' => true] : []
138✔
205
        ));
138✔
206

207
        // Add global defaults attributes to the operation
208
        $operation = $this->addGlobalDefaults($operation);
138✔
209

210
        if ($operation instanceof GraphQlOperation) {
138✔
211
            if (!$operation->getName()) {
109✔
212
                throw new RuntimeException('No GraphQL operation name.');
×
213
            }
214

215
            if ($operation instanceof Mutation) {
109✔
216
                $operation = $operation->withDescription(ucfirst("{$operation->getName()}s a {$resource->getShortName()}."));
97✔
217
            }
218

219
            return [$operation->getName(), $operation];
109✔
220
        }
221

222
        if (!$operation instanceof HttpOperation) {
138✔
223
            throw new RuntimeException(\sprintf('Operation should be an instance of "%s"', HttpOperation::class));
×
224
        }
225

226
        if (!$operation->getName() && $operation->getRouteName()) {
138✔
227
            /** @var HttpOperation $operation */
UNCOV
228
            $operation = $operation->withName($operation->getRouteName());
2✔
229
        }
230

231
        $operationName = $operation->getName() ?? $this->getDefaultOperationName($operation, $resource->getClass());
138✔
232

233
        return [
138✔
234
            $operationName,
138✔
235
            $operation,
138✔
236
        ];
138✔
237
    }
238

239
    private function getDefaultShortname(string $resourceClass): string
240
    {
241
        return (false !== $pos = strrpos($resourceClass, '\\')) ? substr($resourceClass, $pos + 1) : $resourceClass;
×
242
    }
243

244
    private function getDefaultOperationName(HttpOperation $operation, string $resourceClass): string
245
    {
246
        $path = ($operation->getRoutePrefix() ?? '').($operation->getUriTemplate() ?? '');
135✔
247

248
        return \sprintf(
135✔
249
            '_api_%s_%s%s',
135✔
250
            $path ?: ($operation->getShortName() ?? $this->getDefaultShortname($resourceClass)),
135✔
251
            strtolower($operation->getMethod()),
135✔
252
            $operation instanceof CollectionOperationInterface ? '_collection' : '');
135✔
253
    }
254
}
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