Passed
Push — 1.x ( 885d6a...11c6d3 )
by Kevin
01:56
created

Response   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 18
dl 0
loc 60
rs 10
c 1
b 0
f 1
wmc 11

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A session() 0 3 1
A rawBody() 0 3 1
A raw() 0 3 1
A rawMetadata() 0 11 3
A createFor() 0 13 3
A body() 0 3 1
1
<?php
2
3
namespace Zenstruck\Browser;
4
5
use Behat\Mink\Session;
6
use Zenstruck\Browser\Response\HtmlResponse;
7
use Zenstruck\Browser\Response\JsonResponse;
8
9
/**
10
 * @author Kevin Bond <[email protected]>
11
 */
12
abstract class Response
13
{
14
    private Session $session;
15
16
    final public function __construct(Session $session)
17
    {
18
        $this->session = $session;
19
    }
20
21
    final public static function createFor(Session $session): self
22
    {
23
        $contentType = $session->getResponseHeader('content-type');
24
25
        if (str_contains($contentType, 'json')) {
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type null; however, parameter $haystack of str_contains() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

25
        if (str_contains(/** @scrutinizer ignore-type */ $contentType, 'json')) {
Loading history...
26
            return new JsonResponse($session);
27
        }
28
29
        if (str_contains($contentType, 'html')) {
30
            return new HtmlResponse($session);
31
        }
32
33
        throw new \RuntimeException("Unable to create browser response for \"{$contentType}\".");
34
    }
35
36
    public function body()
37
    {
38
        return $this->session->getPage()->getContent();
39
    }
40
41
    final public function raw(): string
42
    {
43
        return "{$this->rawMetadata()}\n{$this->rawBody()}";
44
    }
45
46
    /**
47
     * @return mixed
48
     */
49
    abstract public function find(string $selector);
50
51
    final protected function session(): Session
52
    {
53
        return $this->session;
54
    }
55
56
    protected function rawMetadata(): string
57
    {
58
        $ret = "URL: {$this->session->getCurrentUrl()} ({$this->session->getStatusCode()})\n\n";
59
60
        foreach ($this->session->getResponseHeaders() as $header => $values) {
61
            foreach ($values as $value) {
62
                $ret .= "{$header}: {$value}\n";
63
            }
64
        }
65
66
        return $ret;
67
    }
68
69
    protected function rawBody(): string
70
    {
71
        return $this->body();
72
    }
73
}
74