Passed
Push — 1.x ( 435e44...040dab )
by Kevin
02:11
created

HasHttpBrowser::httpBrowserBaseUri()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Zenstruck\Browser\Test;
4
5
use Symfony\Component\BrowserKit\HttpBrowser as HttpBrowserClient;
6
use Symfony\Component\Panther\PantherTestCase;
7
use Zenstruck\Browser\HttpBrowser;
8
9
/**
10
 * @author Kevin Bond <[email protected]>
11
 *
12
 * @method HttpBrowser browser()
13
 */
14
trait HasHttpBrowser
15
{
16
    use HasBrowser;
17
18
    /** @var HttpBrowserClient[] */
19
    private static array $httpBrowserClients = [];
20
21
    /**
22
     * @internal
23
     * @after
24
     */
25
    public static function _resetHttpBrowserClients(): void
26
    {
27
        self::$httpBrowserClients = [];
28
    }
29
30
    protected function createBrowser(): HttpBrowser
31
    {
32
        $class = static::httpBrowserClass();
33
34
        if (!\is_a($class, HttpBrowser::class, true)) {
35
            throw new \RuntimeException(\sprintf('"HTTP_BROWSER_CLASS" env variable must reference a class that extends %s.', HttpBrowser::class));
36
        }
37
38
        $client = new HttpBrowserClient();
39
        $urlComponents = \parse_url($this->httpBrowserBaseUri());
40
41
        // copied from PantherTestCaseTrait::createHttpBrowserClient()
42
        $host = $urlComponents['host'];
43
44
        if (isset($urlComponents['port'])) {
45
            $host .= ":{$urlComponents['port']}";
46
        }
47
48
        $client->setServerParameter('HTTP_HOST', $host);
49
50
        if ('https' === ($urlComponents['scheme'] ?? 'http')) {
51
            $client->setServerParameter('HTTPS', 'true');
52
        }
53
54
        return new $class(self::$httpBrowserClients[] = $client);
55
    }
56
57
    protected function httpBrowserBaseUri(): string
58
    {
59
        if (!$this instanceof PantherTestCase) {
60
            throw new \RuntimeException(\sprintf('If not using "%s", you must override "%s" and return a base uri.', PantherTestCase::class, __METHOD__));
61
        }
62
63
        self::startWebServer();
64
65
        return self::$baseUri;
66
    }
67
68
    protected static function httpBrowserClass(): string
69
    {
70
        return $_SERVER['HTTP_BROWSER_CLASS'] ?? HttpBrowser::class;
71
    }
72
}
73