AbstractRequest   C
last analyzed

Complexity

Total Complexity 53

Size/Duplication

Total Lines 290
Duplicated Lines 0 %

Test Coverage

Coverage 77.68%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 86
dl 0
loc 290
ccs 87
cts 112
cp 0.7768
rs 6.96
c 4
b 0
f 0
wmc 53

36 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 7 3
A isFullUri() 0 3 1
A getHeaders() 0 3 1
A getQuery() 0 3 1
A getMethod() 0 3 1
A createFullUri() 0 3 2
A buildMethod() 0 3 2
A getVersion() 0 3 1
A getBody() 0 3 1
A buildUri() 0 3 1
A updateFromQuery() 0 13 1
A getFullUri() 0 7 2
A __construct() 0 4 1
A getDbname() 0 3 1
A buildAuth() 0 3 1
A getUri() 0 3 1
A buildDbname() 0 3 1
A buildQueryParams() 0 8 3
A prepareUserAgent() 0 3 1
A isRaw() 0 3 1
A setFormParams() 0 5 3
A createHandler() 0 5 1
A buildProtocolVersion() 0 3 2
A addHeader() 0 9 2
A getHandler() 0 8 2
A getDb() 0 3 2
A buildHeaders() 0 7 2
A prepareHandlerConfig() 0 3 1
A __unserialize() 0 4 2
A __serialize() 0 3 1
A isSupported() 0 3 1
A buildFormParams() 0 3 1
A serialize() 0 3 1
A getParts() 0 10 3
A unserialize() 0 3 1
A buildBody() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like AbstractRequest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractRequest, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * ActiveRecord for API
4
 *
5
 * @link      https://github.com/hiqdev/yii2-hiart
