Completed
Push — master ( e93008...5fbe6a )
by Dan
05:46
created

Guzzle::logRejection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
namespace Nopolabs\Yabot\Guzzle;
3
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Promise\PromiseInterface;
8
use Nopolabs\Yabot\Helpers\LogTrait;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Log\LoggerInterface;
11
12
class Guzzle
13
{
14
    use LogTrait;
15
16
    /** @var Client */
17
    private $client;
18
19
    public function __construct(Client $client, LoggerInterface $log = null)
20
    {
21
        $this->client = $client;
22
        $this->setLog($log);
23
    }
24
25
    public function getClient() : Client
26
    {
27
        return $this->client;
28
    }
29
30
    public function getAsync(string $uri, array $options = [], callable $onRejected = null) : PromiseInterface
31
    {
32
        $onRejected = $onRejected ?? function($reason) { $this->logRejection($reason); };
33
34
        return $this->client->getAsync($uri, $options)->then(null, $onRejected);
35
    }
36
37
    public function postAsync(string $uri, array $options = [], callable $onRejected = null) : PromiseInterface
38
    {
39
        $onRejected = $onRejected ?? function($reason) { $this->logRejection($reason); };
40
41
        return $this->client->postAsync($uri, $options)->then(null, $onRejected);
42
    }
43
44
    public function get(string $uri, array $options = []) : ResponseInterface
45
    {
46
        return $this->client->get($uri, $options);
47
    }
48
49
    public function put(string $uri, array $options = []) : ResponseInterface
50
    {
51
        return $this->client->put($uri, $options);
52
    }
53
    
54
    public function post(string $uri, array $options = []) : ResponseInterface
55
    {
56
        return $this->client->post($uri, $options);
57
    }
58
59
    private function logRejection($reason)
60
    {
61
        if ($reason instanceof Exception) {
62
            $message = $reason->getMessage()."\n".$reason->getTraceAsString();
63
        } else {
64
            $message = $reason;
65
        }
66
        $this->getLog()->warning($message);
67
    }
68
}