Completed
Push — master ( afc775...ef5a6b )
by recca
01:29
created

FileAPI::parseContentRange()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Recca0120\Upload;
4
5
class FileAPI extends Api
6
{
7
    /**
8
     * receive.
9
     *
10
     * @param string $name
11
     * @return \Symfony\Component\HttpFoundation\File\UploadedFile
12
     *
13
     * @throws \Recca0120\Upload\Exceptions\ChunkedResponseException
14
     */
15 4
    public function receive($name)
16
    {
17 4
        $contentDisposition = (string) $this->request->header('content-disposition');
18 4
        if (empty($contentDisposition) === true) {
19 1
            return $this->request->file($name);
20
        }
21
22 3
        list($start, $end, $total) = $this->parseContentRange();
23 3
        $originalName = $this->getOriginalName($contentDisposition);
24 3
        $uuid = $this->request->get('token');
25 3
        $completed = $end >= $total - 1;
26
27 3
        $chunkFile = $this->createChunkFile($originalName, $uuid);
28 3
        $chunkFile->appendStream('php://input', $start);
29
30 3
        return $completed === true
31 2
            ? $chunkFile->createUploadedFile()
32 1
            : $chunkFile->throwException([
33
                'files' => [
34 1
                    'name' => $originalName,
35 1
                    'size' => $end,
36 1
                    'type' => $chunkFile->getMimeType(),
37
                ],
38 3
            ], ['X-Last-Known-Byte' => $end]);
39
    }
40
41
    /**
42
     * getOriginalName.
43
     *
44
     * @param string $contentDisposition
45
     * @return string
46
     */
47 3
    protected function getOriginalName($contentDisposition)
48
    {
49 3
        $originalName = (string) $this->request->get('name');
50 3
        if (empty($originalName) === true) {
51 3
            list($originalName) = sscanf(
52 3
                $contentDisposition,
53 3
                'attachment; filename=%s'
54
            );
55
        }
56
57 3
        return preg_replace('/[\'"]/', '', $originalName);
58
    }
59
60
    /**
61
     * parseContentRange.
62
     *
63
     * @return array
64
     */
65 3
    protected function parseContentRange()
66
    {
67 3
        $contentRange = $this->request->header('content-range');
68 3
        if (empty($contentRange) === false) {
69 2
            return sscanf($contentRange, 'bytes %d-%d/%d');
70
        }
71
72 1
        $total = $end = (int) $this->request->header('content-length');
73
74 1
        return [0, $end, $total];
75
    }
76
}
77