Completed
Push — master ( dccc7f...4ad075 )
by Vladimir
03:52
created

InteractsWithRequest::getHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FondBot\Http;
6
7
use RuntimeException;
8
use FondBot\Helpers\Arr;
9
use Psr\Http\Message\ServerRequestInterface;
10
11
trait InteractsWithRequest
12
{
13
    /** @var ServerRequestInterface */
14
    protected $request;
15
16
    /**
17
     * Get request value.
18
     *
19
     * @param string|null $key
20
     * @param null        $default
21
     *
22
     * @return mixed
23
     */
24 1
    public function getRequest(string $key = null, $default = null)
25
    {
26 1
        if ($this->request === null) {
27
            return null;
28
        }
29
30
        try {
31 1
            $contents = json_decode($this->request->getBody()->getContents(), true);
32
33 1
            if ($contents === null) {
34
                return null;
35
            }
36
37 1
            return Arr::get($contents, $key, $default);
38
        } catch (RuntimeException $exception) {
39
            return null;
40
        }
41
    }
42
43
    /**
44
     * If request has key.
45
     *
46
     * @param string $key
47
     *
48
     * @return bool
49
     */
50 1
    public function hasRequest(string $key): bool
51
    {
52 1
        if ($this->request === null) {
53
            return false;
54
        }
55
56
        try {
57 1
            $contents = json_decode($this->request->getBody()->getContents(), true);
58
59 1
            if ($contents === null) {
60
                return false;
61
            }
62
63 1
            return Arr::has($contents, [$key]);
64
        } catch (RuntimeException $exception) {
65
            return false;
66
        }
67
    }
68
69
    /**
70
     * Get header.
71
     *
72
     * @param string $name
73
     * @param null   $default
74
     *
75
     * @return mixed
76
     */
77 1
    public function getHeader(string $name = null, $default = null)
78
    {
79 1
        return Arr::get($this->request->getHeaders(), $name, $default);
80
    }
81
}
82