Completed
Pull Request — develop (#535)
by Bastian
14:26 queued 09:46
created

Swagger   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 130
Duplicated Lines 2.31 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 4
dl 3
loc 130
ccs 0
cts 57
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
A buildUrl() 3 14 4
A initCache() 0 6 1
B receiveSwaggerData() 0 36 4

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
 * Swagger
4
 */
5
6
namespace Graviton\ProxyBundle\Service\Source;
7
8
use Doctrine\Common\Cache\CacheProvider;
9
use Graviton\ProxyBundle\Adapter\Guzzle\GuzzleAdapter;
10
use Graviton\ProxyBundle\Definition\ApiDefinition;
11
use Graviton\ProxyBundle\Definition\Loader\DispersalStrategy\DispersalStrategyInterface;
12
13
/**
14
 * Class Swagger
15
 *
16
 * @package Graviton\ProxyBundle\Service\Source
17
 * @author  List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
18
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
19
 * @link    http://swisscom.ch
20
 */
21
class Swagger implements SourceInterface
22
{
23
    /** @var string  */
24
    private $prefix;
25
26
    /** @var string  */
27
    private $uri;
28
29
    /** @var GuzzleAdapter  */
30
    private $client;
31
32
    /** @var DispersalStrategyInterface */
33
    private $strategy;
34
35
    /** @var CacheProvider */
36
    private $cache;
37
38
    /** @var string  */
39
    private $cacheId;
40
41
    /** @var array */
42
    private $options;
43
44
    /** cache item lifetime */
45
    const CACHE_TTL = 86400;
46
47
    /** cache namespace */
48
    const CACHE_NS = 'Graviton/ProxyBundle';
49
50
51
    /**
52
     * Swagger constructor.
53
     *
54
     * @param GuzzleAdapter              $client
55
     * @param DispersalStrategyInterface $strategy
56
     * @param CacheProvider              $cache
57
     * @param string                     $prefix Identifier of the source used in the path (serivce://3rdparty/{$prefix}/[...])
58
     * @param string                     $uri    Url of the swagger file to be retrieved
59
     * @param array                      $options
60
     */
61
    public function __construct(
62
        GuzzleAdapter $client,
63
        DispersalStrategyInterface $strategy,
64
        CacheProvider $cache,
65
        $prefix,
66
        $uri,
67
        array $options
68
    )
69
    {
0 ignored issues
show
Coding Style introduced by
The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line
Loading history...
70
        $this->client = $client;
71
        $this->prefix = $prefix;
72
        $this->uri = $uri;
73
        $this->strategy = $strategy;
74
        $this->initCache($cache, sha1($uri));
75
        $this->options = $options;
76
    }
77
78
    /**
79
     *
80
     * @param string $endpoint
81
     * @param bool   $withHost
82
     *
83
     * @return string
84
     */
85
    public function buildUrl($endpoint, $withHost = false)
86
    {
87
        $url = "";
88
        $apiDefinition = $this->receiveSwaggerData();
89
90 View Code Duplication
        if ($withHost) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
91
            $url = empty($this->options['host']) ? $apiDefinition->getHost() : $this->options['host'];
92
        }
93
94
        // If the base path is not already included, we need to add it.
95
        $url .= (empty($this->options['includeBasePath']) ? $apiDefinition->getBasePath() : '') . $endpoint;
96
97
        return $url;
98
    }
99
100
    /**
101
     * @param CacheProvider $cache Used cache provider
102
     * @param string        $id    Identifier for the cache item
103
     */
104
    private function initCache(CacheProvider $cache, $id)
105
    {
106
        $this->cache = $cache;
107
        $this->cacheId = $id;
108
        $this->cache->setNamespace(self::CACHE_NS);
109
    }
110
111
    /**
112
     * @return ApiDefinition
113
     */
114
    private function receiveSwaggerData()
115
    {
116
        // 1. is file in cache? › if so return
117
        if ($this->cache->contains($this->cacheId)) {
118
            $apiDef = $this->cache->fetch($this->cacheId);
119
            if (false == $apiDef) {
120
                $this->cache->delete($this->cacheId);
121
                return $this->receiveSwaggerData();
122
            }
123
        }
124
125
        $apiDef = new ApiDefinition();
126
        // get swagger.json from Source
127
        // TODO [taafeba2]: exception handling
128
        $content = $this->client->request('GET', $this->uri);
129
130
        // store current host (name or ip) serving the API. This MUST be the host only and does not include the
131
        // scheme nor sub-paths. It MAY include a port. If the host is not included, the host serving the
132
        // documentation is to be used (including the port)
133
        $parts = parse_url($this->uri);
134
135
        $fallbackHost = array();
136
        $fallbackHost['host'] = sprintf(
137
            '%s://%s:%d',
138
            $parts['scheme'],
139
            $parts['host'],
140
            $parts['port']
141
        );
142
143
        if ($this->strategy->supports($content)) {
0 ignored issues
show
Documentation introduced by
$content is of type object<Psr\Http\Message\ResponseInterface>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
            $apiDef = $this->strategy->process($content, $fallbackHost);
0 ignored issues
show
Documentation introduced by
$content is of type object<Psr\Http\Message\ResponseInterface>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
145
            $this->cache->save($this->cacheId, $apiDef, self::CACHE_TTL);
146
        }
147
148
        return $apiDef;
149
    }
150
}
151