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

api-platform / core / 13453526416

21 Feb 2025 09:07AM UTC coverage: 7.29%. Remained the same
13453526416

push

github

web-flow
fix(laravel): handle route prefix (#6978)

fixes #6969

0 of 9 new or added lines in 4 files covered. (0.0%)

807 existing lines in 82 files now uncovered.

12436 of 170599 relevant lines covered (7.29%)

11.99 hits per line

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

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

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

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

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

60
                continue;
87✔
61
            }
62

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

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

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

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

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

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

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

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

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

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

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

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

107
            return new Operations($operations);
42✔
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')];
69✔
121
        $graphQlOperations = [];
69✔
122
        foreach ($operations as $operation) {
69✔
123
            [$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
69✔
124
            $graphQlOperations[$key] = $operation;
69✔
125
        }
126

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

132
        return $resource->withGraphQlOperations($graphQlOperations);
69✔
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();
22✔
143

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

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

164
        return $resource->withGraphQlOperations($graphQlOperations);
22✔
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) {
116✔
171
            if (!str_starts_with($methodName, 'get')) {
116✔
172
                continue;
116✔
173
            }
174

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

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

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

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

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

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

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

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

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

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

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

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

222
        return [
116✔
223
            $operationName,
116✔
224
            $operation,
116✔
225
        ];
116✔
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() ?? '');
114✔
236

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