Passed
Push — develop ( 1bb7ea...fa0beb )
by Jens
10:39 queued 14s
created

Config   F

Complexity

Total Complexity 70

Size/Duplication

Total Lines 675
Duplicated Lines 0 %

Test Coverage

Coverage 91.71%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 70
eloc 173
c 1
b 0
f 1
dl 0
loc 675
ccs 166
cts 181
cp 0.9171
rs 2.8

52 Methods

Rating   Name   Duplication   Size   Complexity  
A fromArray() 0 15 2
A __construct() 0 3 1
A getClientId() 0 3 1
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 getOauthUrl() 0 14 5
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

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.sphere.io';
107
108
    /**
109
     * @var string
110
     */
111
    protected $apiUrl = 'https://api.sphere.io';
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 117
    public function __construct()
181
    {
182 117
        $this->enableCorrelationId = Uuid::active();
183 117
    }
184
185
    /**
186
     * @param array $configValues
187
     * @return static
188
     */
189 112
    public static function fromArray(array $configValues)
190
    {
191 112
        $config = static::of();
192 112
        array_walk(
193 112
            $configValues,
194
            function ($value, $key) use ($config) {
195 110
                $functionName = 'set' . $config->camelize($key);
196 110
                if (!is_callable([$config, $functionName])) {
197 1
                    throw new InvalidArgumentException(sprintf(Message::SETTER_NOT_IMPLEMENTED, $key));
198
                }
199 109
                $config->$functionName($value);
200 112
            }
201
        );
202
203 111
        return $config;
204
    }
205
206 110
    protected function camelize($scored)
207
    {
208 110
        return lcfirst(
209 110
            implode(
210 110
                '',
211 110
                array_map(
212 110
                    'ucfirst',
213 110
                    array_map(
214 110
                        'strtolower',
215 110
                        explode('_', $scored)
216
                    )
217
                )
218
            )
219
        );
220
    }
221
222
    /**
223
     * @return string
224
     */
225 87
    public function getClientSecret()
226
    {
227 87
        return $this->clientSecret;
228
    }
229
230
    /**
231
     * @param string $clientSecret
232
     * @return $this
233
     */
234 100
    public function setClientSecret($clientSecret)
235
    {
236 100
        $this->clientSecret = $clientSecret;
237
238 100
        return $this;
239
    }
240
241
    /**
242
     * @return string
243
     */
244 91
    public function getClientId()
245
    {
246 91
        return $this->clientId;
247
    }
248
249
    /**
250
     * @param string $clientId
251
     * @return $this
252
     */
253 100
    public function setClientId($clientId)
254
    {
255 100
        $this->clientId = $clientId;
256
257 100
        return $this;
258
    }
259
260
    /**
261
     * @return string
262
     */
263 781
    public function getProject()
264
    {
265 781
        return $this->project;
266
    }
267
268
    /**
269
     * @param string $project
270
     * @return $this
271
     */
272 109
    public function setProject($project)
273
    {
274 109
        $this->project = $project;
275
276 109
        return $this;
277
    }
278
279
    /**
280
     * @return string
281
     */
282 742
    public function getScope()
283
    {
284 742
        $scope = $this->scope;
285 742
        $project = $this->getProject();
286
287 742
        $permissions = [];
288 742
        foreach ($scope as $key => $value) {
289 738
            if (is_numeric($key)) { // scope defined as string e.g. scope:project_key
290 737
                if (strpos($value, ':') === false) { // scope without project key
291 736
                    $value = $value . ':' . $project;
292
                }
293 737
                $permissions[] = $value;
294
            } else { // scope defined as array
295 738
                $permissions[] = $key . ':' . $value;
296
            }
297
        }
298 742
        $scope = implode(' ', $permissions);
299
300 742
        return $scope;
301
    }
302
303
    /**
304
     * @param string $scope
305
     * @return $this
306
     */
307 70
    public function setScope($scope)
308
    {
309 70
        if (empty($scope)) {
310 4
            $scope = [];
311
        }
312 70
        if (!is_array($scope)) {
313 33
            $scope = explode(' ', $scope);
314
        }
315 70
        $this->scope = $scope;
316
317 70
        return $this;
318
    }
319
320
    /**
321
     * @param string|null $grantType
322
     * @return string
323
     */
324 64
    public function getOauthUrl($grantType = null)
325
    {
326 64
        if (is_null($grantType)) {
327 64
            $grantType = $this->getGrantType();
328
        }
329
330
        switch ($grantType) {
331 64
            case static::GRANT_TYPE_ANONYMOUS:
332 18
                return $this->oauthUrl . '/oauth/' . $this->getProject() . '/anonymous/token';
333 59
            case static::GRANT_TYPE_PASSWORD:
334 53
            case static::GRANT_TYPE_REFRESH:
335 34
                return $this->oauthUrl . '/oauth/' . $this->getProject() . '/customers/token';
336
            default:
337 53
                return $this->oauthUrl . '/oauth/token';
338
        }
339
    }
