Completed
Pull Request — master (#10)
by Christian
04:20
created

Handler::createRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 15
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 4
crap 12
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 Http\Client\Common\Plugin\AuthenticationPlugin;
15
use Http\Client\Common\PluginClient;
16
use Http\Client\Exception;
17
use Http\Client\HttpClient;
18
use Http\Message\Authentication\BasicAuth;
19
use Http\Message\RequestFactory;
20
use Psr\Http\Message\RequestInterface;
21
use Xabbuh\XApi\Common\Exception\AccessDeniedException;
22
use Xabbuh\XApi\Common\Exception\ConflictException;
23
use Xabbuh\XApi\Common\Exception\NotFoundException;
24
use Xabbuh\XApi\Common\Exception\XApiException;
25
26
/**
27
 * Prepares and executes xAPI HTTP requests.
28
 *
29
 * @author Christian Flothmann <[email protected]>
30
 */
31
final class Handler implements HandlerInterface
32
{
33
    private $httpClient;
34
    private $requestFactory;
35
    private $baseUri;
36
    private $version;
37
38
    /**
39
     * @param HttpClient     $httpClient     The HTTP client sending requests to the remote LRS
40
     * @param RequestFactory $requestFactory The factory used to create PSR-7 HTTP requests
41
     * @param string         $baseUri        The APIs base URI (all end points will be created relatively to this URI)
42
     * @param string         $version        The xAPI version
43
     * @param string         $username       The optional HTTP auth username
44
     * @param string         $password       The optional HTTP auth password
45
     */
46
    public function __construct(HttpClient $httpClient, RequestFactory $requestFactory, $baseUri, $version, $username = null, $password = null)
47
    {
48
        if (null !== $username && null !== $password) {
49
            $this->httpClient = new PluginClient($httpClient, array(new AuthenticationPlugin(new BasicAuth($username, $password))));
50
        } else {
51
            $this->httpClient = $httpClient;
52
        }
53
54
        $this->requestFactory = $requestFactory;
55
        $this->baseUri = $baseUri;
56
        $this->version = $version;
57
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62
    public function createRequest($method, $uri, array $urlParameters = array(), $body = null)
63
    {
64
        if (!in_array(strtoupper($method), array('GET', 'POST', 'PUT', 'DELETE'))) {
65
            throw new \InvalidArgumentException(sprintf('"%s" is no valid HTTP method (expected one of [GET, POST, PUT, DELETE]) in an xAPI context.', $method));
66
        }
67
68
        $uri = rtrim($this->baseUri, '/').'/'.ltrim($uri, '/');
69
70
        if (count($urlParameters) > 0) {
71
            $uri .= '?'.http_build_query($urlParameters);
72
        }
73
74
        $request = $this->requestFactory->createRequest($method, $uri, array(
75
            'X-Experience-API-Version' => $this->version,
76
            'Content-Type' => 'application/json',
77
        ));
78
79
        return $request;
80
    }
81
82
    /**
83
     * {@inheritDoc}
84
     */
85
    public function executeRequest(RequestInterface $request, array $validStatusCodes)
86
    {
87
        try {
88
            $response = $this->httpClient->sendRequest($request);
89
        } catch (Exception $e) {
90
            throw new XApiException($e->getMessage(), $e->getCode(), $e);
91
        }
92
93
        // catch some common errors
94
        if (in_array($response->getStatusCode(), array(401, 403))) {
95
            throw new AccessDeniedException(
96
                (string) $response->getBody(),
97
                $response->getStatusCode()
98
            );
99
        } elseif (404 === $response->getStatusCode()) {
100
            throw new NotFoundException((string) $response->getBody());
101
        } elseif (409 === $response->getStatusCode()) {
102
            throw new ConflictException((string) $response->getBody());
103
        }
104
105
        if (!in_array($response->getStatusCode(), $validStatusCodes)) {
106
            throw new XApiException((string) $response->getBody(), $response->getStatusCode());
107
        }
108
109
        return $response;
110
    }
111
}
112