generateDownloadItemOperation()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
nc 1
nop 2
dl 0
loc 12
ccs 0
cts 9
cp 0
crap 2
rs 9.9666
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\CollectionOperationInterface;
18
use ApiPlatform\Metadata\Get;
19
use ApiPlatform\Metadata\HttpOperation;
20
use ApiPlatform\Metadata\Operation;
21
use ApiPlatform\Metadata\Operation\PathSegmentNameGeneratorInterface;
22
use ApiPlatform\Metadata\Post;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
25
use JetBrains\PhpStorm\Pure;
26
use Silverback\ApiComponentsBundle\Action\Uploadable\DownloadAction;
27
use Silverback\ApiComponentsBundle\Action\Uploadable\UploadAction;
28
use Silverback\ApiComponentsBundle\AttributeReader\UploadableAttributeReaderInterface;
29
30
/**
31
 * Configures API Platform metadata for file resources.
32
 * POST /resource_short_name/upload (multipart/form-data)
33
 * POST /resource_short_name/{id}/upload (multipart/form-data)
34
 * GET  /resource_short_name/{id}/download/{property} (download file).
35
 *
36
 * @author Daniel West <[email protected]>
37
 */
38
class UploadableResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
39
{
40
    private ResourceMetadataCollectionFactoryInterface $decorated;
41
    private UploadableAttributeReaderInterface $uploadableFileManager;
42
    private PathSegmentNameGeneratorInterface $pathSegmentNameGenerator;
43
44
    public function __construct(ResourceMetadataCollectionFactoryInterface $decorated, UploadableAttributeReaderInterface $annotationReader, PathSegmentNameGeneratorInterface $pathSegmentNameGenerator)
45
    {
46
        $this->decorated = $decorated;
47
        $this->uploadableFileManager = $annotationReader;
48
        $this->pathSegmentNameGenerator = $pathSegmentNameGenerator;
49
    }
50
51
    public function create(string $resourceClass): ResourceMetadataCollection
52
    {
53
        $resourceMetadata = $this->decorated->create($resourceClass);
54
        if (!$this->uploadableFileManager->isConfigured($resourceClass)) {
55
            return $resourceMetadata;
56
        }
57
58
        $fields = $this->uploadableFileManager->getConfiguredProperties($resourceClass, false);
59
        $openApiRequestMultipartProperties = [];
60
        foreach ($fields as $field => $configuration) {
61
            $openApiRequestMultipartProperties[$field] = [
62
                'type' => 'string',
63
                'format' => 'binary',
64
            ];
65
        }
66
67
        /** @var ApiResource $resourceMetadatum */
68
        foreach ($resourceMetadata as $resourceMetadatum) {
69
            $resourceShortName = $resourceMetadatum->getShortName();
70
            $pathSegmentName = $this->pathSegmentNameGenerator->getSegmentName($resourceShortName);
71
            $operations = $resourceMetadatum->getOperations();
72
            if (!$operations) {
73
                continue;
74
            }
75
            /** @var Operation $operation */
76
            foreach ($operations as $operation) {
77
                if ($operation instanceof Post) {
78
                    $postUploadOperation = static::generatePostOperation($operation, $openApiRequestMultipartProperties, $pathSegmentName);
79
                    $operations->add(self::generateOperationName($postUploadOperation), $postUploadOperation);
80
                }
81
                if ($operation instanceof Get) {
82
                    $uploadItemOperation = self::generateUploadItemOperation($operation, $openApiRequestMultipartProperties, $pathSegmentName);
83
                    $uploadName = self::generateOperationName($uploadItemOperation);
84
                    $operations->add($uploadName, $uploadItemOperation->withName($uploadName));
85
86
                    $downloadItemOperation = self::generateDownloadItemOperation($operation, $pathSegmentName);
87
                    $downloadName = self::generateOperationName($downloadItemOperation);
88
                    $operations->add($downloadName, $downloadItemOperation->withName($downloadName));
89
                }
90
            }
91
        }
92
93
        return $resourceMetadata;
94
    }
95
96
    #[Pure]
97
    private static function generateOperationName(Operation $operation): string
98
    {
99
        return sprintf(
100
            '_api_%s_%s%s',
101
            $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

101
            $operation->/** @scrutinizer ignore-call */ 
102
                        getUriTemplate(),
Loading history...
102
            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

102
            strtolower($operation->/** @scrutinizer ignore-call */ getMethod()),
Loading history...
103
            $operation instanceof CollectionOperationInterface ? '_collection' : ''
104
        );
105
    }
106
107
    #[Pure]
108
    private static function configurePostOperation(Operation $postOperation, array $openApiRequestMultipartProperties): Operation
109
    {
110
        return $postOperation
111
            ->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

111
            ->/** @scrutinizer ignore-call */ withController(UploadAction::class)
Loading history...
112
            ->withDeserialize(false)
113
            ->withStateless(null)
114
            ->withOpenapiContext([
115
                'requestBody' => [
116
                    'content' => [
117
                        'multipart/form-data' => [
118
                            'schema' => [
119
                                'type' => 'object',
120
                                'properties' => $openApiRequestMultipartProperties,
121
                            ],
122
                        ],
123
                    ],
124
                ],
125
            ]);
126
    }
127
128
    #[Pure]
129
    private static function generatePostOperation(Post $defaultOperation, array $openApiRequestMultipartProperties, string $pathSegmentName): Operation
130
    {
131
        $path = sprintf('/%s/upload', $pathSegmentName);
132
        $newPost = $defaultOperation
133
            ->withUriTemplate($path)
134
            ->withShortName($defaultOperation->getShortName())
0 ignored issues
show
Bug introduced by
It seems like $defaultOperation->getShortName() can also be of type null; however, parameter $shortName of ApiPlatform\Metadata\Metadata::withShortName() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

134
            ->withShortName(/** @scrutinizer ignore-type */ $defaultOperation->getShortName())
Loading history...
135
            ->withRoutePrefix($defaultOperation->getRoutePrefix() ?? '');
136
137
        return self::configurePostOperation($newPost, $openApiRequestMultipartProperties);
138
    }
139
140
    #[Pure]
141
    private static function generateUploadItemOperation(Get $getOperation, array $openApiRequestMultipartProperties, string $pathSegmentName): Operation
142
    {
143
        $path = sprintf('/%s/{id}/upload', $pathSegmentName);
144
        $newUploadPost = $getOperation
145
            ->withUriTemplate($path)
146
            ->withMethod(HttpOperation::METHOD_POST)
147
            ->withShortName($getOperation->getShortName())
0 ignored issues
show
Bug introduced by
It seems like $getOperation->getShortName() can also be of type null; however, parameter $shortName of ApiPlatform\Metadata\Metadata::withShortName() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

147
            ->withShortName(/** @scrutinizer ignore-type */ $getOperation->getShortName())
Loading history...
148
            ->withRoutePrefix($getOperation->getRoutePrefix() ?? '');
149
150
        return self::configurePostOperation($newUploadPost, $openApiRequestMultipartProperties);
151
    }
152
153
    #[Pure]
154
    private static function generateDownloadItemOperation(Get $getOperation, string $pathSegmentName): Operation
155
    {
156
        $downloadPath = sprintf('/%s/{id}/download/{property}', $pathSegmentName);
157
158
        return $getOperation
159
            ->withUriTemplate($downloadPath)
160
            ->withStateless(null)
161
            ->withController(DownloadAction::class)
162
            ->withSerialize(false)
163
            ->withShortName($getOperation->getShortName())
0 ignored issues
show
Bug introduced by
It seems like $getOperation->getShortName() can also be of type null; however, parameter $shortName of ApiPlatform\Metadata\Metadata::withShortName() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

163
            ->withShortName(/** @scrutinizer ignore-type */ $getOperation->getShortName())
Loading history...
164
            ->withRoutePrefix($getOperation->getRoutePrefix() ?? '');
165
    }
166
}
167