WebClient::request()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Jerodev\Diglett;
4
5
use Goutte\Client;
6
use GuzzleHttp\Client as GuzzleClient;
7
8
class WebClient
9
{
10
    /**
11
     *  The underlying goutte client.
12
     *
13
     *  @var Client
14
     */
15
    private static $goutteClient;
16
17
    /**
18
     *  Create a new Diglett instance.
19
     *
20
     *  @param GuzzleClient|array|null $client
21
     */
22
    public function __construct($client = null)
23
    {
24
        $goutteClient = new Client();
25
26
        if (is_array($client)) {
27
            $guzzleClient = new GuzzleClient($client);
28
            $goutteClient->setClient($guzzleClient);
29
        } elseif ($client instanceof GuzzleClient) {
30
            $goutteClient->setClient($client);
31
        } else {
32
            // Unknow parmeter type or null, use default configuration
33
            $this->getClient();
34
        }
35
    }
36
37
    /**
38
     *  Perform a GET request.
39
     *
40
     *  @param string $url
41
     */
42
    public static function get(string $url): Diglett
43
    {
44
        return self::request('GET', $url);
45
    }
46
47
    /**
48
     *  Perform a POST request.
49
     *
50
     *  @param string $url
51
     */
52
    public static function post(string $url): Diglett
53
    {
54
        return self::request('POST', $url);
55
    }
56
57
    /**
58
     *  Perform a web request.
59
     *
60
     *  @param string $method Http method
61
     *  @param string $url
62
     */
63
    private static function request(string $method, string $url): Diglett
64
    {
65
        return new Diglett(self::getClient()->request($method, $url));
66
    }
67
68
    /**
69
     *  Get the active GoutteClient.
70
     */
71
    private static function getClient(): Client
72
    {
73
        if (!isset(self::$goutteClient)) {
74
            $guzzleClient = new GuzzleClient(['timeout' => 60]);
75
            $goutteClient = new Client();
76
            $goutteClient->setClient($guzzleClient);
77
            self::$goutteClient = $goutteClient;
78
        }
79
80
        return self::$goutteClient;
81
    }
82
}
83