Passed
Push — master ( fbab97...886d01 )
by László
02:56
created

NgFileBaseHandler::saveMonolith()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 10
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
nc 1
cc 1
nop 3
crap 1
1
<?php
2
3
namespace CodingSocks\UploadHandler\Driver;
4
5
use Closure;
6
use CodingSocks\UploadHandler\Helper\ChunkHelpers;
7
use CodingSocks\UploadHandler\Identifier\Identifier;
8
use CodingSocks\UploadHandler\Range\NgFileUploadRange;
9
use CodingSocks\UploadHandler\Response\PercentageJsonResponse;
10
use CodingSocks\UploadHandler\StorageConfig;
11
use Illuminate\Http\JsonResponse;
12
use Illuminate\Http\Request;
13
use Illuminate\Http\UploadedFile;
14
use Illuminate\Support\Arr;
15
use InvalidArgumentException;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
19
20
class NgFileBaseHandler extends BaseHandler
21
{
22 1
    use ChunkHelpers;
23
24
    /**
25
     * @var \CodingSocks\UploadHandler\Identifier\Identifier
26
     */
27
    private $identifier;
28
29
    /**
30
     * NgFileDriver constructor.
31
     *
32
     * @param \CodingSocks\UploadHandler\Identifier\Identifier $identifier
33
     */
34 23
    public function __construct(Identifier $identifier)
35
    {
36 23
        $this->identifier = $identifier;
37 23
    }
38
39
    /**
40
     * @inheritDoc
41
     */
42 22
    public function handle(Request $request, StorageConfig $config, Closure $fileUploaded = null): Response
43
    {
44 22
        if ($this->isRequestMethodIn($request, [Request::METHOD_GET])) {
45 2
            return $this->resume($request, $config);
46
        }
47
48 20
        if ($this->isRequestMethodIn($request, [Request::METHOD_POST])) {
49 12
            return $this->save($request, $config, $fileUploaded);
50
        }
51
52 8
        throw new MethodNotAllowedHttpException([
53 8
            Request::METHOD_GET,
54
            Request::METHOD_POST,
55
        ]);
56
    }
57
58 2
    private function resume(Request $request, StorageConfig $config): Response
59
    {
60 2
        $request->validate([
0 ignored issues
show
Bug introduced by
The call to validate() misses a required argument $...$params.

This check looks for function calls that miss required arguments.

Loading history...
61 2
            'file' => 'required',
62
            'totalSize' => 'required',
63
        ]);
64
65 2
        $originalFilename = $request->get('file');
66 2
        $totalSize = $request->get('totalSize');
67 2
        $uid = $this->identifier->generateFileIdentifier($totalSize, $originalFilename);
68
69 2
        if (!$this->chunkExists($config, $uid)) {
70 1
            return new JsonResponse([
71 1
                'file' => $originalFilename,
72 1
                'size' => 0,
73
            ]);
74
        }
75
76 1
        $chunk = Arr::last($this->chunks($config, $uid));
77 1
        $size = explode('-', basename($chunk))[1] + 1;
78
79 1
        return new JsonResponse([
80 1
            'file' => $originalFilename,
81 1
            'size' => $size,
82
        ]);
83
    }
84
85 12 View Code Duplication
    private function save(Request $request, StorageConfig $config, Closure $fileUploaded = null): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
    {
87 12
        $file = $request->file('file');
88
89 12
        $this->validateUploadedFile($file);
0 ignored issues
show
Bug introduced by
It seems like $file defined by $request->file('file') on line 87 can also be of type array; however, CodingSocks\UploadHandle...:validateUploadedFile() does only seem to accept null|object<Illuminate\Http\UploadedFile>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
90
91 10
        if ($this->isMonolithRequest($request)) {
92 2
            return $this->saveMonolith($file, $config, $fileUploaded);
0 ignored issues
show
Bug introduced by
It seems like $file defined by $request->file('file') on line 87 can also be of type array or null; however, CodingSocks\UploadHandle...Handler::saveMonolith() does only seem to accept object<Illuminate\Http\UploadedFile>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
93
        }
94
95 8
        $this->validateChunkRequest($request);
96
97 4
        return $this->saveChunk($file, $request, $config, $fileUploaded);
0 ignored issues
show
Bug introduced by
It seems like $file defined by $request->file('file') on line 87 can also be of type array or null; however, CodingSocks\UploadHandle...aseHandler::saveChunk() does only seem to accept object<Illuminate\Http\UploadedFile>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
98
    }
99
100 10
    private function isMonolithRequest(Request $request)
101
    {
102 10
        return empty($request->post());
103
    }
104
105
    /**
106
     * @param \Illuminate\Http\Request $request
107
     */
108 8
    private function validateChunkRequest(Request $request): void
109
    {
110 8
        $request->validate([
0 ignored issues
show
Bug introduced by
The call to validate() misses a required argument $...$params.

This check looks for function calls that miss required arguments.

Loading history...
111 8
            '_chunkNumber' => 'required|numeric',
112
            '_chunkSize' => 'required|numeric',
113
            '_totalSize' => 'required|numeric',
114
            '_currentChunkSize' => 'required|numeric',
115
        ]);
116 4
    }
117
118
    /**
119
     * @param \Illuminate\Http\UploadedFile $file
120
     * @param \CodingSocks\UploadHandler\StorageConfig $config
121
     * @param \Closure|null $fileUploaded
122
     *
123
     * @return \Symfony\Component\HttpFoundation\Response
124
     */
125 2 View Code Duplication
    private function saveMonolith(UploadedFile $file, StorageConfig $config, Closure $fileUploaded = null): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
    {
127 2
        $path = $file->store($config->getMergedDirectory(), [
128 2
            'disk' => $config->getDisk(),
129
        ]);
130
131 2
        $this->triggerFileUploadedEvent($config->getDisk(), $path, $fileUploaded);
132
133 2
        return new PercentageJsonResponse(100);
134
    }
135
136
    /**
137
     * @param \Illuminate\Http\UploadedFile $file
138
     * @param \Illuminate\Http\Request $request
139
     * @param \CodingSocks\UploadHandler\StorageConfig $config
140
     * @param \Closure|null $fileUploaded
141
     *
142
     * @return \Symfony\Component\HttpFoundation\Response
143
     */
144 4
    private function saveChunk(UploadedFile $file, Request $request, StorageConfig $config, Closure $fileUploaded = null): Response
145
    {
146
        try {
147 4
            $range = new NgFileUploadRange($request);
148
        } catch (InvalidArgumentException $e) {
149
            throw new BadRequestHttpException($e->getMessage(), $e);
150
        }
151
152 4
        $originalFilename = $file->getClientOriginalName();
153 4
        $totalSize = $request->get('_totalSize');
154 4
        $uid = $this->identifier->generateFileIdentifier($totalSize, $originalFilename);
155
156 4
        $chunks = $this->storeChunk($config, $range, $file, $uid);
157
158 4
        if (!$range->isLast()) {
159 2
            return new PercentageJsonResponse($range->getPercentage());
160
        }
161
162 2
        $targetFilename = $file->hashName();
163
164 2
        $path = $this->mergeChunks($config, $chunks, $targetFilename);
165
166 2
        if ($config->sweep()) {
167
            $this->deleteChunkDirectory($config, $uid);
168
        }
169
170 2
        $this->triggerFileUploadedEvent($config->getDisk(), $path, $fileUploaded);
171
172 2
        return new PercentageJsonResponse(100);
173
    }
174
}
175