Completed
Pull Request — master (#16)
by Mischa
03:01
created

CurlApiClient::add_default_headers()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 10
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 10
loc 10
rs 9.4285
cc 3
eloc 5
nc 3
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 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;
0 ignored issues
show
Bug introduced by
The property authenticationRetryLimit does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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 View Code Duplication
    private function add_default_headers($headers)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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