Passed
Push — develop ( 51a503...b811fe )
by Jens
08:31 queued 22s
created

Config::setBearerToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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