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

FormData   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 10
eloc 18
c 3
b 0
f 0
dl 0
loc 51
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A checkIsFormData() 0 3 2
A __construct() 0 3 1
A next() 0 3 1
A handleBodySent() 0 6 2
A getBody() 0 12 2
A handle() 0 7 2
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
}