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

CurlApiClient   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 87
Duplicated Lines 11.49 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
C makeApiCall() 0 53 10
A add_default_headers() 10 10 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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