Passed
Push — master ( c3a84b...bc2aa6 )
by Andrea
13:48 queued 12s
created

ApiManager::setToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 10
rs 10
ccs 0
cts 7
cp 0
crap 12
1
<?php
2
3
/**
4
 * API Manager version 3.0 / embedded into Bicore
5
 * This service provides methods that help to manage API Rest communications.
6
 * Each API client can use it to reduce time to interact with API services
7
 */
8
9
namespace Cdf\BiCoreBundle\Service\Api;
10
11
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
12
use Cdf\BiCoreBundle\Utils\Api\ApiManagerUtil;
13
use Cdf\BiCoreBundle\Utils\String\StringUtils;
14
use Cdf\BiCoreBundle\Service\Api\Oauth2TokenService;
15
use \Exception;
0 ignored issues
show
Bug introduced by
The type \Exception 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...
16
17
/**
18
 * It provides services to use API Rest.
19
 */
20
class ApiManager
21
{
22
23
    private string $project;
24
    private Oauth2TokenService $oauth2Service;
25
    private bool $oauth2Enabled;
26
    private mixed $map;
27
    private object $headerSelector;
28
    private object $config;
29
30
    private ApiManagerUtil $apiManUtil;
31
32
    /**
33
     * Build an ApiManager instance
34
     */
35
    public function __construct(String $oauth2Parameter, Oauth2TokenService $oauth2Service)
36
    {
37
        $this->map = array();
38
        $this->oauth2Service = $oauth2Service;
39
        $this->oauth2Enabled = false;
40
        if ($oauth2Parameter == 1) {
41
            $this->oauth2Enabled = true;
42
        }
43
        $this->apiManUtil = new ApiManagerUtil();
44
    }
45
46
    //Set the project name of client api
47
    public function setProjectName(string $projectName): void
48
    {
49
        $this->project = $projectName;
50
    }
51
52
    //Get the project name of client api
53
    public function getProjectName(): string
54
    {
55
        return $this->project;
56
    }
57
58
    //Allow to set a config and an headerselector for the client api
59
    public function setApiClientConfigs(object $headerSelector, object $config): void
60
    {
61
        $this->headerSelector = $headerSelector;
62
        $this->config = $config;
63
    }
64
65
    private function isApiClientConfigs(): void
66
    {
67
        if (!isset($this->headerSelector) || !isset($this->config)) {
68
            throw new Exception("Header selector not set or Config not set. Set them using setApiClientConfigs() method");
69
        }
70
    }
71
72
    //Return true if oauth2 is enabled
73
    private function isOauth2(): bool
74
    {
75
        return $this->oauth2Enabled;
76
    }
77
78
79
    //generic setup
80
    public function setupCollection(string $collectionString): void
81
    {
82
        $this->setApiController($collectionString);
83
    }
84
85
86
    /**
87
     * Assure that exist an item mapped into ApiManager having the given collection
88
     * and project as key.
89
     */
90
    public function setApiController(String $collection, String $subcollection = ''): void
91
    {
92
        //if not set it throws a new exception
93
        $this->isApiClientConfigs();
94
95
        $apiUtils = new ApiUtils($collection);
96
        $parametri = array('str' => $collection, 'primamaiuscola' => true);
97
        $outcome = StringUtils::toCamelCase($parametri);
98
99
        $subcollectionValue = '';
100
        if (!empty($subcollection)) {
101
            $parametri2 = array('str' => $subcollection, 'primamaiuscola' => true);
102
            $subcollectionValue = StringUtils::toCamelCase($parametri2);
103
        }
104
        //NOT VALID FOR WINDOWS OS
105
        $apiClass = $apiUtils->getApiControllerClass($this->project, $outcome);
106
107
        $apiController = new $apiClass(null, $this->config, $this->headerSelector);
108
        $subArray = [ $subcollection => $subcollectionValue ];
109
        if (!empty($this->map[$collection]['sub-api'])) {
110
            $subArray = $this->map[$collection]['sub-api'][$subcollection] = $subcollectionValue;
111
        }
112
        $this->map($collection, [
113
            'util' => $apiUtils,
114
            'api' => $apiController,
115
            'sub-api' => $subArray,
116
            ]);
117
    }
118
119
    private function map(string $collection, mixed $tools): void
120
    {
121
        if (!isset($this->map[$collection])) {
122
            $this->map[$collection] = $tools;
123
        }
124
    }
125
126
    /**
127
     * It checks if error is due to a Broken Pipe
128
     */
129
    private function isBrokenPipe(Exception &$error) : bool
130
    {
131
        $outcome = false;
132
        if (strpos($error->getMessage(), 'broken pipe') !== false) {
133
            $outcome = true;
134
        }
135
        return $outcome;
136
    }
137
138
    /**
139
     * Set the token managed by wso2TokenService into api-service
140
     * If token is already set, then it doesn't change it
141
     */
142
    private function setToken(mixed $api): string
143
    {
144
        $token = '';
145
        if ($this->isOauth2()) {
146
            $token = $this->oauth2Service->getToken();
147
            if (empty($api->getConfig()->getAccessToken())) {
148
                $this->refreshToken($api, $token);
149
            }
150
        }
151
        return $token;
152
    }
153
154
    /**
155
     * Set the token managed by wso2TokenService into api-service
156
     * If token is already set, it replaces it
157
     */
158
    private function refreshToken(mixed $api, string $token): void
159
    {
160
        if ($this->isOauth2()) {
161
            $api->getConfig()->setAccessToken($token);
162
        }
163
    }
164
165
166
    /**
167
     * Return the proper method to be used
168
     */
169
    private function getMethod(String $collection, String $getMethod, String $subcollection = null): string
170
    {
171
        $tools = $this->map[$collection];
172
        $method = $tools['util']->$getMethod();
173
        if ($subcollection != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollection of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
174
            $method .= $tools['sub-api'][$subcollection];
175
        }
176
        return $method;
177
    }
178
179
180
    /**
181
     * Retry one more time if exception is for broken pipes
182
     */
183
    private function retry(Exception $apiEx, object $object, string $method, mixed $args): mixed
184
    {
185
        if ($this->isBrokenPipe($apiEx)) {
186
            return $object->$method(...$args);
187
        }
188
        throw $apiEx;
189
    }
190
191
    /**
192
     * Return the amount of element existent for the given collection.
193
     */
194
    public function getCount(String $collection, String $subcollection = null): mixed
195
    {
196
        $getCountmethod = $this->getMethod($collection, 'getCount', $subcollection);
197
        $tools = $this->map[$collection];
198
        //the array of arguments
199
        $arguments = array();
200
        if ($subcollection != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollection of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
201
            array_push($arguments, $subcollection);
202
        }
203
        $amount = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $amount is dead and can be removed.
Loading history...
204
        $token = $this->setToken($tools['api']);
205
        try {
206
                $amount = $tools['api']->$getCountmethod(...$arguments);
207
        } catch (\Exception $apiEx) {
208
            $this->refreshToken($tools['api'], $token);
209
            $amount = $this->retry($apiEx, $tools['api'], $getCountmethod, $arguments);
210
        }
211
        return $amount;
212
    }
213
214
    /**
215
     * Get items existent for the given collection, filtered as requested.
216
     */
217
    public function getAll(string $collection, ?int $offset, ?int $limit, mixed $sort = null, ?string $condition, string $subcollection = null): mixed
218
    {
219
        $tools = $this->map[$collection];
220
        $getAllmethod = $this->getMethod($collection, 'getAll', $subcollection);
221
        $results = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $results is dead and can be removed.
Loading history...
222
        //the array of arguments
223
        $arguments = array();
224
        if ($subcollection != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollection of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
225
            array_push($arguments, $subcollection);
226
        }
227
        array_push($arguments, $offset);
228
        array_push($arguments, $limit);
229
        array_push($arguments, $sort);
230
        array_push($arguments, $condition);
231
232
        $token = $this->setToken($tools['api']);
233
        try {
234
                $results = $tools['api']->$getAllmethod(...$arguments);
235
        } catch (\Exception $apiEx) {
236
            $this->refreshToken($tools['api'], $token);
237
            $results = $this->retry($apiEx, $tools['api'], $getAllmethod, $arguments);
238
        }
239
        return $results;
240
    }
241
242
    /**
243
     * Get items existent for the given collection in "to-string" format, filtered as requested.
244
     */
245
    public function getAllToString(string $collection, ?int $offset, ?int $limit, mixed $sort = null, ?string $cond, String $sub = null): mixed
246
    {
247
        $tools = $this->map[$collection];
248
        $getMethod = $this->getMethod($collection, 'getAllToString', $sub);
249
        $results = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $results is dead and can be removed.
Loading history...
250
        //the array of arguments
251
        $arguments = array();
252
        if ($sub != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $sub of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
253
            array_push($arguments, $sub);
254
        }
255
        array_push($arguments, $offset);
256
        array_push($arguments, $limit);
257
        array_push($arguments, $sort);
258
        array_push($arguments, $cond);
259
260
        $token = $this->setToken($tools['api']);
261
        try {
262
            $results = $tools['api']->$getMethod(...$arguments);
263
        } catch (\Exception $apiEx) {
264
            $this->refreshToken($tools['api'], $token);
265
            $results = $this->retry($apiEx, $tools['api'], $getMethod, $arguments);
266
        }
267
        return $results;
268
    }
269
270
      /**
271
     * Get items existent for the given collection, filtered as requested.
272
     * subcollection contains the name of sub-collection if any
273
     * subcollectionVar contains the value of sub-collection if any
274
     */
275
    public function getItem(String $collection, int $id, String $subcollection = null, string $subcollectionVar = null): mixed
276
    {
277
        $tools = $this->map[$collection];
278
        $getAllmethod = $this->getMethod($collection, 'getItem', $subcollection);
279
        $results = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $results is dead and can be removed.
Loading history...
280
        $arguments = array();
281
        if ($subcollectionVar != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollectionVar of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
282
            array_push($arguments, $subcollectionVar);
283
        }
284
        array_push($arguments, $id);
285
        $token = $this->setToken($tools['api']);
286
        try {
287
            $results = $tools['api']->$getAllmethod(...$arguments);
288
        } catch (\Exception $apiEx) {
289
            $this->refreshToken($tools['api'], $token);
290
            $results = $this->retry($apiEx, $tools['api'], $getAllmethod, $arguments);
291
        }
292
        return $results;
293
    }
294
295
    /**
296
     * Delete an existent item
297
     */
298
    public function deleteItem(String $collection, int $id, String $subcollection = null): mixed
299
    {
300
        $tools = $this->map[$collection];
301
        $deleteMethod = $this->getMethod($collection, 'getDelete', $subcollection);
302
        $arguments = array();
303
        if ($subcollection != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollection of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
304
            array_push($arguments, $subcollection);
305
        }
306
        array_push($arguments, $id);
307
        $token = $this->setToken($tools['api']);
308
        try {
309
            $response = $tools['api']->$deleteMethod(...$arguments);
310
        } catch (\Exception $apiEx) {
311
            $this->refreshToken($tools['api'], $token);
312
            $response = $this->retry($apiEx, $tools['api'], $deleteMethod, $arguments);
313
        }
314
        return $response;
315
    }
316
317
318
    /**
319
     * Create the requested object, using the given body item.
320
     */
321
    public function postCreate(String $collection, mixed $body, String $subcollection = null): mixed
322
    {
323
        $tools = $this->map[$collection];
324
        $createMethod = $this->getMethod($collection, 'getCreate', $subcollection);
325
        $results = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $results is dead and can be removed.
Loading history...
326
        $arguments = array();
327
        array_push($arguments, $body);
328
        if ($subcollection != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollection of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
329
            array_push($arguments, $subcollection);
330
        }
331
        $token = $this->setToken($tools['api']);
332
        try {
333
            $results = $tools['api']->$createMethod(...$arguments);
334
        } catch (\Exception $apiEx) {
335
            $this->refreshToken($tools['api'], $token);
336
            $results = $this->retry($apiEx, $tools['api'], $createMethod, $arguments);
337
        }
338
        return $results;
339
    }
340
341
342
     /**
343
     * Create the requested object, using the given body item.
344
     */
345
    public function postUpdate(String $collection, object $body, int $id, String $subcollection = null): mixed
346
    {
347
        $tools = $this->map[$collection];
348
        $createMethod = $this->getMethod($collection, 'getUpdateItem', $subcollection);
349
        $results = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $results is dead and can be removed.
Loading history...
350
        $arguments = array();
351
        array_push($arguments, $body);
352
        array_push($arguments, $id);
353
        if ($subcollection != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subcollection of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
354
            array_push($arguments, $subcollection);
355
        }
356
        $token = $this->setToken($tools['api']);
357
        try {
358
            $results = $tools['api']->$createMethod(...$arguments);
359
        } catch (\Exception $apiEx) {
360
            $this->refreshToken($tools['api'], $token);
361
            $results = $this->retry($apiEx, $tools['api'], $createMethod, $arguments);
362
        }
363
        return $results;
364
    }
365
366
    /**
367
     * It prepares entity values so that they can be used with types compliant with BiCoreBundle.
368
     * For example it transforms a date that arrive in string format into a DateTime.
369
     * @deprecated: evaluate to migrate on ApiManagerUtil
370
     */
371
    public function setupApiValues(mixed $entityout): mixed
372
    {
373
        return $this->apiManUtil->setupApiValues($entityout);
374
    }
375
376
    /**
377
     * Map first object transformed into the second where possible,
378
     * attempting to map each field of first into field of the second.
379
     * @deprecated: evaluate to migrate on ApiManagerUtil
380
     */
381
    public function mapData(object $modelEntity, object $controllerItem): mixed
382
    {
383
        return $this->apiManUtil->mapData($modelEntity, $controllerItem);
384
    }
385
}
386