Config   F
last analyzed

Complexity

Total Complexity 69

Size/Duplication

Total Lines 674
Duplicated Lines 0 %

Test Coverage

Coverage 91.71%

Importance

Changes 0
Metric Value
wmc 69
eloc 172
dl 0
loc 674
ccs 166
cts 181
cp 0.9171
rs 2.88
c 0
b 0
f 0

52 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getClientId() 0 3 1
A fromArray() 0 15 2
A setScope() 0 11 3
A setClientId() 0 5 1
A getScope() 0 19 4
A setProject() 0 5 1
A setClientSecret() 0 5 1
A getProject() 0 3 1
A getClientSecret() 0 3 1
A camelize() 0 10 1
A getBearerToken() 0 3 1
A setClientOptions() 0 4 1
A getThrowExceptions() 0 3 1
A getUsername() 0 3 1
A getAcceptEncoding() 0 3 1
A setAdapter() 0 5 1
A setAnonymousId() 0 5 1
A isEnableCorrelationId() 0 3 1
A getAnonymousId() 0 3 1
A getAdapter() 0 3 1
A getRefreshToken() 0 3 1
A setCorrelationIdProvider() 0 5 1
A getPassword() 0 3 1
A of() 0 3 1
A getLogLevel() 0 3 1
A setMessageFormatter() 0 4 1
A setThrowExceptions() 0 5 1
A getOAuthClientOptions() 0 3 1
A getClientOptions() 0 3 1
A getGrantType() 0 3 1
A setAcceptEncoding() 0 5 1
A setRefreshToken() 0 5 1
A setCacheDir() 0 5 1
A setLogLevel() 0 5 1
A setBearerToken() 0 4 1
A setPassword() 0 5 1
A getCacheDir() 0 3 1
A getMessageFormatter() 0 3 1
A setBatchPoolSize() 0 6 1
A getCorrelationIdProvider() 0 9 3
A check() 0 15 6
A getBatchPoolSize() 0 6 2
A getClientCredentials() 0 6 1
A setApiUrl() 0 5 1
A setUsername() 0 5 1
A setEnableCorrelationId() 0 4 1
A setGrantType() 0 5 1
A setOAuthClientOptions() 0 4 1
A getApiUrl() 0 3 1
A setOauthUrl() 0 5 1
A getOauthUrl() 0 13 4

How to fix   Complexity   

Complex Class

Complex classes like Config 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 Config, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @author @jenschude <[email protected]>
4
 * @created: 20.01.15, 17:54
5
 */
6
7
namespace Commercetools\Core;
8
9
use Commercetools\Core\Client\OAuth\ClientCredentials;
10
use Commercetools\Core\Error\Message;
11
use Commercetools\Core\Error\InvalidArgumentException;
12
use Commercetools\Core\Helper\CorrelationIdProvider;
13
use Commercetools\Core\Helper\DefaultCorrelationIdProvider;
14
use Commercetools\Core\Helper\Uuid;
15
use Commercetools\Core\Model\Common\ContextAwareInterface;
16
use Commercetools\Core\Model\Common\ContextTrait;
17
use Psr\Log\LogLevel;
18
19
/**
20
 * Client configuration object
21
 *
22
 * @description
23
 *
24
 * Often configuration like credentials is stored in YAML or INI files. To setup the configuration object
25
 * this can be done by the fromArray method.
26
 *
27
 * Configuration file:
28
 *
29
 * ```
30
 * [commercetools]
31
 * client_id = '<client-id>'
32
 * client_secret = '<client-secret>'
33
 * project = '<project>'
34
 * ```
35
 *
36
 * Config instantiation:
37
 *
38
 * ```php
39
 * $iniConfig = parse_ini_file('<config-file>.ini', true);
40
 * $config = Config::fromArray($iniConfig['commercetools']);
41
 * ```
42
 *
43
 * ### Exceptions ###
44
 *
45
 * The client by default suppresses exceptions when a response had been returned by the API and the result
46
 * can be handled afterwards by checking the isError method of the response. For interacting with Exceptions
47
 * they can be enabled with the throwExceptions flag.
48
 *
49
 * ```php
50
 * $config->setThrowExceptions(true);
51
 * $client = new Client($config);
52
 * try {
53
 *     $response = $client->execute($request);
54
 * } catch (\Commercetools\Core\Error\ApiException $e) {
55
 *     // handle Exception
56
 * }
57
 * ```
58
 * @package Commercetools\Core
59
 */
