Completed
Pull Request — master (#19)
by Mischa
12:28 queued 04:58
created

DefaultApiClient::makeApiCall()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 35
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 35
rs 8.439
cc 5
eloc 14
nc 8
nop 1
1
<?php
2
3
/**
4
 * This file is part of the PHP SDK library for the Superdesk Content API.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú.
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace Superdesk\ContentApiSdk\Client;
16
17
use Superdesk\ContentApiSdk\API\Request\RequestInterface;
18
use Superdesk\ContentApiSdk\API\Request\OAuthDecorator;
19
use Superdesk\ContentApiSdk\API\Response;
20
use Superdesk\ContentApiSdk\ContentApiSdk;
21
use Superdesk\ContentApiSdk\Exception\AuthenticationException;
22
use Superdesk\ContentApiSdk\Exception\AccessDeniedException;
23
use Superdesk\ContentApiSdk\Exception\ClientException;
24
use Superdesk\ContentApiSdk\Exception\ResponseException;
25
26
/**
27
 * Request client that implements all methods regarding basic request/response
28
 * handling for the Content API.
29
 */
30
class DefaultApiClient extends AbstractApiClient
31
{
32
    /**
33
     * Default request headers.
34
     *
35
     * @var array
36
     */
37
    protected $headers = array(
38
        'Accept' => 'application/json'
39
    );
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function makeApiCall(RequestInterface $request)
45
    {
46
        // Request tokens when none are set
47
        if ($this->authenticator->getAccessToken() === null) {
48
            $this->getNewToken($request);
49
        }
50
51
        $response = $this->sendRequest($this->authenticateRequest($request));
52
53
        if ($response['status'] === 401) {
54
55
            $this->incrementAuthenticationRetryAttempt();
56
57
            if ($this->isAuthenticationRetryLimitReached()) {
58
                throw new AccessDeniedException('Authentication retry limit reached.');
59
            }
60
61
            // Once SD-3820 is fixed, implement SWP-92 branch, it will use
62
            // the refresh token functionality, instead of request a new token
63
            // each time this method is called.
64
            $this->getNewToken($request);
65
66
            // Retry making an api call
67
            return $this->makeApiCall($request);
68
        }
69
70
        if ($response['status'] == 200) {
71
72
            $this->resetAuthenticationRetryAttempt();
73
74
            return $this->createResponseObject($response);
75
        }
76
77
        throw new ClientException(sprintf('The server returned an error with status %s.', $response['status']), $response['status']);
78
    }
79
80
    private function createResponseObject($response)
81
    {
82
        try {
83
            return new Response($response['body'], $response['headers']);
84
        } catch (ResponseException $e) {
85
            throw new ClientException($e->getMessage(), $e->getCode(), $e);
86
        }
87
    }
88
89
    /**
90
     * Adds authentication details to request with OAuth decorator.
91
     *
92
     * @param  RequestInterface $request
93
     *
94
     * @return OAuthDecorator OAuth ready decorated Request
95
     */
96
    private function authenticateRequest(RequestInterface $request)
97
    {
98
        $authenticatedRequest = new OAuthDecorator($request);
99
        $authenticatedRequest->setAccessToken($this->authenticator->getAccessToken());
100
        $authenticatedRequest->addAuthentication();
101
102
        return $authenticatedRequest;
103
    }
104
105
    /**
106
     * Sends the actual request.
107
     *
108
     * @param  RequestInterface $request
109
     *
110
     * @return Response Response object created from raw response
111
     *
112
     * @throws ClientException Thrown when response could not be created.
113
     */
114
    private function sendRequest(RequestInterface $request)
115
    {
116
        return $this->client->makeCall(
117
            $request->getFullUrl(),
118
            $this->addDefaultHeaders($request->getHeaders()),
119
            $request->getOptions()
120
        );
121
    }
122
123
    /**
124
     * Refreshes the token via then authenticator.
125
     *
126
     * @param  RequestInterface $request
127
     *
128
     * @return void
129
     */
130
    private function getNewToken(RequestInterface $request)
131
    {
132
        try {
133
            $this->authenticator->setBaseUrl($request->getBaseUrl());
134
            $this->authenticator->getAuthenticationTokens();
135
        } catch (AuthenticationException $e) {
136
            throw new AccessDeniedException('Could not authenticate against API.', $e->getCode(), $e);
137
        }
138
139
        return;
140
    }
141
142
    /**
143
     * Adds default headers to the headers per request, only if the key
144
     * cannot not be found in the headers per request.
145
     *
146
     * @param array $headers
147
     *
148
     * @return array
149
     */
150
    private function addDefaultHeaders($headers)
151
    {
152
        foreach ($this->headers as $key => $value) {
153
            if (!isset($headers[$key])) {
154
                $headers[$key] = $value;
155
            }
156
        }
157
158
        return $headers;
159
    }
160
}
161