Test Failed
Push — master ( b2d464...e1b9bb )
by Erandir
02:06
created

FormData::next()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace PlugHttp\Body;
4
5
use PlugHttp\Globals\Server;
6
use PlugHttp\Utils\ContentHelper;
7
8
class FormData implements Handler, Advancer
9
{
10
	private Handler $handler;
11
12
	private array $currentData;
13
14
	public function __construct()
15
    {
16
        $this->currentData = [];
17
    }
18
19
    public function getBody($content): array
20
	{
21
        $boundary = substr($content, 0, strpos($content, "\r\n"));
22
        $parts = array_slice(explode($boundary, $content), 1);
23
24
        foreach ($parts as $part) {
25
            preg_match_all('/"(.+)"+\s+([^\t]+)/', $part, $matches);
26
27
            $this->handleBodySent($matches);
28
        }
29
30
        return $this->currentData;
31
	}
32
33
    private function handleBodySent(array $matches): void
34
    {
35
        foreach ($matches[1] as $key => $match) {
36
            $matchKey = str_replace(["'", '"'], '', $match);
37
38
            $this->currentData[$matchKey] = substr($matches[2][$key], 0, -2);
39
        }
40
	}
41
42
	public function next(Handler $handler)
43
	{
44
		$this->handler = $handler;
45
	}
46
47
	private function checkIsFormData(Server $server): bool
48
	{
49
		return ContentHelper::contentIs($server, 'form-data') && $server->method() !== 'POST';
50
	}
51
52
	public function handle($server): array
53
	{
54
		if ($this->checkIsFormData($server)) {
55
			return $this->getBody($server->getContent());
56
		}
57
58
		return $this->handler->handle($server);
59
	}
60
}