Test Failed
Pull Request — main (#139)
by Daniel
16:46
created

configurePostOperation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 12
nc 1
nop 2
dl 0
loc 14
rs 9.8666
c 1
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
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 Silverback\ApiComponentsBundle\ApiPlatform\Metadata\Resource;
15
16
use ApiPlatform\Metadata\ApiResource;
17
use ApiPlatform\Metadata\Get;
18
use ApiPlatform\Metadata\Operation;
19
use ApiPlatform\Metadata\Post;
20
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
21
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
22
use ApiPlatform\Operation\PathSegmentNameGeneratorInterface;
23
use JetBrains\PhpStorm\Pure;
24
use Silverback\ApiComponentsBundle\Action\Uploadable\DownloadAction;
25
use Silverback\ApiComponentsBundle\Action\Uploadable\UploadAction;
26
use Silverback\ApiComponentsBundle\AttributeReader\UploadableAttributeReaderInterface;
27
28
/**
29
 * Configures API Platform metadata for file resources.
30
 * POST /resource_short_name/upload (multipart/form-data)
31
 * POST /resource_short_name/{id}/upload (multipart/form-data)
32
 * GET  /resource_short_name/{id}/download/{property} (download file).
33
 *
34
 * @author Daniel West <[email protected]>
35
 */
36
class UploadableResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
37
{
38
    private ResourceMetadataCollectionFactoryInterface $decorated;
39
    private UploadableAttributeReaderInterface $uploadableFileManager;
40
    private PathSegmentNameGeneratorInterface $pathSegmentNameGenerator;
41
42
    public function __construct(ResourceMetadataCollectionFactoryInterface $decorated, UploadableAttributeReaderInterface $annotationReader, PathSegmentNameGeneratorInterface $pathSegmentNameGenerator)
43
    {
44
        $this->decorated = $decorated;
45
        $this->uploadableFileManager = $annotationReader;
46
        $this->pathSegmentNameGenerator = $pathSegmentNameGenerator;
47
    }
48
49
    public function create(string $resourceClass): ResourceMetadataCollection
50
    {
51
        $resourceMetadata = $this->decorated->create($resourceClass);
52
        if (!$this->uploadableFileManager->isConfigured($resourceClass)) {
53
            return $resourceMetadata;
54
        }
55
56
        $fields = $this->uploadableFileManager->getConfiguredProperties($resourceClass, false);
57
        $openApiRequestMultipartProperties = [];
58
        foreach ($fields as $field => $configuration) {
59
            $openApiRequestMultipartProperties[$field] = [
60
                'type' => 'string',
61
                'format' => 'binary',
62
            ];
63
        }
64
65
        /** @var ApiResource $resourceMetadatum */
66
        foreach ($resourceMetadata as $resourceMetadatum) {
67
            $resourceShortName = $resourceMetadatum->getShortName();
68
            $pathSegmentName = $this->pathSegmentNameGenerator->getSegmentName($resourceShortName);
69
            $operations = $resourceMetadatum->getOperations();
70
            if (!$operations) {
71
                continue;
72
            }
73
            /** @var Operation $operation */
74
            foreach ($operations as $operation) {
75
                if ($operation instanceof Post) {
76
                    $postUploadOperation = static::generatePostOperation($operation, $openApiRequestMultipartProperties, $pathSegmentName);
77
                    $operations->add(self::generateOperationName($postUploadOperation), $postUploadOperation);
78
                }
79
                if ($operation instanceof Get) {
80
                    $uploadItemOperation = self::generateUploadItemOperation($operation, $openApiRequestMultipartProperties, $pathSegmentName);
81
                    $operations->add(self::generateOperationName($uploadItemOperation), $uploadItemOperation);
82
83
                    $downloadItemOperation = self::generateDownloadItemOperation($operation, $pathSegmentName);
84
                    $operations->add(self::generateOperationName($downloadItemOperation), $downloadItemOperation);
85
                }
86
            }
87
        }
88
89
        return $resourceMetadata;
90
    }
91
92
    #[Pure]
93
    private static function generateOperationName(Operation $operation): string
94
    {
95
        return sprintf(
96
            '_api_%s_%s%s',
97
            $operation->getUriTemplate(),
0 ignored issues
show
Bug introduced by
The method getUriTemplate() does not exist on ApiPlatform\Metadata\Operation. It seems like you code against a sub-type of ApiPlatform\Metadata\Operation such as ApiPlatform\Metadata\HttpOperation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

97
            $operation->/** @scrutinizer ignore-call */ 
98
                        getUriTemplate(),
Loading history...
98
            strtolower($operation->getMethod()),
0 ignored issues
show
Bug introduced by
The method getMethod() does not exist on ApiPlatform\Metadata\Operation. It seems like you code against a sub-type of ApiPlatform\Metadata\Operation such as ApiPlatform\Metadata\HttpOperation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

98
            strtolower($operation->/** @scrutinizer ignore-call */ getMethod()),
Loading history...
99
            $operation->isCollection() ? '_collection' : ''
0 ignored issues
show
Bug introduced by
The method isCollection() does not exist on ApiPlatform\Metadata\Operation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

99
            $operation->/** @scrutinizer ignore-call */ 
100
                        isCollection() ? '_collection' : ''

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
100
        );
101
    }
102
103
    #[Pure]
104
    private static function configurePostOperation(Operation $postOperation, array $openApiRequestMultipartProperties): Operation
105
    {
106
        return $postOperation
107
            ->withController(UploadAction::class)
0 ignored issues
show
Bug introduced by
The method withController() does not exist on ApiPlatform\Metadata\Operation. It seems like you code against a sub-type of ApiPlatform\Metadata\Operation such as ApiPlatform\Metadata\HttpOperation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

107
            ->/** @scrutinizer ignore-call */ withController(UploadAction::class)
Loading history...
108
            ->withDeserialize(false)
109
            ->withStateless(null)
110
            ->withOpenapiContext([
111
                'requestBody' => [
112
                    'content' => [
113
                        'multipart/form-data' => [
114
                            'schema' => [
115
                                'type' => 'object',
116
                                'properties' => $openApiRequestMultipartProperties,
117
                            ],
118
                        ],
119
                    ],
120
                ],
121
            ]);
122
    }
123
124
    #[Pure]
125
    private static function generatePostOperation(Post $defaultOperation, array $openApiRequestMultipartProperties, string $pathSegmentName): Operation
126
    {
127
        $path = sprintf('/%s/upload', $pathSegmentName);
128
        $newPost = $defaultOperation
129
            ->withUriTemplate($path)
130
            ->withShortName($defaultOperation->getShortName())
131
            ->withRoutePrefix($defaultOperation->getRoutePrefix() ?? '');
132
133
        return self::configurePostOperation($newPost, $openApiRequestMultipartProperties);
134
    }
135
136
    #[Pure]
137
    private static function generateUploadItemOperation(Get $getOperation, array $openApiRequestMultipartProperties, string $pathSegmentName): Operation
138
    {
139
        $path = sprintf('/%s/{id}/upload', $pathSegmentName);
140
        $newUploadPost = $getOperation
141
            ->withUriTemplate($path)
142
            ->withMethod(Operation::METHOD_POST)
0 ignored issues
show
Bug introduced by
The constant ApiPlatform\Metadata\Operation::METHOD_POST was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
143
            ->withShortName($getOperation->getShortName())
144
            ->withRoutePrefix($getOperation->getRoutePrefix() ?? '');
145
146
        return self::configurePostOperation($newUploadPost, $openApiRequestMultipartProperties);
147
    }
148
149
    #[Pure]
150
    private static function generateDownloadItemOperation(Get $getOperation, string $pathSegmentName): Operation
151
    {
152
        $downloadPath = sprintf('/%s/{id}/download/{property}', $pathSegmentName);
153
154
        return $getOperation
155
            ->withUriTemplate($downloadPath)
156
            ->withStateless(null)
157
            ->withController(DownloadAction::class)
158
            ->withSerialize(false);
159
    }
160
}
161