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

api-platform / core / 13814792797

12 Mar 2025 03:09PM UTC coverage: 5.889% (-1.4%) from 7.289%
13814792797

Pull #7012

github

web-flow
Merge 199d44919 into 284937039
Pull Request #7012: doc: comment typo in ApiResource.php

10048 of 170615 relevant lines covered (5.89%)

5.17 hits per line

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

90.72
/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'] ?? [];
90✔
46

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

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

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

60
                continue;
63✔
61
            }
62

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

65
            if (\is_array($currentValue) && $currentValue) {
81✔
66
                $operation = $operation->{'with'.$upperKey}(array_merge($value, $currentValue));
81✔
67
            }
68

69
            if (null !== $currentValue || null === $value) {
81✔
70
                continue;
81✔
71
            }
72

73
            $operation = $operation->{'with'.$upperKey}($value);
81✔
74
        }
75

76
        return $operation->withExtraProperties(array_merge($extraProperties, $operation->getExtraProperties()));
90✔
77
    }
78

79
    private function getResourceWithDefaults(string $resourceClass, string $shortName, ApiResource $resource): ApiResource
80
    {
81
        $resource = $resource
90✔
82
            ->withShortName($resource->getShortName() ?? $shortName)
90✔
83
            ->withClass($resourceClass);
90✔
84

85
        return $this->addGlobalDefaults($resource);
90✔
86
    }
87

88
    private function getDefaultHttpOperations($resource): iterable
89
    {
90
        if (enum_exists($resource->getClass())) {
30✔
91
            return new Operations([new GetCollection(paginationEnabled: false), new Get()]);
6✔
92
        }
93

94
        if (($defaultOperations = $this->defaults['operations'] ?? null) && null === $resource->getOperations()) {
24✔
95
            $operations = [];
24✔
96

97
            foreach ($defaultOperations as $defaultOperation) {
24✔
98
                $operation = new $defaultOperation();
24✔
99

100
                if ($operation instanceof Post && $resource->getUriTemplate() && !$resource->getProvider()) {
24✔
101
                    $operation = $operation->withProvider(CreateProvider::class);
×
102
                }
103

104
                $operations[] = $operation;
24✔
105
            }
106

107
            return new Operations($operations);
24✔
108
        }
109

110
        $post = new Post();
×
111
        if ($resource->getUriTemplate() && !$resource->getProvider()) {
×
112
            $post = $post->withProvider(CreateProvider::class);
×
113
        }
114

115
        return [new Get(), new GetCollection(), $post, new Patch(), new Delete()];
×
116
    }
117

118
    private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
119
    {
120
        $operations = enum_exists($resource->getClass()) ? [new QueryCollection(paginationEnabled: false), new Query()] : [new QueryCollection(), new Query(), (new Mutation())->withName('update'), (new DeleteMutation())->withName('delete'), (new Mutation())->withName('create')];
51✔
121
        $graphQlOperations = [];
51✔
122
        foreach ($operations as $operation) {
51✔
123
            [$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
51✔
124
            $graphQlOperations[$key] = $operation;
51✔
125
        }
126

127
        if ($resource->getMercure()) {
51✔
128
            [$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
3✔
129
            $graphQlOperations[$key] = $operation;
3✔
130
        }
131

132
        return $resource->withGraphQlOperations($graphQlOperations);
51✔
133
    }
134

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

144
        $hasQueryOperation = false;
15✔
145
        $hasQueryCollectionOperation = false;
15✔
146
        foreach ($graphQlOperations as $operation) {
15✔
147
            if ($operation instanceof Query && !$operation instanceof QueryCollection) {
12✔
148
                $hasQueryOperation = true;
9✔
149
            }
150
            if ($operation instanceof QueryCollection) {
12✔
151
                $hasQueryCollectionOperation = true;
6✔
152
            }
153
        }
154

155
        if (!$hasQueryOperation) {
15✔
156
            $queryOperation = (new Query())->withNested(true);
6✔
157
            $graphQlOperations[$queryOperation->getName()] = $queryOperation;
6✔
158
        }
159
        if (!$hasQueryCollectionOperation) {
15✔
160
            $queryCollectionOperation = (new QueryCollection())->withNested(true);
9✔
161
            $graphQlOperations[$queryCollectionOperation->getName()] = $queryCollectionOperation;
9✔
162
        }
163

164
        return $resource->withGraphQlOperations($graphQlOperations);
15✔
165
    }
166

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

175
            if (\in_array(lcfirst(substr($methodName, 3)), $ignoredOptions, true)) {
90✔
176
                continue;
21✔
177
            }
178

179
            if (!method_exists($operation, $methodName) || null !== $operation->{$methodName}()) {
90✔
180
                continue;
90✔
181
            }
182

183
            if (null === ($value = $resource->{$methodName}())) {
90✔
184
                continue;
90✔
185
            }
186

187
            $operation = $operation->{'with'.substr($methodName, 3)}($value);
90✔
188
        }
189

190
        $operation = $operation->withExtraProperties(array_merge(
90✔
191
            $resource->getExtraProperties(),
90✔
192
            $operation->getExtraProperties(),
90✔
193
            $generated ? ['generated_operation' => true] : []
90✔
194
        ));
90✔
195

196
        // Add global defaults attributes to the operation
197
        $operation = $this->addGlobalDefaults($operation);
90✔
198

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

204
            if ($operation instanceof Mutation) {
63✔
205
                $operation = $operation->withDescription(ucfirst("{$operation->getName()}s a {$resource->getShortName()}."));
51✔
206
            }
207

208
            return [$operation->getName(), $operation];
63✔
209
        }
210

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

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

220
        $operationName = $operation->getName() ?? $this->getDefaultOperationName($operation, $resource->getClass());
90✔
221

222
        return [
90✔
223
            $operationName,
90✔
224
            $operation,
90✔
225
        ];
90✔
226
    }
227

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

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

237
        return \sprintf(
90✔
238
            '_api_%s_%s%s',
90✔
239
            $path ?: ($operation->getShortName() ?? $this->getDefaultShortname($resourceClass)),
90✔
240
            strtolower($operation->getMethod()),
90✔
241
            $operation instanceof CollectionOperationInterface ? '_collection' : '');
90✔
242
    }
243
}
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