Completed
Pull Request — master (#16)
by Mischa
19:07 queued 12:02
created

CurlApiClient::makeApiCall()   C

Complexity

Conditions 10
Paths 34

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 53
rs 6.5333
cc 10
eloc 32
nc 34
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 service that implements all method regarding basic request/response
28
 * handling.
29
 */
30
class CurlApiClient 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;
47
48
        if ($this->authenticator->getAccessToken() !== null) {
49
            $authenticatedRequest = new OAuthDecorator($request);
50
            $authenticatedRequest->setAccessToken($this->authenticator->getAccessToken());
51
            $authenticatedRequest->addAuthentication();
52
53
            $response = $this->client->makeCall(
54
                $authenticatedRequest->getFullUrl(),
55
                $this->add_default_headers($authenticatedRequest->getHeaders()),
56
                $authenticatedRequest->getOptions()
57
            );
58
59
            if ($response['status'] == 200) {
60
                $this->authenticationRetryLimit = 0;
61
62
                try {
63
                    return new Response($response['body'], $response['headers']);
64
                } catch (ResponseException $e) {
65
                    throw new ClientException($e->getMessage(), $e->getCode(), $e);
66
                }
67
            }
68
        }
69
70
        if ($response === null || $response['status'] == 401) {
71
72
            $this->authenticationRetryLimit++;
73
74
            if ($this->authenticationRetryLimit > self::MAX_RETRY_LIMIT) {
75
                throw new AccessDeniedException('Authentication retry limit reached.');
76
            }
77
78
            try {
79
                $this->authenticator->setBaseUrl($request->getBaseUrl());
80
                if ($this->authenticator->getAccessToken() !== null) {
81
                    $this->authenticator->refreshAccessToken();
82
                } else {
83
                    $this->authenticator->getAuthenticationTokens();
84
                }
85
86
                // Reexecute event
87
                return $this->makeApiCall($request);
88
            } catch (AccessDeniedException $e) {
89
                throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e);
90
            } catch (AuthenticationException $e) {
91
                throw new AccessDeniedException('Could not authenticate against API.', $e->getCode(), $e);
92
            }
93
        }
94
95
        throw new ClientException(sprintf('The server returned an error with status %s.', $response['status']));
96
    }
97
98
    /**
99
     * Adds default headers to the headers per request, only if the key
100
     * cannot not be found in the headers per request.
101
     *
102
     * @param array $headers
103
     *
104
     * @return array
105
     */
106
    private function add_default_headers($headers)
107
    {
108
        foreach ($this->headers as $key => $value) {
109
            if (!isset($headers[$key])) {
110
                $headers[$key] = $value;
111
            }
112
        }
113
114
        return $headers;
115
    }
116
}
117