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

api-platform / core / 14246153067

03 Apr 2025 02:56PM UTC coverage: 7.286% (-0.002%) from 7.288%
14246153067

push

github

web-flow
Merge commit from fork

12 of 160 new or added lines in 7 files covered. (7.5%)

2343 existing lines in 152 files now uncovered.

12450 of 170870 relevant lines covered (7.29%)

12.06 hits per line

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

91.92
/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\CreateProvider;
35
use Psr\Log\LoggerInterface;
36

37
trait OperationDefaultsTrait
38
{
39
    private CamelCaseToSnakeCaseNameConverter $camelCaseToSnakeCaseNameConverter;
40
    private array $defaults = [];
41
    private LoggerInterface $logger;
42

43
    private function addGlobalDefaults(ApiResource|Operation $operation): ApiResource|Operation
44
    {
45
        $extraProperties = $this->defaults['extra_properties'] ?? [];
113✔
46

47
        foreach ($this->defaults as $key => $value) {
113✔
48
            if ('operations' === $key) {
104✔
49
                continue;
104✔
50
            }
51

52
            $upperKey = ucfirst($this->camelCaseToSnakeCaseNameConverter->denormalize($key));
104✔
53
            $getter = 'get'.$upperKey;
104✔
54

55
            if (!method_exists($operation, $getter)) {
104✔
56
                if (!isset($extraProperties[$key])) {
84✔
57
                    $extraProperties[$key] = $value;
84✔
58
                }
59

60
                continue;
84✔
61
            }
62

63
            $currentValue = $operation->{$getter}();
104✔
64

65
            if (\is_array($currentValue) && $currentValue) {
104✔
66
                if (\is_string($value)) {
104✔
67
                    $value = [$value];
×
68
                }
69

70
                $operation = $operation->{'with'.$upperKey}(array_merge($value, $currentValue));
104✔
71
            }
72

73
            if (null !== $currentValue || null === $value) {
104✔
74
                continue;
104✔
75
            }
76

77
            $operation = $operation->{'with'.$upperKey}($value);
104✔
78
        }
79

80
        return $operation->withExtraProperties(array_merge($extraProperties, $operation->getExtraProperties()));
113✔
81
    }
82

83
    private function getResourceWithDefaults(string $resourceClass, string $shortName, ApiResource $resource): ApiResource
84
    {
85
        $resource = $resource
113✔
86
            ->withShortName($resource->getShortName() ?? $shortName)
113✔
87
            ->withClass($resourceClass);
113✔
88

89
        return $this->addGlobalDefaults($resource);
113✔
90
    }
91

92
    private function getDefaultHttpOperations($resource): iterable
93
    {
94
        if (enum_exists($resource->getClass())) {
48✔
95
            return new Operations([new GetCollection(paginationEnabled: false), new Get()]);
7✔
96
        }
97

98
        if (($defaultOperations = $this->defaults['operations'] ?? null) && null === $resource->getOperations()) {
42✔
99
            $operations = [];
42✔
100

101
            foreach ($defaultOperations as $defaultOperation) {
42✔
102
                $operation = new $defaultOperation();
42✔
103

104
                if ($operation instanceof Post && $resource->getUriTemplate() && !$resource->getProvider()) {
42✔
UNCOV
105
                    $operation = $operation->withProvider(CreateProvider::class);
1✔
106
                }
107

108
                $operations[] = $operation;
42✔
109
            }
110

111
            return new Operations($operations);
42✔
112
        }
113

114
        $post = new Post();
×
115
        if ($resource->getUriTemplate() && !$resource->getProvider()) {
×
116
            $post = $post->withProvider(CreateProvider::class);
×
117
        }
118

119
        return [new Get(), new GetCollection(), $post, new Patch(), new Delete()];
×
120
    }
121

122
    private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
123
    {
124
        $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')];
69✔
125
        $graphQlOperations = [];
69✔
126
        foreach ($operations as $operation) {
69✔
127
            [$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
69✔
128
            $graphQlOperations[$key] = $operation;
69✔
129
        }
130

131
        if ($resource->getMercure()) {
69✔
132
            [$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
4✔
133
            $graphQlOperations[$key] = $operation;
4✔
134
        }
135

136
        return $resource->withGraphQlOperations($graphQlOperations);
69✔
137
    }
138

139
    /**
140
     * Adds nested query operations if there are no existing query ones on the resource.
141
     * They are needed when the resource is queried inside a root query, using a relation.
142
     * Since the nested argument is used, root queries will not be generated for these operations.
143
     */
144
    private function completeGraphQlOperations(ApiResource $resource): ApiResource
145
    {
146
        $graphQlOperations = $resource->getGraphQlOperations();
19✔
147

148
        $hasQueryOperation = false;
19✔
149
        $hasQueryCollectionOperation = false;
19✔
150
        foreach ($graphQlOperations as $operation) {
19✔
151
            if ($operation instanceof Query && !$operation instanceof QueryCollection) {
14✔
152
                $hasQueryOperation = true;
11✔
153
            }
154
            if ($operation instanceof QueryCollection) {
14✔
155
                $hasQueryCollectionOperation = true;
9✔
156
            }
157
        }
158

159
        if (!$hasQueryOperation) {
19✔
160
            $queryOperation = (new Query())->withNested(true);
9✔
161
            $graphQlOperations[$queryOperation->getName()] = $queryOperation;
9✔
162
        }
163
        if (!$hasQueryCollectionOperation) {
19✔
164
            $queryCollectionOperation = (new QueryCollection())->withNested(true);
15✔
165
            $graphQlOperations[$queryCollectionOperation->getName()] = $queryCollectionOperation;
15✔
166
        }
167

168
        return $resource->withGraphQlOperations($graphQlOperations);
19✔
169
    }
170

171
    private function getOperationWithDefaults(ApiResource $resource, Operation $operation, bool $generated = false, array $ignoredOptions = []): array
172
    {
173
        // Inherit from resource defaults
174
        foreach (get_class_methods($resource) as $methodName) {
113✔
175
            if (!str_starts_with($methodName, 'get')) {
113✔
176
                continue;
113✔
177
            }
178

179
            if (\in_array(lcfirst(substr($methodName, 3)), $ignoredOptions, true)) {
113✔
180
                continue;
23✔
181
            }
182

183
            if (!method_exists($operation, $methodName) || null !== $operation->{$methodName}()) {
113✔
184
                continue;
113✔
185
            }
186

187
            if (null === ($value = $resource->{$methodName}())) {
113✔
188
                continue;
113✔
189
            }
190

191
            $operation = $operation->{'with'.substr($methodName, 3)}($value);
113✔
192
        }
193

194
        $operation = $operation->withExtraProperties(array_merge(
113✔
195
            $resource->getExtraProperties(),
113✔
196
            $operation->getExtraProperties(),
113✔
197
            $generated ? ['generated_operation' => true] : []
113✔
198
        ));
113✔
199

200
        // Add global defaults attributes to the operation
201
        $operation = $this->addGlobalDefaults($operation);
113✔
202

203
        if ($operation instanceof GraphQlOperation) {
113✔
204
            if (!$operation->getName()) {
84✔
205
                throw new RuntimeException('No GraphQL operation name.');
×
206
            }
207

208
            if ($operation instanceof Mutation) {
84✔
209
                $operation = $operation->withDescription(ucfirst("{$operation->getName()}s a {$resource->getShortName()}."));
70✔
210
            }
211

212
            return [$operation->getName(), $operation];
84✔
213
        }
214

215
        if (!$operation instanceof HttpOperation) {
113✔
216
            throw new RuntimeException(\sprintf('Operation should be an instance of "%s"', HttpOperation::class));
×
217
        }
218

219
        if (!$operation->getName() && $operation->getRouteName()) {
113✔
220
            /** @var HttpOperation $operation */
UNCOV
221
            $operation = $operation->withName($operation->getRouteName());
1✔
222
        }
223

224
        $operationName = $operation->getName() ?? $this->getDefaultOperationName($operation, $resource->getClass());
113✔
225

226
        return [
113✔
227
            $operationName,
113✔
228
            $operation,
113✔
229
        ];
113✔
230
    }
231

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

237
    private function getDefaultOperationName(HttpOperation $operation, string $resourceClass): string
238
    {
239
        $path = ($operation->getRoutePrefix() ?? '').($operation->getUriTemplate() ?? '');
111✔
240

241
        return \sprintf(
111✔
242
            '_api_%s_%s%s',
111✔
243
            $path ?: ($operation->getShortName() ?? $this->getDefaultShortname($resourceClass)),
111✔
244
            strtolower($operation->getMethod()),
111✔
245
            $operation instanceof CollectionOperationInterface ? '_collection' : '');
111✔
246
    }
247
}
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