Completed
Push — http-resource-object ( 848b06 )
by Akihito
05:01
created

HttpResourceObject::__get()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.3888
c 0
b 0
f 0
cc 5
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use function strtoupper;
8
use Symfony\Contracts\HttpClient\HttpClientInterface;
9
use Symfony\Contracts\HttpClient\ResponseInterface;
10
11
/**
12
 * @method HttpResourceObject get(AbstractUri|string $uri, array $params = [])
13
 * @method HttpResourceObject head(AbstractUri|string $uri, array $params = [])
14
 * @method HttpResourceObject put(AbstractUri|string $uri, array $params = [])
15
 * @method HttpResourceObject post(AbstractUri|string $uri, array $params = [])
16
 * @method HttpResourceObject patch(AbstractUri|string $uri, array $params = [])
17
 * @method HttpResourceObject delete(AbstractUri|string $uri, array $params = [])
18
 */
19
final class HttpResourceObject extends ResourceObject
20
{
21
    /**
22
     * @var HttpClientInterface
23
     */
24
    private $client;
25
26
    /**
27
     * @var ResponseInterface
28
     */
29
    private $response;
30
31
    public function __construct(HttpClientInterface $client)
32
    {
33
        $this->client = $client;
34
        unset($this->code, $this->headers, $this->body, $this->view);
35
    }
36
37
    public function __call(string $name, array $arguments = ['get', []])
38
    {
39
        $method = strtoupper($name);
40
        $params = isset($arguments[1]) ? $arguments[1] : [];
41
        $options = ($method === 'GET') ? ['query' => $params] : ['body' => $params];
42
        $this->response = $this->client->request(strtoupper($name), $arguments[0], $options);
43
44
        return $this;
45
    }
46
47
    public function __get(string $name)
48
    {
49
        if ($name === 'code') {
50
            return $this->response->getStatusCode();
51
        }
52
        if ($name === 'headers') {
53
            return $this->response->getHeaders();
54
        }
55
        if ($name === 'body') {
56
            return $this->response->toArray();
57
        }
58
        if ($name === 'view') {
59
            return $this->response->getContent();
60
        }
61
62
        throw new \InvalidArgumentException($name);
63
    }
64
65
    public function __set(string $name, $value) : void
66
    {
67
        $this->{$name} = $value;
68
    }
69
70
    public function __isset(string $name) : bool
71
    {
72
        return isset($this->{$name});
73
    }
74
75
    public function __toString() : string
76
    {
77
        return $this->response->getContent();
78
    }
79
}
80