340
341
    /**
342
     * @param string $oauthUrl
343
     * @return $this
344
     */
345 99
    public function setOauthUrl($oauthUrl)
346
    {
347 99
        $this->oauthUrl = $oauthUrl;
348
349 99
        return $this;
350
    }
351
352
    /**
353
     * @return string
354
     */
355 86
    public function getApiUrl()
356
    {
357 86
        return $this->apiUrl;
358
    }
359
360
    /**
361
     * @param string $apiUrl
362
     * @return $this
363
     */
364 99
    public function setApiUrl($apiUrl)
365
    {
366 99
        $this->apiUrl = $apiUrl;
367
368 99
        return $this;
369
    }
370
371
    /**
372
     * @return bool
373
     */
374 79
    public function check()
375
    {
376 79
        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...
377 4
            throw new InvalidArgumentException(Message::NO_CLIENT_ID);
378
        }
379
380 75
        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...
381
            throw new InvalidArgumentException(Message::NO_CLIENT_SECRET);
382
        }
383
384 75
        if (is_null($this->getProject())) {
0 ignored issues
show
introduced by
The condition is_null($this->getProject()) is always false.
Loading history...
385
            throw new InvalidArgumentException(Message::NO_PROJECT_ID);
386
        }
387
388 75
        return true;
389
    }
390
391
    /**
392
     * @deprecated use getClientOptions()['concurrency'] instead
393
     * @return int
394
     */
395 1
    public function getBatchPoolSize()
396
    {
397 1
        if (!isset($this->clientOptions['concurrency'])) {
398 1
            return $this->batchPoolSize;
399
        }
400 1
        return $this->clientOptions['concurrency'];
401
    }
402
403
    /**
404
     * @deprecated use setClientOptions(['concurrency' => 5]) instead
405
     * @param int $batchPoolSize
406
     * @return $this
407
     */
408 1
    public function setBatchPoolSize($batchPoolSize)
409
    {
410 1
        $this->clientOptions['concurrency'] = $batchPoolSize;
411 1
        $this->batchPoolSize = $batchPoolSize;
412
413 1
        return $this;
414
    }
415
416
    /**
417
     * @return string
418
     */
419 70
    public function getAdapter()
420
    {
421 70
        return $this->adapter;
422
    }
423
424
    /**
425
     * @param string $adapter
426
     * @return $this
427
     */
428
    public function setAdapter($adapter)
429
    {
430
        $this->adapter = $adapter;
431
432
        return $this;
433
    }
434
435
    /**
436
     * @return bool
437
     */
438 121
    public function getThrowExceptions()
439
    {
440 121
        return $this->throwExceptions;
441
    }
442
443
    /**
444
     * @param bool $throwExceptions
445
     * @return $this
446
     */
447 11
    public function setThrowExceptions($throwExceptions)
448
    {
449 11
        $this->throwExceptions = (bool)$throwExceptions;
450
451 11
        return $this;
452
    }
453
454
    /**
455
     * @return string
456
     */
457 88
    public function getAcceptEncoding()
458
    {
459 88
        return $this->acceptEncoding;
460
    }
461
462
    /**
463
     * @param string $acceptEncoding
464
     * @return $this
465
     */
466
    public function setAcceptEncoding($acceptEncoding)
467
    {
468
        $this->acceptEncoding = $acceptEncoding;
469
470
        return $this;
471
    }
472
473
    /**
474
     * @return static
475
     */
476 113
    public static function of()
477
    {
478 113
        return new static();
479
    }
480
481
    /**
482
     * @return string
483
     */
484 739
    public function getGrantType()
485
    {
486 739
        return $this->grantType;
487
    }
488
489
    /**
490
     * @param string $grantType
491
     * @return $this
492
     */
493 34
    public function setGrantType($grantType)
494
    {
495 34
        $this->grantType = $grantType;
496
497 34
        return $this;
498
    }
499
500
    /**
501
     * @return string
502
     */
503 20
    public function getUsername()
504
    {
505 20
        return $this->username;
506
    }
507
508
    /**
509
     * @param string $username
510
     * @return $this
511
     */
512 25
    public function setUsername($username)
513
    {
514 25
        $this->username = $username;
515
516 25
        return $this;
517
    }
518
519
    /**
520
     * @return string
521
     */
522 20
    public function getPassword()
523
    {
524 20
        return $this->password;
525
    }
526
527
    /**
528
     * @param string $password
529
     * @return $this
530
     */
531 25
    public function setPassword($password)
532
    {
533 25
        $this->password = $password;
534
535 25
        return $this;
536
    }
537
538
    /**
539
     * @return string
540
     */
541 27
    public function getRefreshToken()
542
    {
543 27
        return $this->refreshToken;
544
    }
