Passed
Push — 1.x ( 4cbda7...25b111 )
by Kevin
01:43
created

Response   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
eloc 24
c 2
b 0
f 2
dl 0
loc 79
rs 10
wmc 18

11 Methods

Rating   Name   Duplication   Size   Complexity  
A statusCode() 0 3 1
A isRedirect() 0 3 2
A __construct() 0 3 1
A dump() 0 7 2
A raw() 0 3 1
A isSuccessful() 0 3 2
A body() 0 3 1
A createFor() 0 13 3
A session() 0 3 1
A rawBody() 0 3 1
A rawMetadata() 0 11 3
1
<?php
2
3
namespace Zenstruck\Browser;
4
5
use Behat\Mink\Session;
6
use Symfony\Component\VarDumper\VarDumper;
7
use Zenstruck\Browser\Response\HtmlResponse;
8
use Zenstruck\Browser\Response\JsonResponse;
9
10
/**
11
 * @author Kevin Bond <[email protected]>
12
 */
13
class Response
14
{
15
    private Session $session;
16
17
    final public function __construct(Session $session)
18
    {
19
        $this->session = $session;
20
    }
21
22
    final public function statusCode(): int
23
    {
24
        return $this->session->getStatusCode();
25
    }
26
27
    final public static function createFor(Session $session): self
28
    {
29
        $contentType = (string) $session->getResponseHeader('content-type');
30
31
        if (str_contains($contentType, 'json')) {
32
            return new JsonResponse($session);
33
        }
34
35
        if (str_contains($contentType, 'html')) {
36
            return new HtmlResponse($session);
37
        }
38
39
        return new self($session);
40
    }
41
42
    final public function body(): string
43
    {
44
        return $this->session->getPage()->getContent();
45
    }
46
47
    final public function raw(): string
48
    {
49
        return "{$this->rawMetadata()}\n{$this->rawBody()}";
50
    }
51
52
    final public function isSuccessful(): bool
53
    {
54
        return $this->statusCode() >= 200 && $this->statusCode() < 300;
55
    }
56
57
    final public function isRedirect(): bool
58
    {
59
        return $this->statusCode() >= 300 && $this->statusCode() < 400;
60
    }
61
62
    public function dump(?string $selector = null): void
63
    {
64
        if (null !== $selector) {
65
            throw new \LogicException('$selector cannot be used with this response type.');
66
        }
67
68
        VarDumper::dump($this->raw());
69
    }
70
71
    final protected function session(): Session
72
    {
73
        return $this->session;
74
    }
75
76
    protected function rawMetadata(): string
77
    {
78
        $ret = "URL: {$this->session->getCurrentUrl()} ({$this->statusCode()})\n\n";
79
80
        foreach ($this->session->getResponseHeaders() as $header => $values) {
81
            foreach ($values as $value) {
82
                $ret .= "{$header}: {$value}\n";
83
            }
84
        }
85
86
        return $ret;
87
    }
88
89
    protected function rawBody(): string
90
    {
91
        return $this->body();
92
    }
93
}
94