6
 * @package   yii2-hiart
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\hiart;
12
13
abstract class AbstractRequest implements RequestInterface
14
{
15
    /**
16
     * @var string response implementation to be specified in concrete implementation
17
     */
18
    protected $responseClass;
19
20
    /**
21
     * @var string request handler implementation to be specified in concrete implementation
22
     */
23
    protected $handlerClass;
24
25
    /**
26
     * @var QueryBuilderInterface
27
     */
28
    protected $builder;
29
30
    /**
31
     * @var Query
32
     */
33
    protected $query;
34
35
    /**
36
     * @var string Connection name
37
     */
38
    protected $dbname;
39
40
    /**
41
     * @var array request method
42
     */
43
    protected $method;
44
    protected $uri;
45
    protected $headers = [];
46
    protected $body;
47
    protected $version;
48
49
    protected $isBuilt;
50
    protected array $parts = [];
51
    protected $fullUri;
52
53
    abstract public function send($options = []);
54
55 3
    public function __construct(QueryBuilderInterface $builder, Query $query)
56
    {
57 3
        $this->builder = $builder;
58 3
        $this->query = $query;
59 3
    }
60
61
    public function getDbname()
62
    {
63
        return $this->dbname;
64
    }
65
66 2
    public function getMethod()
67
    {
68 2
        return $this->method;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->method returns the type array which is incompatible with the return type mandated by hiqdev\hiart\RequestInterface::getMethod() of string.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
69
    }
70
71
    public function getUri()
72
    {
73
        return $this->uri;
74
    }
75
76 2
    public function getFullUri()
77
    {
78 2
        if ($this->fullUri === null) {
79 2
            $this->fullUri = $this->createFullUri();
80
        }
81
82 2
        return $this->fullUri;
83
    }
84
85 2
    public function createFullUri()
86
    {
87 2
        return ($this->isFullUri($this->uri) ? '' : $this->getDb()->getBaseUri()) . $this->uri;
0 ignored issues
show
Bug introduced by
The method getBaseUri() does not exist on hiqdev\hiart\ConnectionInterface. It seems like you code against a sub-type of said class. However, the method does not exist in hiqdev\hiart\github\ConnectionInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

87
        return ($this->isFullUri($this->uri) ? '' : $this->getDb()->/** @scrutinizer ignore-call */ getBaseUri()) . $this->uri;
Loading history...
88
    }
89
90 2
    public function isFullUri($uri)
91
    {
92 2
        return preg_match('/^https?:\\/\\//i', (string)$uri);
93
    }
94
95 2
    public function getHeaders()
96
    {
97 2
        return $this->headers;
98
    }
99
100
    public function getBody()
101
    {
102
        return $this->body;
103
    }
104
105 2
    public function getVersion()
106
    {
107 2
        return $this->version;
108
    }
109
110
    /**
111
     * @return Query
112
     */
113 2
    public function getQuery()
114
    {
115 2
        return $this->query;
116
    }
117
118 2
    public function build()
119
    {
120 2
        if ($this->isBuilt === null) {
121 2
            if (!empty($this->query)) {
122 2
                $this->updateFromQuery();
123
            }
124 2
            $this->isBuilt = true;
125
        }
126 2
    }
127
128 2
    protected function updateFromQuery()
129
    {
130 2
        $this->builder->prepare($this->query);
131
132 2
        $this->buildDbname();
133 2
        $this->buildAuth();
134 2
        $this->buildMethod();
135 2
        $this->buildUri();
136 2
        $this->buildQueryParams();
137 2
        $this->buildHeaders();
138 2
        $this->buildBody();
139 2
        $this->buildFormParams();
140 2
        $this->buildProtocolVersion();
141 2
    }
142
143 2
    protected function buildDbname()
144
    {
145 2
        $this->dbname = $this->getDb()->name;
146 2
    }
147
148 2
    protected function buildAuth()
149
    {
150 2
        $this->builder->buildAuth($this->query);
151 2
    }
152
153 2
    protected function buildMethod()
154
    {
155 2
        $this->method = $this->builder->buildMethod($this->query) ?: 'GET';
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->builder->buildMet...($this->query) ?: 'GET' can also be of type string. However, the property $method is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
156 2
    }
157
158 2
    protected function buildUri()
159
    {
160 2
        $this->uri = $this->builder->buildUri($this->query);
161 2
    }
162
163 2
    protected function buildQueryParams()
164
    {
165 2
        $params = $this->builder->buildQueryParams($this->query);
166 2
        if (is_array($params)) {
167 2
            $params = http_build_query($params, '', '&');
168
        }
169 2
        if (!empty($params)) {
170
            $this->uri .= '?' . $params;
171
        }
172 2
    }
173
174 2
    protected function buildHeaders()
175
    {
176 2
        $this->headers = $this->builder->buildHeaders($this->query);
177 2
        if (empty($this->headers['User-Agent'])) {
178 2
            $this->headers['User-Agent'] = $this->prepareUserAgent();
179
        }
180 2
        $this->headers['traceparent'] = $this->getDb()->getTraceparentHeader();
0 ignored issues
show
Bug introduced by
The method getTraceparentHeader() does not exist on hiqdev\hiart\ConnectionInterface. It seems like you code against a sub-type of said class. However, the method does not exist in hiqdev\hiart\github\ConnectionInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

180
        $this->headers['traceparent'] = $this->getDb()->/** @scrutinizer ignore-call */ getTraceparentHeader();
Loading history...
181
    }
182 2
183
    protected function buildBody()
184 2
    {
185 2
        $this->body = $this->builder->buildBody($this->query);
186
    }
187 2
188
    protected function buildFormParams()
189 2
    {
190 2
        $this->setFormParams($this->builder->buildFormParams($this->query));
191
    }
192 2
193
    protected function setFormParams($params)
194 2
    {
195
        if (!empty($params)) {
196
            $this->body = is_array($params) ? http_build_query($params, '', '&') : $params;
197
            $this->headers['Content-Type'] = 'application/x-www-form-urlencoded';
198 2
        }
199
    }
200 2
201
    protected function buildProtocolVersion()
202 2
    {
203 2
        $this->version = $this->builder->buildProtocolVersion($this->query) ?: '1.1';
204
    }
205 2
206
    public function serialize(): string
207 2
    {
208
        return serialize($this->__serialize());
209
    }
210
211
    public function __serialize(): array
212
    {
213
        return $this->getParts();
214
    }
215
216
    public function unserialize(string $serialized): void
217 2
    {
218
        $this->__unserialize(unserialize($serialized));
219 2
    }
220 2
221 2
    public function __unserialize(array $serialized): void
222 2
    {
223
        foreach ($serialized as $key => $value) {
224
            $this->{$key} = $value;
225
        }
226 2
    }
227
228
    public function getParts(): array
229 2
    {
230
        if (empty($this->parts)) {
231 2
            $this->build();
232
            foreach (['dbname', 'method', 'uri', 'headers', 'body', 'version'] as $key) {
233
                $this->parts[$key] = $this->{$key};
234
            }
235
        }
236
237
        return $this->parts;
238
    }
239
240
    public function isRaw()
241
    {
242
        return !empty($this->query->options['raw']);
243
    }
244
245
    public function getHandler()
246
    {
247
        $handler = $this->getDb()->getHandler();
0 ignored issues
show
Bug introduced by
The method getHandler() does not exist on hiqdev\hiart\ConnectionInterface. It seems like you code against a sub-type of said class. However, the method does not exist in hiqdev\hiart\github\ConnectionInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

247
        $handler = $this->getDb()->/** @scrutinizer ignore-call */ getHandler();
Loading history...
248
        if ($handler === null) {
249
            $handler = $this->createHandler();
250
        }
251
252
        return $handler;
253
    }
254
255
    protected function createHandler()
256 2
    {
257
        $config = $this->prepareHandlerConfig($this->getDb()->config);
258 2
259
        return new $this->handlerClass($config);
260
    }
261
262
    protected function prepareHandlerConfig($config)
263
    {
264 2
        return $config;
265
    }
266 2
267
    protected function prepareUserAgent()
268
    {
269
        return $this->getDb()->getUserAgent();
0 ignored issues
show
Bug introduced by
The method getUserAgent() does not exist on hiqdev\hiart\ConnectionInterface. It seems like you code against a sub-type of said class. However, the method does not exist in hiqdev\hiart\github\ConnectionInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

269
        return $this->getDb()->/** @scrutinizer ignore-call */ getUserAgent();
Loading history...
270
    }
271
272
    /**
273
     * @return AbstractConnection|ConnectionInterface
274
     */
275
    public function getDb()
276
    {
277
        return isset($this->builder) ? $this->builder->db : AbstractConnection::getDb($this->dbname);
0 ignored issues
show
Bug introduced by
Accessing db on the interface hiqdev\hiart\QueryBuilderInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
278
    }
279
280
    /**
281
     * @param string $header
282
     * @param string $value
283
     * @return $this
284
     */
285
    public function addHeader($header, $value)
286
    {
287
        if (!isset($this->headers[$header])) {
288
            $this->headers[$header] = [];
289
        }
290
291
        $this->headers[$header][] = $value;
292
293
        return $this;
294
    }
295
296
    /**
297
     * {@inheritdoc}
298
     * Should be declared abstract, but it is not supported in PHP5.
299
     */
300
    public static function isSupported()
301
    {
302
        return false;
303
    }
304
}
305