FormData::next()   A
last analyzed

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
    private const CONTENT_TYPE = 'form-data';
15
16
	public function __construct()
17
    {
18
        $this->currentData = [];
19
    }
20
21
    public function getBody($content): array
22
	{
23
        $boundary = substr($content, 0, strpos($content, "\r\n"));
24
        $parts = array_slice(explode($boundary, $content), 1);
25
26
        foreach ($parts as $part) {
27
            preg_match_all('/"(.+)"+\s+([^\t]+)/', $part, $matches);
28
29
            $this->handleBodySent($matches);
30
        }
31
32
        return $this->currentData;
33
	}
34
35
    private function handleBodySent(array $matches): void
36
    {
37
        foreach ($matches[1] as $key => $match) {
38
            $matchKey = str_replace(["'", '"'], '', $match);
39
40
            $this->currentData[$matchKey] = substr($matches[2][$key], 0, -2);
41
        }
42
	}
43
44
	public function next(Handler $handler)
45
	{
46
		$this->handler = $handler;
47
	}
48
49
	private function isFormDataContentType(Server $server): bool
50
	{
51
		return ContentHelper::contentIs($server, self::CONTENT_TYPE) && $server->method() !== 'POST';
52
	}
53
54
	public function handle($server): array
55
	{
56
		if ($this->isFormDataContentType($server)) {
57
			return $this->getBody($server->getContent());
58
		}
59
60
		return $this->handler->handle($server);
61
	}
62
}