MailxpertStreamHttpClient::compileHeader()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/**
3
 * sources.
4
 * Date: 14/08/15
5
 */
6
7
namespace Mailxpert\HttpClients;
8
9
use Mailxpert\Exceptions\MailxpertSDKException;
10
use Mailxpert\Http\RawResponse;
11
12
/**
13
 * Class MailxpertStreamHttpClient
14
 * @package Mailxpert\HttpClients
15
 */
16
class MailxpertStreamHttpClient implements MailxpertHttpClientInterface
17
{
18
    /**
19
     * @var MailxpertStream Procedural stream wrapper as object.
20
     */
21
    protected $mailxpertStream;
22
23
    /**
24
     * @param MailxpertStream|null $mailxpertStream Procedural stream wrapper as object.
25
     */
26
    public function __construct(MailxpertStream $mailxpertStream = null)
27
    {
28
        $this->mailxpertStream = $mailxpertStream ?: new MailxpertStream();
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function send($url, $method, $body, array $headers, $timeOut)
35
    {
36
        $options = [
37
            'http' => [
38
                'method' => $method,
39
                'header' => $this->compileHeader($headers),
40
                'content' => $body,
41
                'timeout' => $timeOut,
42
                'ignore_errors' => true,
43
            ],
44
        ];
45
46
        $this->mailxpertStream->streamContextCreate($options);
47
        $rawBody = $this->mailxpertStream->fileGetContents($url);
48
        $rawHeaders = $this->mailxpertStream->getResponseHeaders();
49
50
        if ($rawBody === false || empty($rawHeaders)) {
51
            throw new MailxpertSDKException('Stream returned an empty response', 660);
52
        }
53
54
        $rawHeaders = implode("\r\n", $rawHeaders);
55
56
        return new RawResponse($rawHeaders, $rawBody);
57
    }
58
59
    /**
60
     * Formats the headers for use in the stream wrapper.
61
     *
62
     * @param array $headers The request headers.
63
     *
64
     * @return string
65
     */
66
    public function compileHeader(array $headers)
67
    {
68
        $header = [];
69
        foreach ($headers as $k => $v) {
70
            $header[] = $k.': '.$v;
71
        }
72
73
        return implode("\r\n", $header);
74
    }
75
}
76