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

Response::find()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
rs 10
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