Completed
Pull Request — master (#15)
by Mischa
11:40 queued 04:07
created

CurlApiClient   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 88
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 13
c 1
b 0
f 1
lcom 1
cbo 8
dl 0
loc 88
rs 10

2 Methods

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