Completed
Pull Request — master (#19)
by Mischa
04:02
created

DefaultApiClient::authenticateRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4286
cc 1
eloc 5
nc 1
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
        $response = null;
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
47
48
        // Request tokens when none are set
49
        if ($this->authenticator->getAccessToken() === null) {
50
            $this->getNewToken($request);
51
        }
52
53
        $response = $this->sendRequest($this->authenticateRequest($request));
54
55
        if ($response['status'] === 401) {
56
57
            $this->incrementAuthenticationRetryAttempt();
58
59
            if ($this->isAuthenticationRetryLimitReached()) {
60
                throw new AccessDeniedException('Authentication retry limit reached.');
61
            }
62
63
            // Once SD-3820 is fixed, implement SWP-92 branch, it will use
64
            // the refresh token functionality, instead of request a new token
65
            // each time this method is called.
66
            $this->getNewToken($request);
67
68
            // Retry making an api call
69
            return $this->makeApiCall($request);
70
        }
71
72
        if ($response['status'] == 200) {
73
74
            $this->resetAuthenticationRetryAttempt();
75
76
            return $this->createResponseObject($response);
77
        }
78
79
        throw new ClientException(sprintf('The server returned an error with status %s.', $response['status']));
80
    }
81
82
    private function createResponseObject($response)
83
    {
84
        try {
85
            return new Response($response['body'], $response['headers']);
86
        } catch (ResponseException $e) {
87
            throw new ClientException($e->getMessage(), $e->getCode(), $e);
88
        }
89
    }
90
91
    /**
92
     * Adds authentication details to request with OAuth decorator.
93
     *
94
     * @param  RequestInterface $request
95
     *
96
     * @return OAuthDecorator OAuth ready decorated Request
97
     */
98
    private function authenticateRequest(RequestInterface $request)
99
    {
100
        $authenticatedRequest = new OAuthDecorator($request);
101
        $authenticatedRequest->setAccessToken($this->authenticator->getAccessToken());
102
        $authenticatedRequest->addAuthentication();
103
104
        return $authenticatedRequest;
105
    }
106
107
    /**
108
     * Sends the actual request.
109
     *
110
     * @param  RequestInterface $request
111
     *
112
     * @return Response Response object created from raw response
113
     *
114
     * @throws ClientException Thrown when response could not be created.
115
     */
116
    private function sendRequest(RequestInterface $request)
117
    {
118
        return $this->client->makeCall(
119
            $request->getFullUrl(),
120
            $this->addDefaultHeaders($request->getHeaders()),
121
            $request->getOptions()
122
        );
123
    }
124
125
    /**
126
     * Refreshes the token via then authenticator.
127
     *
128
     * @param  RequestInterface $request
129
     *
130
     * @return void
131
     */
132
    private function getNewToken(RequestInterface $request)
133
    {
134
        try {
135
            $this->authenticator->setBaseUrl($request->getBaseUrl());
136
            $this->authenticator->getAuthenticationTokens();
137
        } catch (AuthenticationException $e) {
138
            throw new AccessDeniedException('Could not authenticate against API.', $e->getCode(), $e);
139
        }
140
141
        return;
142
    }
143
144
    /**
145
     * Adds default headers to the headers per request, only if the key
146
     * cannot not be found in the headers per request.
147
     *
148
     * @param array $headers
149
     *
150
     * @return array
151
     */
152
    private function addDefaultHeaders($headers)
153
    {
154
        foreach ($this->headers as $key => $value) {
155
            if (!isset($headers[$key])) {
156
                $headers[$key] = $value;
157
            }
158
        }
159
160
        return $headers;
161
    }
162
}
163