Completed
Push — master ( 770f40...f229c5 )
by Christian
06:37
created

Handler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 0
cts 7
cp 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 4
crap 2
1
<?php
2
3
/*
4
 * This file is part of the xAPI package.
5
 *
6
 * (c) Christian Flothmann <[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 Xabbuh\XApi\Client\Request;
13
14
use Guzzle\Http\ClientInterface;
15
use Guzzle\Http\Exception\ClientErrorResponseException;
16
use Guzzle\Http\Message\RequestInterface;
17
use Xabbuh\XApi\Common\Exception\AccessDeniedException;
18
use Xabbuh\XApi\Common\Exception\ConflictException;
19
use Xabbuh\XApi\Common\Exception\NotFoundException;
20
use Xabbuh\XApi\Common\Exception\XApiException;
21
22
/**
23
 * Prepare and execute xAPI HTTP requests.
24
 *
25
 * @author Christian Flothmann <[email protected]>
26
 */
27
final class Handler implements HandlerInterface
28
{
29
    private $httpClient;
30
31
    private $version;
32
33
    private $username;
34
35
    private $password;
36
37
    /**
38
     * @param ClientInterface $httpClient The HTTP client
39
     * @param string          $version    The xAPI version
40
     * @param string          $username   The optional HTTP auth username
41
     * @param string          $password   The optional HTTP auth password
42
     */
43
    public function __construct(ClientInterface $httpClient, $version, $username = null, $password = null)
44
    {
45
        $this->httpClient = $httpClient;
46
        $this->version = $version;
47
        $this->username = $username;
48
        $this->password = $password;
49
    }
50
51
    /**
52
     * {@inheritDoc}
53
     */
54
    public function createRequest($method, $uri, array $urlParameters = array(), $body = null)
55
    {
56
        if (count($urlParameters) > 0) {
57
            $uri .= '?'.http_build_query($urlParameters);
58
        }
59
60
        switch (strtolower($method)) {
61
            case 'get':
62
                $request = $this->httpClient->get($uri);
63
                break;
64
            case 'post':
65
                $request = $this->httpClient->post($uri, null, $body);
66
                break;
67
            case 'put':
68
                $request = $this->httpClient->put($uri, null, $body);
69
                break;
70
            case 'delete':
71
                $request = $this->httpClient->delete($uri);
72
                break;
73
            default:
74
                throw new \InvalidArgumentException(
75
                    $method.' is no valid HTTP method'
76
                );
77
        }
78
79
        $request->addHeader('X-Experience-API-Version', $this->version);
80
        $request->addHeader('Content-Type', 'application/json');
81
82
        if (null !== $this->username && null !== $this->password) {
83
            $request->setAuth($this->username, $this->password);
84
        }
85
86
        return $request;
87
    }
88
89
    /**
90
     * {@inheritDoc}
91
     */
92
    public function executeRequest(RequestInterface $request, array $validStatusCodes)
93
    {
94
        try {
95
            $response = $request->send();
96
        } catch (ClientErrorResponseException $e) {
97
            $response = $e->getResponse();
98
        }
99
100
        // catch some common errors
101
        if (in_array($response->getStatusCode(), array(401, 403))) {
102
            throw new AccessDeniedException(
103
                $response->getBody(true),
104
                $response->getStatusCode()
105
            );
106
        } elseif (404 === $response->getStatusCode()) {
107
            throw new NotFoundException($response->getBody(true));
108
        } elseif (409 === $response->getStatusCode()) {
109
            throw new ConflictException($response->getBody(true));
110
        }
111
112
        if (!in_array($response->getStatusCode(), $validStatusCodes)) {
113
            throw new XApiException($response->getBody(true), $response->getStatusCode());
114
        }
115
116
        return $response;
117
    }
118
}
119