Completed
Pull Request — master (#10)
by Christian
08:22 queued 06:26
created

Handler::executeRequest()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 22
cp 0
rs 8.439
c 0
b 0
f 0
cc 6
eloc 16
nc 6
nop 2
crap 42
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\Exception;
15
use Http\Client\HttpClient;
16
use Http\Message\RequestFactory;
17
use Psr\Http\Message\RequestInterface;
18
use Xabbuh\XApi\Common\Exception\AccessDeniedException;
19
use Xabbuh\XApi\Common\Exception\ConflictException;
20
use Xabbuh\XApi\Common\Exception\NotFoundException;
21
use Xabbuh\XApi\Common\Exception\XApiException;
22
23
/**
24
 * Prepares and executes xAPI HTTP requests.
25
 *
26
 * @author Christian Flothmann <[email protected]>
27
 */
28
final class Handler implements HandlerInterface
29
{
30
    private $httpClient;
31
    private $requestFactory;
32
    private $baseUri;
33
    private $version;
34
    private $username;
35
    private $password;
36
37
    /**
38
     * @param HttpClient     $httpClient     The HTTP client sending requests to the remote LRS
39
     * @param RequestFactory $requestFactory The factory used to create PSR-7 HTTP requests
40
     * @param string         $baseUri        The APIs base URI (all end points will be created relatively to this URI)
41
     * @param string         $version        The xAPI version
42
     * @param string         $username       The optional HTTP auth username
43
     * @param string         $password       The optional HTTP auth password
44
     */
45
    public function __construct(HttpClient $httpClient, RequestFactory $requestFactory, $baseUri, $version, $username = null, $password = null)
46
    {
47
        $this->httpClient = $httpClient;
48
        $this->requestFactory = $requestFactory;
49
        $this->baseUri = $baseUri;
50
        $this->version = $version;
51
        $this->username = $username;
52
        $this->password = $password;
53
    }
54
55
    /**
56
     * {@inheritDoc}
57
     */
58
    public function createRequest($method, $uri, array $urlParameters = array(), $body = null)
59
    {
60
        if (!in_array(strtoupper($method), array('GET', 'POST', 'PUT', 'DELETE'))) {
61
            throw new \InvalidArgumentException(sprintf('"%s" is no valid HTTP method (expected one of [GET, POST, PUT, DELETE]) in an xAPI context.', $method));
62
        }
63
64
        $uri = rtrim($this->baseUri, '/').'/'.ltrim($uri, '/');
65
66
        if (count($urlParameters) > 0) {
67
            $uri .= '?'.http_build_query($urlParameters);
68
        }
69
70
        $request = $this->requestFactory->createRequest($method, $uri, array(
71
            'X-Experience-API-Version' => $this->version,
72
            'Content-Type' => 'application/json',
73
        ));
74
75
        $request->setAuth($this->username, $this->password);
0 ignored issues
show
Bug introduced by
The method setAuth() does not seem to exist on object<Psr\Http\Message\RequestInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
76
77
        return $request;
78
    }
79
80
    /**
81
     * {@inheritDoc}
82
     */
83
    public function executeRequest(RequestInterface $request, array $validStatusCodes)
84
    {
85
        try {
86
            $response = $this->httpClient->sendRequest($request);
87
        } catch (Exception $e) {
88
            throw new XApiException($e->getMessage(), $e->getCode(), $e);
89
        }
90
91
        // catch some common errors
92
        if (in_array($response->getStatusCode(), array(401, 403))) {
93
            throw new AccessDeniedException(
94
                (string) $response->getBody(),
95
                $response->getStatusCode()
96
            );
97
        } elseif (404 === $response->getStatusCode()) {
98
            throw new NotFoundException((string) $response->getBody());
99
        } elseif (409 === $response->getStatusCode()) {
100
            throw new ConflictException((string) $response->getBody());
101
        }
102
103
        if (!in_array($response->getStatusCode(), $validStatusCodes)) {
104
            throw new XApiException((string) $response->getBody(), $response->getStatusCode());
105
        }
106
107
        return $response;
108
    }
109
}
110