60
class Config implements ContextAwareInterface
61
{
62
    use ContextTrait;
63
64
    const OAUTH_URL = 'oauth_url';
65
    const CLIENT_ID = 'client_id';
66
    const CLIENT_SECRET = 'client_secret';
67
    const SCOPE = 'scope';
68
    const PROJECT = 'project';
69
    const API_URL = 'api_url';
70
    const USER_NAME = 'username';
71
    const PASSWORD = 'password';
72
    const REFRESH_TOKEN = 'refresh_token';
73
    const BEARER_TOKEN = 'bearer_token';
74
    const ANONYMOUS_ID = 'anonymous_id';
75
    const GRANT_TYPE = 'grant_type';
76
77
    const GRANT_TYPE_CLIENT = 'client_credentials';
78
    const GRANT_TYPE_PASSWORD = 'password';
79
    const GRANT_TYPE_REFRESH = 'refresh_token';
80
    const GRANT_TYPE_ANONYMOUS = 'anonymous_token';
81
    const GRANT_TYPE_BEARER_TOKEN = 'bearer_token';
82
83
    /**
84
     * @var string
85
     */
86
    protected $clientSecret;
87
88
    /**
89
     * @var string
90
     */
91
    protected $clientId;
92
93
    /**
94
     * @var string
95
     */
96
    protected $project;
97
98
    /**
99
     * @var array
100
     */
101
    protected $scope = ['manage_project'];
102
103
    /**
104
     * @var string
105
     */
106
    protected $oauthUrl = 'https://auth.europe-west1.gcp.commercetools.com';
107
108
    /**
109
     * @var string
110
     */
111
    protected $apiUrl = 'https://api.europe-west1.gcp.commercetools.com';
112
113
    /**
114
     * @var int
115
     */
116
    protected $batchPoolSize = 25;
117
118
    protected $adapter;
119
120
    /**
121
     * @var bool
122
     */
123
    protected $throwExceptions = false;
124
125
    protected $acceptEncoding = 'gzip';
126
127
    protected $grantType = 'client_credentials';
128
129
    /**
130
     * @var string
131
     */
132
    protected $username;
133
134
    /**
135
     * @var string
136
     */
137
    protected $password;
138
139
    /**
140
     * @var string
141
     */
142
    protected $refreshToken;
143
144
    /**
145
     * @var string
146
     */
147
    protected $bearerToken;
148
149
    /**
150
     * @var string
151
     */
152
    protected $anonymousId;
153
154
    /**
155
     * @var string
156
     */
157
    protected $cacheDir;
158
159
    /**
160
     * @var string
161
     */
162
    protected $logLevel = LogLevel::INFO;
163
164
    protected $messageFormatter;
165
166
    /**
167
     * @var bool
168
     */
169
    protected $enableCorrelationId = false;
170
171
    /**
172
     * @var CorrelationIdProvider
173
     */
174
    protected $correlationIdProvider;
175
176
    protected $clientOptions = [];
177
178
    protected $oauthClientOptions = [];
179
180 128
    public function __construct()
181
    {
182 128
        $this->enableCorrelationId = Uuid::active();
183 128
    }
184
185
    /**
186
     * @param array $configValues
187
     * @return static
188
     */
189 121
    public static function fromArray(array $configValues)
190
    {
191 121
        $config = static::of();
192 121
        array_walk(
193 121
            $configValues,
194 121
            function ($value, $key) use ($config) {
195 119
                $functionName = 'set' . $config->camelize($key);
196 119
                if (!is_callable([$config, $functionName])) {
197 1
                    throw new InvalidArgumentException(sprintf(Message::SETTER_NOT_IMPLEMENTED, $key));
198
                }
199 118
                $config->$functionName($value);
200 121
            }
201
        );
202
203 120
        return $config;
204
    }
205
206 119
    protected function camelize($scored)
207
    {
208 119
        return lcfirst(
209 119
            implode(
210 119
                '',
211 119
                array_map(
212 119
                    'ucfirst',
213 119
                    array_map(
214 119
                        'strtolower',
215 119
                        explode('_', $scored)
216
                    )
217
                )
218
            )
219
        );
220
    }
221
222
    /**
223
     * @return string
224
     */
225 95
    public function getClientSecret()
226
    {
227 95
        return $this->clientSecret;
228
    }
229
230
    /**
231
     * @param string $clientSecret
232
     * @return $this
233
     */
234 109
    public function setClientSecret($clientSecret)
235
    {
236 109
        $this->clientSecret = $clientSecret;
237
238 109
        return $this;
239
    }
240
241
    /**
242
     * @return string
243
     */
244 99
    public function getClientId()
245
    {
246 99
        return $this->clientId;
247
    }
248
249
    /**
250
     * @param string $clientId
251
     * @return $this
252
     */
253 109
    public function setClientId($clientId)
254
    {
255 109
        $this->clientId = $clientId;
256
257 109
        return $this;
258
    }
259
260
    /**
261
     * @return string
262
     */
263 131
    public function getProject()
264
    {
265 131
        return $this->project;
266
    }
267
268
    /**
269
     * @param string $project
270
     * @return $this
271
     */
272 119
    public function setProject($project)
273
    {
274 119
        $this->project = $project;
275
276 119
        return $this;
277
    }
278
279
    /**
280
     * @return string
281
     */
282 89
    public function getScope()
283
    {
284 89
        $scope = $this->scope;
285 89
        $project = $this->getProject();
286
287 89
        $permissions = [];
288 89
        foreach ($scope as $key => $value) {
289 84
            if (is_numeric($key)) { // scope defined as string e.g. scope:project_key
290 83
                if (strpos($value, ':') === false) { // scope without project key
291 82
                    $value = $value . ':' . $project;
292
                }
293 83
                $permissions[] = $value;
294
            } else { // scope defined as array
295 2
                $permissions[] = $key . ':' . $value;
296
            }
297
        }
298 89
        $scope = implode(' ', $permissions);
299
300 89
        return $scope;
301
    }
302
303
    /**
304
     * @param string $scope
305
     * @return $this
306
     */
307 71
    public function setScope($scope)
308
    {
309 71
        if (empty($scope)) {
310 5
            $scope = [];
311
        }
312 71
        if (!is_array($scope)) {
313 33
            $scope = explode(' ', $scope);
314
        }
315 71
        $this->scope = $scope;
316
317 71
        return $this;
318
    }
319
320
    /**
321
     * @param string|null $grantType
322
     * @return string
323
     */
324 73
    public function getOauthUrl($grantType = null)
325
    {
326 73
        if (is_null($grantType)) {
327 73
            $grantType = $this->getGrantType();
328
        }
329
330
        switch ($grantType) {
331 73
            case static::GRANT_TYPE_ANONYMOUS:
332 19
                return $this->oauthUrl . '/oauth/' . $this->getProject() . '/anonymous/token';
333 70
            case static::GRANT_TYPE_PASSWORD:
334 29
                return $this->oauthUrl . '/oauth/' . $this->getProject() . '/customers/token';
335
            default:
336 69
                return $this->oauthUrl . '/oauth/token';
337
        }
338
    }
339
340
    /**
341
     * @param string $oauthUrl
342
     * @return $this
343
     */
344 50
    public function setOauthUrl($oauthUrl)
345
    {
346 50
        $this->oauthUrl = $oauthUrl;
347
348 50
        return $this;
349
    }
350
351
    /**
352
     * @return string
353
     */
354 86
    public function getApiUrl()
355
    {
356 86
        return $this->apiUrl;
357
    }
358
359
    /**
360
     * @param string $apiUrl
361
     * @return $this
362
     */
363 50
    public function setApiUrl($apiUrl)
364
    {
365 50
        $this->apiUrl = $apiUrl;
366
367 50
        return $this;
368
    }
369
370
    /**
371
     * @return bool
372
     */
373 83
    public function check()
374
    {
375 83
        if (is_null($this->getClientId()) && $this->getGrantType() !== self::GRANT_TYPE_BEARER_TOKEN) {
0 ignored issues
show
introduced by
The condition is_null($this->getClientId()) is always false.
Loading history...
376 4
            throw new InvalidArgumentException(Message::NO_CLIENT_ID);
377
        }
378
379 79
        if (is_null($this->getClientSecret()) && $this->getGrantType() !== self::GRANT_TYPE_BEARER_TOKEN) {
0 ignored issues
show
introduced by
The condition is_null($this->getClientSecret()) is always false.
Loading history...
380
            throw new InvalidArgumentException(Message::NO_CLIENT_SECRET);
381
        }
382
383 79
        if (is_null($this->getProject())) {
0 ignored issues
show
introduced by
The condition is_null($this->getProject()) is always false.
Loading history...
384
            throw new InvalidArgumentException(Message::NO_PROJECT_ID);
385
        }
386
387 79
        return true;
388
    }
389
390
    /**
391
     * @deprecated use getClientOptions()['concurrency'] instead
392
     * @return int
393
     */
394 1
    public function getBatchPoolSize()
395
    {
396 1
        if (!isset($this->clientOptions['concurrency'])) {
397 1
            return $this->batchPoolSize;
398
        }
399 1
        return $this->clientOptions['concurrency'];
400
    }
401
402
    /**
403
     * @deprecated use setClientOptions(['concurrency' => 5]) instead
404
     * @param int $batchPoolSize
405
     * @return $this
406
     */
407 1
    public function setBatchPoolSize($batchPoolSize)
408
    {
409 1
        $this->clientOptions['concurrency'] = $batchPoolSize;
410 1
        $this->batchPoolSize = $batchPoolSize;
411
412 1
        return $this;
413
    }
414
415
    /**
416
     * @return string
417
     */
418 71
    public function getAdapter()
419
    {
420 71
        return $this->adapter;
421
    }
422
423
    /**
424
     * @param string $adapter
425
     * @return $this
426
     */
427
    public function setAdapter($adapter)
428
    {
429
        $this->adapter = $adapter;
430
431
        return $this;
432
    }
433
434
    /**
435
     * @return bool
436
     */
437 54
    public function getThrowExceptions()
438
    {
439 54
        return $this->throwExceptions;
440
    }
441
442
    /**
443
     * @param bool $throwExceptions
444
     * @return $this
445
     */
446 15
    public function setThrowExceptions($throwExceptions)
447
    {
448 15
        $this->throwExceptions = (bool)$throwExceptions;
449
450 15
        return $this;
451
    }
452
453
    /**
454
     * @return string
455
     */
456 97
    public function getAcceptEncoding()
457
    {
458 97
        return $this->acceptEncoding;
459
    }
460
461
    /**
462
     * @param string $acceptEncoding
463
     * @return $this
464
     */
465
    public function setAcceptEncoding($acceptEncoding)
466
    {
467
        $this->acceptEncoding = $acceptEncoding;
468
469
        return $this;
470
    }
471
472
    /**
473
     * @return static
474
     */
475 123
    public static function of()
476
    {
477 123
        return new static();
478
    }
479
480
    /**
481
     * @return string
482
     */
483 88
    public function getGrantType()
484
    {
485 88
        return $this->grantType;
486
    }
487
488
    /**
489
     * @param string $grantType
490
     * @return $this
491
     */
492 28
    public function setGrantType($grantType)
493
    {
494 28
        $this->grantType = $grantType;
495
496 28
        return $this;
497
    }
498
499
    /**
500
     * @return string
501
     */
502 15
    public function getUsername()
503
    {
504 15
        return $this->username;
505
    }
506
507
    /**
508
     * @param string $username
509
     * @return $this
510
     */
511 20
    public function setUsername($username)
512
    {
513 20
        $this->username = $username;
514
515 20
        return $this;
516
    }
517
518
    /**
519
     * @return string
520
     */
521 15
    public function getPassword()
522
    {
523 15
        return $this->password;
524
    }
525
526
    /**
527
     * @param string $password
528
     * @return $this
529
     */
530 20
    public function setPassword($password)
531
    {
532 20
        $this->password = $password;
533
534 20
        return $this;
535
    }
536
537
    /**
538
     * @return string
539
     */
540 20
    public function getRefreshToken()
541
    {
542 20
        return $this->refreshToken;
543
    }
544
545
    /**
546
     * @param string $refreshToken
547
     * @return $this
548
     */
549 20
    public function setRefreshToken($refreshToken)
550
    {
551 20
        $this->refreshToken = $refreshToken;
552
553 20
        return $this;
554
    }
555
556
    /**
557
     * @return string
558
     */
559 7
    public function getAnonymousId()
560
    {
561 7
        return $this->anonymousId;
562
    }
563
564
    /**
565
     * @param string $anonymousId
566
     * @return $this
567
     */
568 2
    public function setAnonymousId($anonymousId)
569
    {
570 2
        $this->anonymousId = $anonymousId;
571
572 2
        return $this;
573
    }
574
575
    /**
576
     * @return string
577
     */
578 100
    public function getCacheDir()
579
    {
580 100
        return $this->cacheDir;
581
    }
582
583
    /**
584
     * @param string $cacheDir
585
     * @return $this
586
     */
587
    public function setCacheDir($cacheDir)
588
    {
589
        $this->cacheDir = $cacheDir;
590
591
        return $this;
592
    }
593
594
    /**
595
     * @return string
596
     */
597 33
    public function getLogLevel()
598
    {
599 33
        return $this->logLevel;
600
    }
601
602
    /**
603
     * @param string $logLevel
604
     * @return $this
605
     */
606 1
    public function setLogLevel($logLevel)
607
    {
608 1
        $this->logLevel = $logLevel;
609
610 1
        return $this;
611
    }
612
613
    /**
614
     * @return mixed
615
     */
616 33
    public function getMessageFormatter()
617
    {
618 33
        return $this->messageFormatter;
619
    }
620
621
    /**
622
     * @param mixed $messageFormatter
623
     * @return $this
624
     */
625
    public function setMessageFormatter($messageFormatter)
626
    {
627
        $this->messageFormatter = $messageFormatter;
628
        return $this;
629
    }
630
631
    /**
632
     * @return CorrelationIdProvider|null
633
     */
634 96
    public function getCorrelationIdProvider()
635
    {
636 96
        if (!$this->isEnableCorrelationId()) {
637
            return null;
638
        }
639 96
        if (is_null($this->correlationIdProvider)) {
640 94
            $this->correlationIdProvider = DefaultCorrelationIdProvider::of($this->getProject());
641
        }
642 96
        return $this->correlationIdProvider;
643
    }
644
645
    /**
646
     * @param CorrelationIdProvider $correlationIdProvider
647
     * @return Config
648
     */
649 2
    public function setCorrelationIdProvider(CorrelationIdProvider $correlationIdProvider)
650
    {
651 2
        $this->correlationIdProvider = $correlationIdProvider;
652 2
        $this->setEnableCorrelationId(true);
653 2
        return $this;
654
    }
655
656
    /**
657
     * @return bool
658
     */
659 96
    public function isEnableCorrelationId()
660
    {
661 96
        return $this->enableCorrelationId;
662
    }
663
664
    /**
665
     * @param bool $enableCorrelationId
666
     * @return Config
667
     */
668 2
    public function setEnableCorrelationId($enableCorrelationId)
669
    {
670 2
        $this->enableCorrelationId = (bool)$enableCorrelationId;
671 2
        return $this;
672
    }
673
674
    /**
675
     * @return array
676
     */
677 80
    public function getClientOptions()
678
    {
679 80
        return $this->clientOptions;
680
    }
681
682
    /**
683
     * @param array $clientOptions
684
     * @return Config
685
     */
686 13
    public function setClientOptions(array $clientOptions)
687
    {
688 13
        $this->clientOptions = $clientOptions;
689 13
        return $this;
690
    }
691
692
    /**
693
     * @return array
694
     */
695 68
    public function getOAuthClientOptions()
696
    {
697 68
        return $this->oauthClientOptions;
698
    }
699
700
    /**
701
     * @param array $clientOptions
702
     * @return Config
703
     */
704 13
    public function setOAuthClientOptions(array $clientOptions)
705
    {
706 13
        $this->oauthClientOptions = $clientOptions;
707 13
        return $this;
708
    }
709
710
    /**
711
     * @return string
712
     */
713 2
    public function getBearerToken()
714
    {
715 2
        return $this->bearerToken;
716
    }
717
718
    /**
719
     * @param string $bearerToken
720
     * @return Config
721
     */
722 2
    public function setBearerToken($bearerToken)
723
    {
724 2
        $this->bearerToken = $bearerToken;
725 2
        return $this;
726
    }
727
728 27
    public function getClientCredentials()
729
    {
730 27
        return new ClientCredentials([
731 27
            ClientCredentials::CLIENT_ID => $this->clientId,
732 27
            ClientCredentials::CLIENT_SECRET => $this->clientSecret,
733 27
            ClientCredentials::SCOPE => $this->getScope()
734
        ]);
735
    }
736
}
737