545
546
    /**
547
     * @param string $refreshToken
548
     * @return $this
549
     */
550 27
    public function setRefreshToken($refreshToken)
551
    {
552 27
        $this->refreshToken = $refreshToken;
553
554 27
        return $this;
555
    }
556
557
    /**
558
     * @return string
559
     */
560 9
    public function getAnonymousId()
561
    {
562 9
        return $this->anonymousId;
563
    }
564
565
    /**
566
     * @param string $anonymousId
567
     * @return $this
568
     */
569 3
    public function setAnonymousId($anonymousId)
570
    {
571 3
        $this->anonymousId = $anonymousId;
572
573 3
        return $this;
574
    }
575
576
    /**
577
     * @return string
578
     */
579 89
    public function getCacheDir()
580
    {
581 89
        return $this->cacheDir;
582
    }
583
584
    /**
585
     * @param string $cacheDir
586
     * @return $this
587
     */
588
    public function setCacheDir($cacheDir)
589
    {
590
        $this->cacheDir = $cacheDir;
591
592
        return $this;
593
    }
594
595
    /**
596
     * @return string
597
     */
598 41
    public function getLogLevel()
599
    {
600 41
        return $this->logLevel;
601
    }
602
603
    /**
604
     * @param string $logLevel
605
     * @return $this
606
     */
607 1
    public function setLogLevel($logLevel)
608
    {
609 1
        $this->logLevel = $logLevel;
610
611 1
        return $this;
612
    }
613
614
    /**
615
     * @return mixed
616
     */
617 41
    public function getMessageFormatter()
618
    {
619 41
        return $this->messageFormatter;
620
    }
621
622
    /**
623
     * @param mixed $messageFormatter
624
     * @return $this
625
     */
626
    public function setMessageFormatter($messageFormatter)
627
    {
628
        $this->messageFormatter = $messageFormatter;
629
        return $this;
630
    }
631
632
    /**
633
     * @return CorrelationIdProvider|null
634
     */
635 87
    public function getCorrelationIdProvider()
636
    {
637 87
        if (!$this->isEnableCorrelationId()) {
638
            return null;
639
        }
640 87
        if (is_null($this->correlationIdProvider)) {
641 85
            $this->correlationIdProvider = DefaultCorrelationIdProvider::of($this->getProject());
642
        }
643 87
        return $this->correlationIdProvider;
644
    }
645
646
    /**
647
     * @param CorrelationIdProvider $correlationIdProvider
648
     * @return Config
649
     */
650 2
    public function setCorrelationIdProvider(CorrelationIdProvider $correlationIdProvider)
651
    {
652 2
        $this->correlationIdProvider = $correlationIdProvider;
653 2
        $this->setEnableCorrelationId(true);
654 2
        return $this;
655
    }
656
657
    /**
658
     * @return bool
659
     */
660 87
    public function isEnableCorrelationId()
661
    {
662 87
        return $this->enableCorrelationId;
663
    }
664
665
    /**
666
     * @param bool $enableCorrelationId
667
     * @return Config
668
     */
669 59
    public function setEnableCorrelationId($enableCorrelationId)
670
    {
671 59
        $this->enableCorrelationId = (bool)$enableCorrelationId;
672 59
        return $this;
673
    }
674
675
    /**
676
     * @return array
677
     */
678 80
    public function getClientOptions()
679
    {
680 80
        return $this->clientOptions;
681
    }
682
683
    /**
684
     * @param array $clientOptions
685
     * @return Config
686
     */
687 11
    public function setClientOptions(array $clientOptions)
688
    {
689 11
        $this->clientOptions = $clientOptions;
690 11
        return $this;
691
    }
692
693
    /**
694
     * @return array
695
     */
696 59
    public function getOAuthClientOptions()
697
    {
698 59
        return $this->oauthClientOptions;
699
    }
700
701
    /**
702
     * @param array $clientOptions
703
     * @return Config
704
     */
705 10
    public function setOAuthClientOptions(array $clientOptions)
706
    {
707 10
        $this->oauthClientOptions = $clientOptions;
708 10
        return $this;
709
    }
710
711
    /**
712
     * @return string
713
     */
714 1
    public function getBearerToken()
715
    {
716 1
        return $this->bearerToken;
717
    }
718
719
    /**
720
     * @param string $bearerToken
721
     * @return Config
722
     */
723 1
    public function setBearerToken($bearerToken)
724
    {
725 1
        $this->bearerToken = $bearerToken;
726 1
        return $this;
727
    }
728
729 19
    public function getClientCredentials()
730
    {
731 19
        return new ClientCredentials([
732 19
            ClientCredentials::CLIENT_ID => $this->clientId,
733 19
            ClientCredentials::CLIENT_SECRET => $this->clientSecret,
734 19
            ClientCredentials::SCOPE => $this->getScope()
735
        ]);
736
    }
737
}
738