Completed
Branch master (431168)
by Gennady
09:40
created

GuzzleHandler::factoryException()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 16
ccs 0
cts 8
cp 0
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
crap 12
1
<?php
2
/**
3
 * PHP APNS.
4
 *
5
 * @author Gennady Telegin <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Apns\Handler;
12
13
use Apns\Client as ApnsClient;
14
use Apns\Exception\ApnsException;
15
use Apns\ExceptionFactory;
16
use Apns\Message;
17
use GuzzleHttp\Client as HttpClient;
18
use GuzzleHttp\Exception\RequestException;
19
20 1
if (!defined('CURL_HTTP_VERSION_2_0')) {
21
    define('CURL_HTTP_VERSION_2_0', 3);
22
}
23
24
/**
25
 * Class GuzzleHandler.
26
 */
27
class GuzzleHandler
28
{
29
    /**
30
     * @var HttpClient
31
     */
32
    private $httpClient;
33
34
    /**
35
     * GuzzleHandler constructor.
36
     */
37 5
    public function __construct()
38
    {
39 5
        $this->httpClient = new HttpClient();
40 5
    }
41
42
    /**
43
     * @param ApnsClient $apns
44
     * @param Message    $message
45
     *
46
     * @return bool
47
     *
48
     * @throws ApnsException
49
     */
50
    public function __invoke(ApnsClient $apns, Message $message)
51
    {
52
        try {
53
            $response = $this->httpClient->request(
54
                'POST',
55
                $apns->getPushURI($message),
56
                [
57
                    'json' => json_encode($message),
58
                    'cert' => $apns->getSslCert(),
59
                    'headers' => $message->getMessageHeaders(),
60
                    'curl' => [
61
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
62
                    ],
63
                ]
64
            );
65
66
            return 200 === $response->getStatusCode();
67
        } catch (RequestException $e) {
68
            throw self::factoryException($e);
69
        }
70
    }
71
72
    /**
73
     * @param RequestException $exception
74
     *
75
     * @return ApnsException
76
     */
77
    private static function factoryException(RequestException $exception)
78
    {
79
        $response = $exception->getResponse();
80
81
        if (null === $response) {
82
            return new ApnsException('Unknown network error', 0, $exception);
83
        }
84
85
        try {
86
            $contents = $response->getBody()->getContents();
87
        } catch (\Exception $e) {
88
            return new ApnsException('Unknown network error', 0, $e);
89
        }
90
91
        return ExceptionFactory::factoryException($response->getStatusCode(), $contents, $exception);
92
    }
93
}
94