Completed
Branch master (95c7f4)
by Asmir
03:33
created

MultipartRequestListener   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 92.68%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 9
dl 0
loc 149
ccs 76
cts 82
cp 0.9268
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A onKernelRequest() 0 16 3
C processRequest() 0 73 12
A mergeFormArray() 0 20 4
A parseKey() 0 9 1
A isDispositionFormData() 0 7 2
A setRequestContent() 0 6 1
1
<?php
2
3
namespace Goetas\MultipartUploadBundle\EventListener;
4
5
use Riverline\MultiPartParser\Converters\HttpFoundation;
6
use Symfony\Component\HttpFoundation\File\UploadedFile;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
11
class MultipartRequestListener
12
{
13
    /**
14
     * @var bool
15
     */
16
    private $injectFirstPart;
17
18 13
    public function __construct(bool $injectFirstPart = true)
19
    {
20 13
        $this->injectFirstPart = $injectFirstPart;
21 13
    }
22
23 13
    public function onKernelRequest(GetResponseEvent $event)
24
    {
25
        try {
26 13
            $this->processRequest($event->getRequest());
27 4
        } catch (\LogicException $e) {
28 4
            $message = 'Bad Request';
29
30 4
            if ($e->getMessage()) {
31 4
                $message .= ': ' . $e->getMessage();
32
            }
33
34 4
            $response = new Response($message, 400);
35
36 4
            $event->setResponse($response);
37
        }
38 13
    }
39
40 13
    private function processRequest(Request $request)
41
    {
42 13
        $contentType = $request->headers->get('Content-Type');
43 13
        if (0 === strpos($contentType, 'multipart/')) {
44
45 13
            $streamedPart = HttpFoundation::convert($request);
46
47 9
            if ($this->injectFirstPart === true) {
48 8
                $request->headers->remove('Content-Type');
49 8
                $request->headers->remove('Content-Length');
50
            }
51 9
            $attachments = [];
52 9
            $relatedParts = $streamedPart->getParts();
53
54 9
            foreach ($relatedParts as $k => $part) {
55
56 9
                if ($this->injectFirstPart === true && 0 === $k) {
57 8
                    $request->headers->add($part->getHeaders());
58 8
                    if ('application/x-www-form-urlencoded' === $part->getHeader('Content-Type')) {
59
                        $output = [];
60
                        parse_str($part->getBody(), $output);
61
                        $request->request->add($output);
0 ignored issues
show
Bug introduced by
It seems like $output can also be of type null; however, Symfony\Component\HttpFo...ion\ParameterBag::add() does only seem to accept array, 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...
62
                    } else {
63 8
                        $this->setRequestContent($request, $part->getBody());
64
                    }
65 8
                    continue;
66
                }
67
68 5
                $contentDisposition = $part->getHeader('Content-Disposition');
69
70 5
                if ($contentDisposition === null) {
71 2
                    continue;
72
                }
73
74 3
                $fileName = $part->getFileName();
75
76 3
                if ($fileName!== null) {
77 2
                    $fp = tmpfile();
78 2
                    fwrite($fp, $part->getBody());
79 2
                    rewind($fp);
80
81 2
                    $tmpPath = stream_get_meta_data($fp)['uri'];
82
83 2
                    $ref = new \ReflectionClass('Symfony\Component\HttpFoundation\File\UploadedFile');
84 2
                    $params = $ref->getConstructor()->getParameters();
85 2
                    if ('error' === $params[3]->getName()) { // symfony 4
86 2
                        $file = new UploadedFile($tmpPath, urldecode($fileName), $part->getMimeType(), null, true);
87
                    } else { // symfony < 4
88
                        $file = new UploadedFile($tmpPath, urldecode($fileName), $part->getMimeType(), filesize($tmpPath), null, false);
89
                    }
90 2
                    @$file->ref = $fp;
0 ignored issues
show
Bug introduced by
The property ref does not seem to exist in Symfony\Component\HttpFoundation\File\UploadedFile.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
91 2
                    $attachments[] = $file;
92
                }
93
94 3
                if (($formName = $this->isDispositionFormData($contentDisposition)) !== null) {
95 2
                    $formPath = $this->parseKey($formName);
96
97 2
                    if ($fileName !== null) {
98 1
                        $files = $request->files->all();
99 1
                        $files = $this->mergeFormArray($files, $formPath, $file);
0 ignored issues
show
Bug introduced by
The variable $file does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
100 1
                        $request->files->replace($files);
101
                    } else {
102 1
                        $data = $request->request->all();
103 1
                        $data = $this->mergeFormArray($data, $formPath, $part->getBody());
104 3
                        $request->request->replace($data);
105
                    }
106
                }
107
            }
108
109 9
            $request->attributes->set('attachments', $attachments);
110 9
            $request->attributes->set('related-parts', $relatedParts);
111
        }
112 9
    }
113
114 2
    protected function mergeFormArray($array, $path, $data)
115
    {
116 2
        if (count($path) > 0) {
117 2
            $key = array_shift($path);
118
119 2
            if (!is_array($array)) {
120
                $array = [];
121
            }
122
123 2
            if (!empty($key)) {
124 2
                $array[$key] = $this->mergeFormArray($array[$key] ?? [], $path, $data);
125
            } else {
126 2
                $array[] = $data;
127
            }
128
129 2
            return $array;
130
        }
131
132
        return $data;
133
    }
134
135 2
    private function parseKey($key)
136
    {
137 2
        return array_map(
138
            function ($v) {
139 2
                return trim($v, ']');
140 2
            },
141 2
            explode('[', $key)
142
        );
143
    }
144
145 3
    private function isDispositionFormData($value)
146
    {
147 3
        if (preg_match('/(?:^|form-data;\s*)name="?([^";]+)("|;|$)/', $value, $matches)) {
148 2
            return trim($matches[1]);
149
        }
150 1
        return null;
151
    }
152
153 8
    private function setRequestContent(Request $request, $content)
154
    {
155 8
        $p = new \ReflectionProperty(Request::class, 'content');
156 8
        $p->setAccessible(true);
157 8
        $p->setValue($request, $content);
158 8
    }
159
}
160