Completed
Push — master ( f4889a...d7a000 )
by Andrii
05:14
created

AbstractRequest::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
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-2017, 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 $parts = [];
51
    protected $fullUri;
52
53
    abstract public function send($options = []);
54
55
    public function __construct(QueryBuilderInterface $builder, Query $query)
56
    {
57
        $this->builder = $builder;
58
        $this->query = $query;
59
    }
60
61
    public function getDbname()
62
    {
63
        return $this->dbname;
64
    }
65
66
    public function getMethod()
67
    {
68
        return $this->method;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->method; (array) is incompatible with the return type declared by the interface hiqdev\hiart\RequestInterface::getMethod of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
69
    }
70
71
    public function getUri()
72
    {
73
        return $this->uri;
74
    }
75
76
    public function getFullUri()
77
    {
78
        if ($this->fullUri === null) {
79
            $this->fullUri = $this->createFullUri();
80
        }
81
82
        return $this->fullUri;
83
    }
84
85
    public function createFullUri()
86
    {
87
        return ($this->isFullUri($this->uri) ? '' : $this->getDb()->getBaseUri()) . $this->uri;
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface hiqdev\hiart\ConnectionInterface as the method getBaseUri() does only exist in the following implementations of said interface: hiqdev\hiart\AbstractConnection, hiqdev\hiart\rest\Connection.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
88
    }
89
90
    public function isFullUri($uri)
91
    {
92
        return preg_match('/^https?:\\/\\//i', $uri);
93
    }
94
95
    public function getHeaders()
96
    {
97
        return $this->headers;
98
    }
99
100
    public function getBody()
101
    {
102
        return $this->body;
103
    }
104
105
    public function getVersion()
106
    {
107
        return $this->version;
108
    }
109
110
    /**
111
     * @return Query
112
     */
113
    public function getQuery()
114
    {
115
        return $this->query;
116
    }
117
118
    protected function build()
119
    {
120
        if ($this->isBuilt === null) {
121
            if (!empty($this->query)) {
122
                $this->updateFromQuery();
123
            }
124
            $this->isBuilt = true;
125
        }
126
    }
127
128
    protected function updateFromQuery()
129
    {
130
        $this->builder->prepare($this->query);
131
132
        $this->buildDbname();
133
        $this->buildAuth();
134
        $this->buildMethod();
135
        $this->buildUri();
136
        $this->buildQueryParams();
137
        $this->buildHeaders();
138
        $this->buildBody();
139
        $this->buildFormParams();
140
        $this->buildProtocolVersion();
141
    }
142
143
    protected function buildDbname()
144
    {
145
        $this->dbname = $this->getDb()->name;
0 ignored issues
show
Bug introduced by
Accessing name on the interface hiqdev\hiart\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
146
    }
147
148
    protected function buildAuth()
149
    {
150
        $this->builder->buildAuth($this->query);
151
    }
152
153
    protected function buildMethod()
154
    {
155
        $this->method = $this->builder->buildMethod($this->query) ?: 'GET';
156
    }
157
158
    protected function buildUri()
159
    {
160
        $this->uri = $this->builder->buildUri($this->query);
161
    }
162
163
    protected function buildQueryParams()
164
    {
165
        $params = $this->builder->buildQueryParams($this->query);
166
        if (is_array($params)) {
167
            $params = http_build_query($params, '', '&');
168
        }
169
        if (!empty($params)) {
170
            $this->uri .= '?' . $params;
171
        }
172
    }
173
174
    protected function buildHeaders()
175
    {
176
        $this->headers = $this->builder->buildHeaders($this->query);
177
        if (empty($this->headers['User-Agent'])) {
178
            $this->headers['User-Agent'] = $this->prepareUserAgent();
179
        }
180
    }
181
182
    protected function buildBody()
183
    {
184
        $this->body = $this->builder->buildBody($this->query);
185
    }
186
187
    protected function buildFormParams()
188
    {
189
        $this->setFormParams($this->builder->buildFormParams($this->query));
190
    }
191
192
    protected function setFormParams($params)
193
    {
194
        if (!empty($params)) {
195
            $this->body = is_array($params) ? http_build_query($params, '', '&') : $params;
196
            $this->headers['Content-Type'] = 'application/x-www-form-urlencoded';
197
        }
198
    }
199
200
    protected function buildProtocolVersion()
201
    {
202
        $this->version = $this->builder->buildProtocolVersion($this->query) ?: '1.1';
203
    }
204
205
    public function serialize()
206
    {
207
        return serialize($this->getParts());
208
    }
209
210
    public function unserialize($string)
211
    {
212
        foreach (unserialize($string) as $key => $value) {
213
            $this->{$key} = $value;
214
        }
215
    }
216
217
    public function getParts()
218
    {
219
        if (empty($this->parts)) {
220
            $this->build();
221
            foreach (['dbname', 'method', 'uri', 'headers', 'body', 'version'] as $key) {
222
                $this->parts[$key] = $this->{$key};
223
            }
224
        }
225
226
        return $this->parts;
227
    }
228
229
    public function isRaw()
230
    {
231
        return !empty($this->query->options['raw']);
232
    }
233
234
    protected function getHandler()
235
    {
236
        $handler = $this->getDb()->getHandler();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface hiqdev\hiart\ConnectionInterface as the method getHandler() does only exist in the following implementations of said interface: hiqdev\hiart\AbstractConnection, hiqdev\hiart\rest\Connection.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
237
        if ($handler === null) {
238
            $handler = $this->createHandler();
239
        }
240
241
        return $handler;
242
    }
243
244
    protected function createHandler()
245
    {
246
        $config = $this->prepareHandlerConfig($this->getDb()->config);
0 ignored issues
show
Bug introduced by
Accessing config on the interface hiqdev\hiart\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
247
248
        return new $this->handlerClass($config);
249
    }
250
251
    protected function prepareHandlerConfig($config)
252
    {
253
        return $config;
254
    }
255
256
    protected function prepareUserAgent()
257
    {
258
        return $this->getDb()->getUserAgent();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface hiqdev\hiart\ConnectionInterface as the method getUserAgent() does only exist in the following implementations of said interface: hiqdev\hiart\AbstractConnection, hiqdev\hiart\rest\Connection.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
259
    }
260
261
    /**
262
     * @return AbstractConnection|ConnectionInterface
263
     */
264
    public function getDb()
265
    {
266
        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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
267
    }
268
269
    abstract public static function isSupported();
270
}
271