Passed
Push — master ( e0ef62...90fcea )
by Rodrigo
01:56
created

CittaApi::setUrlBase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
/**
3
 *
4
 * @author Rodrigo Dornelles <[email protected]> <[email protected]>
5
 * 
6
 * @copyright Copyright (c) 2019 Dynamika Web
7
 * @link https://github.com/dynamikaweb/yii2-citta-api
8
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
9
 */
10
11
namespace dynamikaweb\api;
12
13
use Yii;
0 ignored issues
show
Bug introduced by
The type Yii was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
15
/** 
16
 * dynamikaweb\api\CittaApi 
17
 */
18
class CittaApi
19
{   
20
    /**
21
     * @param string $url_base
22
     * @param integer $max_redirect 
23
     */
24
    private static $url_base;
25
    private static $max_redirect = 10;
26
27
    /** 
28
     * __construct
29
     * 
30
     * @deprecated
31
     */ 
32
    private function  __construct()
33
    {
34
35
    }
36
37
    /**
38
     * setUrlBase
39
     * 
40
     * @param string $uri
41
     */
42
    public static function setUrlBase($uri)
43
    {
44
        self::$url_base = $uri;
45
    }
46
47
    /**
48
     * getUrlBase
49
     * 
50
     * @throws dynamikaweb\api\CittaException
51
     * 
52
     * @return string
53
     */
54
    public static function getUrlBase()
55
    {
56
        if (!self::$url_base) {
57
            throw new CittaException('URL Base Not Set');
58
        }
59
60
        if (!is_string(self::$url_base)){
61
            throw new CittaException('URL Base Type Error');
62
        }
63
64
        return self::$url_base;
65
    }
66
67
    /**
68
     * getUrl
69
     * 
70
     * @param string|array $uri 
71
     * 
72
     * @see yii\helpers\Url
73
     * @throws dynamikaweb\api\CittaException
74
     * 
75
     * @return string
76
     */
77
    public static function getUrlTo($uri)
78
    {
79
        if (is_array($uri)) {
80
            return strtr("{base_url}{uri}",[
81
                "{base_url}" => self::getUrlBase(),
82
                "{uri}" => \yii\helpers\Url::to($uri)
0 ignored issues
show
Bug introduced by
The type yii\helpers\Url was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
83
            ]);
84
        } else if (is_string($uri)) {
0 ignored issues
show
introduced by
The condition is_string($uri) is always true.
Loading history...
85
            return strtr("{base_url}/{uri}",[
86
                "{base_url}" => self::getUrlBase(),
87
                "{uri}" => $uri
88
            ]);
89
        }
90
        
91
        throw new CittaException('URI Request Type Error');
92
    }
93
94
    /**
95
     * makeRequest
96
     * 
97
     * @param string $uri
98
     * 
99
     * @return object
100
     */
101
    private static function makeRequest($uri)
102
    {
103
        $curl = new \Curl\Curl();
104
        $attemps = 0;
105
106
        // get link
107
        $request = self::getUrlTo($uri);
108
109
        // try
110
        do {
111
            $result = $curl->get($request);
0 ignored issues
show
Bug introduced by
The method get() does not exist on Curl\Curl. ( Ignorable by Annotation )

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

111
            /** @scrutinizer ignore-call */ 
112
            $result = $curl->get($request);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
112
        }
113
        // redirect
114
        while (self::remakeRequest($request, $attemps, $result));
115
116
        return $result;
117
    }  
118
119
    /**
120
     * remakeRequest
121
     * 
122
     * @property 
123
     * 
124
     * @param string $uri
125
     * @param integer $attemps
126
     * @param object $result
127
     * 
128
     * @throws dynamikaweb\api\CittaException
129
     * 
130
     * @return boolean
131
     */
132
    private static function remakeRequest(&$uri, &$attemps, $result)
133
    {
134
        // success
135
        if (300 > $result->http_status_code || $result->http_status_code >= 400) {
136
            return false;
137
        }
138
139
        // probably loop
140
        if ($attemps++ >= self::$max_redirect) {
141
            throw new CittaException('Too many redirects');
142
        }
143
144
        foreach ($result->response_headers as $header) {
145
            if (strpos($header, 'Location:') === false) {
146
                continue;
147
            }
148
149
            // new url
150
            $uri = strtr($header, [
151
                'Location: ' => '',
152
                'location: ' => '',
153
                'Location:' => '',
154
                'location:' => ''
155
            ]);
156
        }
157
158
        return true;
159
    }
160
161
    /**
162
     * cacheFindAll
163
     * 
164
     * @see yii\helpers\Json
165
     * @see yii\helpers\ArrayHelper
166
     * @see yii\data\ArrayDataProvider
167
     *
168
     * @param array|string $uri 
169
     * @param array|void $dataProviderParams
170
     * @param array|void $cacheParams
171
     * 
172
     * @throws dynamikaweb\api\CittaException
173
     * 
174
     * @return object
175
     */
176
    public static function cacheFindAll($uri, $dataProviderParams = [], $cacheParams = [])
177
    {
178
        $key = base64_encode($uri);
0 ignored issues
show
Bug introduced by
It seems like $uri can also be of type array; however, parameter $data of base64_encode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

178
        $key = base64_encode(/** @scrutinizer ignore-type */ $uri);
Loading history...
179
180
        if (!Yii::$app->cache->exists($key)){
181
            Yii::$app->cache->set($key, self::findAll($uri, $dataProviderParams), $cacheParams);
182
        }
183
184
        return Yii::$app->cache->get($key);
185
    }
186
187
    /**
188
     * findAll
189
     * 
190
     * @see yii\helpers\Json
191
     * @see yii\helpers\ArrayHelper
192
     * @see yii\data\ArrayDataProvider
193
     *
194
     * @param array|string $uri 
195
     * @param array|void $dataProviderParams
196
     * 
197
     * @throws dynamikaweb\api\CittaException
198
     * 
199
     * @return object
200
     */
201
    public static function findAll($uri, $dataProviderParams = [])
202
    {
203
        // call api
204
        $result = self::makeRequest($uri);
0 ignored issues
show
Bug introduced by
It seems like $uri can also be of type array; however, parameter $uri of dynamikaweb\api\CittaApi::makeRequest() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

204
        $result = self::makeRequest(/** @scrutinizer ignore-type */ $uri);
Loading history...
205
206
        // http return a error
207
        if ($result->error && $result->http_status_code) {
208
            throw new CittaException(strtr('HTTP Status {code} Error: {error}', [ 
209
                    '{error}' => \yii\helpers\ArrayHelper::getValue(\yii\helpers\Json::decode($result->response, true), 'message', null),
0 ignored issues
show
Bug introduced by
The type yii\helpers\ArrayHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type yii\helpers\Json was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
210
                    '{code}' => $result->http_status_code
211
                 ])
212
            );
213
        }
214
215
        // curl return a error
216
        if ($result->error) {
217
            throw new CittaException($result->error_message);
218
        }
219
220
        // decode json
221
        $data = \yii\helpers\Json::decode($result->response, true);
222
        
223
        // return response data
224
        return new \yii\data\ArrayDataProvider(
0 ignored issues
show
Bug introduced by
The type yii\data\ArrayDataProvider was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
225
            \yii\Helpers\ArrayHelper::merge(
0 ignored issues
show
Bug introduced by
The type yii\Helpers\ArrayHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
226
                [
227
                    'allModels' =>  \yii\helpers\ArrayHelper::getValue($data, 'data', $data), // adapt data|root for unique patern
228
                    'totalCount' => \yii\helpers\ArrayHelper::getValue($data, 'count', count($data)), // total count api            
229
                    'pagination' => [
230
                        'pageSize' => \yii\helpers\ArrayHelper::getValue($uri, 'size', false),
231
                        'page' => false
232
                    ]
233
                ],
234
                $dataProviderParams
235
            )
236
        );
237
    }
238
}
239