Completed
Push — master ( 58620c...f23d9f )
by Vitaliy
02:20
created

CurlHttpSender   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 68
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A send() 0 10 1
A close() 0 5 1
A initializeCurlResource() 0 10 2
A prepareCurlResourceByRequest() 0 18 3
1
<?php
2
3
/*
4
 * This file is part of the AppleApnPush package
5
 *
6
 * (c) Vitaliy Zhuk <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code
10
 */
11
12
namespace Apple\ApnPush\Protocol\Http\Sender;
13
14
use Apple\ApnPush\Protocol\Http\Request;
15
use Apple\ApnPush\Protocol\Http\Response;
16
17
/**
18
 * Send HTTP request via cURL
19
 */
20
class CurlHttpSender implements HttpSenderInterface
21
{
22
    /**
23
     * @var resource
24
     */
25
    private $resource;
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function send(Request $request) : Response
31
    {
32
        $this->initializeCurlResource();
33
        $this->prepareCurlResourceByRequest($request);
34
35
        $content = curl_exec($this->resource);
36
        $statusCode = (int) curl_getinfo($this->resource, CURLINFO_HTTP_CODE);
37
38
        return new Response($statusCode, $content);
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function close()
45
    {
46
        curl_close($this->resource);
47
        $this->resource = null;
48
    }
49
50
    /**
51
     * Initialize cURL resource
52
     */
53
    private function initializeCurlResource()
54
    {
55
        if (!$this->resource) {
56
            $this->resource = curl_init();
57
58
            curl_setopt($this->resource, CURLOPT_RETURNTRANSFER, 1);
59
            curl_setopt($this->resource, CURLOPT_POST, 1);
60
            curl_setopt($this->resource, CURLOPT_HTTP_VERSION, 3);
61
        }
62
    }
63
64
    /**
65
     * Prepare cURL resource by request
66
     *
67
     * @param Request $request
68
     */
69
    private function prepareCurlResourceByRequest(Request $request)
70
    {
71
        curl_setopt($this->resource, CURLOPT_URL, $request->getUrl());
72
        curl_setopt($this->resource, CURLOPT_POSTFIELDS, $request->getContent());
73
74
        if ($request->getCertificate()) {
75
            curl_setopt($this->resource, CURLOPT_SSLCERT, $request->getCertificate());
76
            curl_setopt($this->resource, CURLOPT_SSLCERTPASSWD, $request->getCertificatePassPhrase());
77
        }
78
79
        $inlineHeaders = [];
80
81
        foreach ($request->getHeaders() as $name => $value) {
82
            $inlineHeaders[] = sprintf('%s: %s', $name, $value);
83
        }
84
85
        curl_setopt($this->resource, CURLOPT_HTTPHEADER, $inlineHeaders);
86
    }
87
}
88