Completed
Push — develop ( 67ce5a...d93a45 )
by
unknown
16:41
created

Config::camelize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @author @jayS-de <[email protected]>
4
 * @created: 20.01.15, 17:54
5
 */
6
7
namespace Commercetools\Core;
8
9
use Commercetools\Core\Error\Message;
10
use Commercetools\Core\Error\InvalidArgumentException;
11
use Commercetools\Core\Helper\CorrelationIdProvider;
12
use Commercetools\Core\Helper\DefaultCorrelationIdProvider;
13
use Commercetools\Core\Helper\Uuid;
14
use Commercetools\Core\Model\Common\ContextAwareInterface;
15
use Commercetools\Core\Model\Common\ContextTrait;
16
use Psr\Log\LogLevel;
17
18
/**
19
 * Client configuration object
20
 *
21
 * @description
22
 *
23
 * Often configuration like credentials is stored in YAML or INI files. To setup the configuration object
24
 * this can be done by the fromArray method.
25
 *
26
 * Configuration file:
27
 *
28
 * ```
29
 * [commercetools]
30
 * client_id = '<client-id>'
31
 * client_secret = '<client-secret>'
32
 * project = '<project>'
33
 * ```
34
 *
35
 * Config instantiation:
36
 *
37
 * ```php
38
 * $iniConfig = parse_ini_file('<config-file>.ini', true);
39
 * $config = Config::fromArray($iniConfig['commercetools']);
40
 * ```
41
 *
42
 * ### Exceptions ###
43
 *
44
 * The client by default suppresses exceptions when a response had been returned by the API and the result
45
 * can be handled afterwards by checking the isError method of the response. For interacting with Exceptions
46
 * they can be enabled with the throwExceptions flag.
47
 *
48
 * ```php
49
 * $config->setThrowExceptions(true);
50
 * $client = new Client($config);
51
 * try {
52
 *     $response = $client->execute($request);
53
 * } catch (\Commercetools\Core\Error\ApiException $e) {
54
 *     // handle Exception
55
 * }
56
 * ```
57
 * @package Commercetools\Core
58
 */
59
class Config implements ContextAwareInterface
60
{
61
    use ContextTrait;
62
63
    const OAUTH_URL = 'oauth_url';
64
    const CLIENT_ID = 'client_id';
65
    const CLIENT_SECRET = 'client_secret';
66
    const SCOPE = 'scope';
67
    const PROJECT = 'project';
68
    const API_URL = 'api_url';
69
    const USER_NAME = 'username';
70
    const PASSWORD = 'password';
71
    const REFRESH_TOKEN = 'refresh_token';
72
    const BEARER_TOKEN = 'bearer_token';
73
    const ANONYMOUS_ID = 'anonymous_id';
74
    const GRANT_TYPE = 'grant_type';
75
76
    const GRANT_TYPE_CLIENT = 'client_credentials';
77
    const GRANT_TYPE_PASSWORD = 'password';
78
    const GRANT_TYPE_REFRESH = 'refresh_token';
79
    const GRANT_TYPE_ANONYMOUS = 'anonymous_token';
80
    const GRANT_TYPE_BEARER_TOKEN = 'bearer_token';
81
82
    /**
83
     * @var string
84
     */
85
    protected $clientSecret;
86
87
    /**
88
     * @var string
89
     */
90
    protected $clientId;
91
92
    /**
93
     * @var string
94
     */
95
    protected $project;
96
97
    /**
98
     * @var array
99
     */
100
    protected $scope = ['manage_project'];
101
102
    /**
103
     * @var string
104
     */
105
    protected $oauthUrl = 'https://auth.sphere.io';
106
107
    /**
108
     * @var string
109
     */
110
    protected $apiUrl = 'https://api.sphere.io';
111
112
    /**
113
     * @var int
114
     */
115
    protected $batchPoolSize = 25;
116
117
    protected $adapter;
118
119
    /**
120
     * @var bool
121
     */
122
    protected $throwExceptions = false;
123
124
    protected $acceptEncoding = 'gzip';
125
126
    protected $grantType = 'client_credentials';
127
128
    /**
129
     * @var string
130
     */
131
    protected $username;
132
133
    /**
134
     * @var string
135
     */
136
    protected $password;
137
138
    /**
139
     * @var string
140
     */
141
    protected $refreshToken;
142
143
    /**
144
     * @var string
145
     */
146
    protected $bearerToken;
147
148
    /**
149
     * @var string
150
     */
151
    protected $anonymousId;
152
153
    /**
154
     * @var string
155
     */
156
    protected $cacheDir;
157
158
    /**
159
     * @var string
160
     */
161
    protected $logLevel = LogLevel::INFO;
162
163
    protected $messageFormatter;
164
165
    /**
166
     * @var bool
167
     */
168
    protected $enableCorrelationId = false;
169
170
    /**
171
     * @var CorrelationIdProvider
172
     */
173
    protected $correlationIdProvider;
174
175
    protected $clientOptions = [];
176
177 106
    public function __construct()
178
    {
179 106
        $this->enableCorrelationId = Uuid::active();
180 106
    }
181
182
    /**
183
     * @param array $configValues
184
     * @return static
185
     */
186 103
    public static function fromArray(array $configValues)
187
    {
188 103
        $config = static::of();
189 103
        array_walk(
190 103
            $configValues,
191 103
            function ($value, $key) use ($config) {
192 101
                $functionName = 'set' . $config->camelize($key);
193 101
                if (!is_callable([$config, $functionName])) {
194 1
                    throw new InvalidArgumentException(sprintf(Message::SETTER_NOT_IMPLEMENTED, $key));
195
                }
196 100
                $config->$functionName($value);
197 103
            }
198
        );
199
200 102
        return $config;
201
    }
202
203 101
    protected function camelize($scored)
204
    {
205 101
        return lcfirst(
206 101
            implode(
207 101
                '',
208 101
                array_map(
209 101
                    'ucfirst',
210 101
                    array_map(
211 101
                        'strtolower',
212 101
                        explode('_', $scored)
213
                    )
214
                )
215
            )
216
        );
217
    }
218
219
    /**
220
     * @return string
221
     */
222 86
    public function getClientSecret()
223
    {
224 86
        return $this->clientSecret;
225
    }
226
227
    /**
228
     * @param string $clientSecret
229
     * @return $this
230
     */
231 89
    public function setClientSecret($clientSecret)
232
    {
233 89
        $this->clientSecret = $clientSecret;
234
235 89
        return $this;
236
    }
237
238
    /**
239
     * @return string
240
     */
241 90
    public function getClientId()
242
    {
243 90
        return $this->clientId;
244
    }
245
246
    /**
247
     * @param string $clientId
248
     * @return $this
249
     */
250 89
    public function setClientId($clientId)
251
    {
252 89
        $this->clientId = $clientId;
253
254 89
        return $this;
255
    }
256
257
    /**
258
     * @return string
259
     */
260 568
    public function getProject()
261
    {
262 568
        return $this->project;
263
    }
264
265
    /**
266
     * @param string $project
267
     * @return $this
268
     */
269 99
    public function setProject($project)
270
    {
271 99
        $this->project = $project;
272
273 99
        return $this;
274
    }
275
276
    /**
277
     * @return string
278
     */
279 529
    public function getScope()
280
    {
281 529
        $scope = $this->scope;
282 529
        $project = $this->getProject();
283
284 529
        $permissions = [];
285 529
        foreach ($scope as $key => $value) {
286 524
            if (is_numeric($key)) { // scope defined as string e.g. scope:project_key
287 523
                if (strpos($value, ':') === false) { // scope without project key
288 522
                    $value = $value . ':' . $project;
289
                }
290 523
                $permissions[] = $value;
291
            } else { // scope defined as array
292 524
                $permissions[] = $key . ':' . $value;
293
            }
294
        }
295 529
        $scope = implode(' ', $permissions);
296
297 529
        return $scope;
298
    }
299
300
    /**
301
     * @param string $scope
302
     * @return $this
303
     */
304 54
    public function setScope($scope)
305
    {
306 54
        if (empty($scope)) {
307 5
            $scope = [];
308
        }
309 54
        if (!is_array($scope)) {
310 24
            $scope = explode(' ', $scope);
311
        }
312 54
        $this->scope = $scope;
313
314 54
        return $this;
315
    }
316
317
    /**
318
     * @return string
319
     */
320 52
    public function getOauthUrl()
321
    {
322 52
        switch ($this->getGrantType()) {
323 52
            case static::GRANT_TYPE_ANONYMOUS:
324 11
                return $this->oauthUrl . '/oauth/' . $this->getProject() . '/anonymous/token';
325 47
            case static::GRANT_TYPE_PASSWORD:
326 42
            case static::GRANT_TYPE_REFRESH:
327 23
                return $this->oauthUrl . '/oauth/' . $this->getProject() . '/customers/token';
328
            default:
329 42
                return $this->oauthUrl . '/oauth/token';
330
        }
331
    }
332
333
    /**
334
     * @param string $oauthUrl
335
     * @return $this
336
     */
337 89
    public function setOauthUrl($oauthUrl)
338
    {
339 89
        $this->oauthUrl = $oauthUrl;
340
341 89
        return $this;
342
    }
343
344
    /**
345
     * @return string
346
     */
347 64
    public function getApiUrl()
348
    {
349 64
        return $this->apiUrl;
350
    }
351
352
    /**
353
     * @param string $apiUrl
354
     * @return $this
355
     */
356 89
    public function setApiUrl($apiUrl)
357
    {
358 89
        $this->apiUrl = $apiUrl;
359
360 89
        return $this;
361
    }
362
363
    /**
364
     * @return bool
365
     */
366 87
    public function check()
367
    {
368 87 View Code Duplication
        if (is_null($this->getClientId()) && $this->getGrantType() !== self::GRANT_TYPE_BEARER_TOKEN) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
369 4
            throw new InvalidArgumentException(Message::NO_CLIENT_ID);
370
        }
371
372 83 View Code Duplication
        if (is_null($this->getClientSecret()) && $this->getGrantType() !== self::GRANT_TYPE_BEARER_TOKEN) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
373
            throw new InvalidArgumentException(Message::NO_CLIENT_SECRET);
374
        }
375
376 83
        if (is_null($this->getProject())) {
377
            throw new InvalidArgumentException(Message::NO_PROJECT_ID);
378
        }
379
380 83
        return true;
381
    }
382
383
    /**
384
     * @deprecated use getClientOptions()['concurrency'] instead
385
     * @return int
386
     */
387 1
    public function getBatchPoolSize()
388
    {
389 1
        if (!isset($this->clientOptions['concurrency'])) {
390 1
            return $this->batchPoolSize;
391
        }
392 1
        return $this->clientOptions['concurrency'];
393
    }
394
395
    /**
396
     * @deprecated use setClientOptions(['concurrency' => 5]) instead
397
     * @param int $batchPoolSize
398
     * @return $this
399
     */
400 1
    public function setBatchPoolSize($batchPoolSize)
401
    {
402 1
        $this->clientOptions['concurrency'] = $batchPoolSize;
403 1
        $this->batchPoolSize = $batchPoolSize;
404
405 1
        return $this;
406
    }
407
408
    /**
409
     * @return string
410
     */
411 75
    public function getAdapter()
412
    {
413 75
        return $this->adapter;
414
    }
415
416
    /**
417
     * @param string $adapter
418
     * @return $this
419
     */
420
    public function setAdapter($adapter)
421
    {
422
        $this->adapter = $adapter;
423
424
        return $this;
425
    }
426
427
    /**
428
     * @return bool
429
     */
430 87
    public function getThrowExceptions()
431
    {
432 87
        return $this->throwExceptions;
433
    }
434
435
    /**
436
     * @param bool $throwExceptions
437
     * @return $this
438
     */
439 9
    public function setThrowExceptions($throwExceptions)
440
    {
441 9
        $this->throwExceptions = (bool)$throwExceptions;
442
443 9
        return $this;
444
    }
445
446
    /**
447
     * @return string
448
     */
449 74
    public function getAcceptEncoding()
450
    {
451 74
        return $this->acceptEncoding;
452
    }
453
454
    /**
455
     * @param string $acceptEncoding
456
     * @return $this
457
     */
458
    public function setAcceptEncoding($acceptEncoding)
459
    {
460
        $this->acceptEncoding = $acceptEncoding;
461
462
        return $this;
463
    }
464
465
    /**
466
     * @return static
467
     */
468 103
    public static function of()
469
    {
470 103
        return new static();
471
    }
472
473
    /**
474
     * @return string
475
     */
476 527
    public function getGrantType()
477
    {
478 527
        return $this->grantType;
479
    }
480
481
    /**
482
     * @param string $grantType
483
     * @return $this
484
     */
485 35
    public function setGrantType($grantType)
486
    {
487 35
        $this->grantType = $grantType;
488
489 35
        return $this;
490
    }
491
492
    /**
493
     * @return string
494
     */
495 19
    public function getUsername()
496
    {
497 19
        return $this->username;
498
    }
499
500
    /**
501
     * @param string $username
502
     * @return $this
503
     */
504 23
    public function setUsername($username)
505
    {
506 23
        $this->username = $username;
507
508 23
        return $this;
509
    }
510
511
    /**
512
     * @return string
513
     */
514 19
    public function getPassword()
515
    {
516 19
        return $this->password;
517
    }
518
519
    /**
520
     * @param string $password
521
     * @return $this
522
     */
523 23
    public function setPassword($password)
524
    {
525 23
        $this->password = $password;
526
527 23
        return $this;
528
    }
529
530
    /**
531
     * @return string
532
     */
533 28
    public function getRefreshToken()
534
    {
535 28
        return $this->refreshToken;
536
    }
537
538
    /**
539
     * @param string $refreshToken
540
     * @return $this
541
     */
542 28
    public function setRefreshToken($refreshToken)
543
    {
544 28
        $this->refreshToken = $refreshToken;
545
546 28
        return $this;
547
    }
548
549
    /**
550
     * @return string
551
     */
552 11
    public function getAnonymousId()
553
    {
554 11
        return $this->anonymousId;
555
    }
556
557
    /**
558
     * @param string $anonymousId
559
     * @return string
560
     */
561 4
    public function setAnonymousId($anonymousId)
562
    {
563 4
        $this->anonymousId = $anonymousId;
564
565 4
        return $this;
566
    }
567
568
    /**
569
     * @return string
570
     */
571 78
    public function getCacheDir()
572
    {
573 78
        return $this->cacheDir;
574
    }
575
576
    /**
577
     * @param string $cacheDir
578
     * @return $this
579
     */
580
    public function setCacheDir($cacheDir)
581
    {
582
        $this->cacheDir = $cacheDir;
583
584
        return $this;
585
    }
586
587
    /**
588
     * @return string
589
     */
590 40
    public function getLogLevel()
591
    {
592 40
        return $this->logLevel;
593
    }
594
595
    /**
596
     * @param string $logLevel
597
     * @return $this
598
     */
599 1
    public function setLogLevel($logLevel)
600
    {
601 1
        $this->logLevel = $logLevel;
602
603 1
        return $this;
604
    }
605
606
    /**
607
     * @return mixed
608
     */
609 40
    public function getMessageFormatter()
610
    {
611 40
        return $this->messageFormatter;
612
    }
613
614
    /**
615
     * @param mixed $messageFormatter
616
     * @return $this
617
     */
618
    public function setMessageFormatter($messageFormatter)
619
    {
620
        $this->messageFormatter = $messageFormatter;
621
        return $this;
622
    }
623
624
    /**
625
     * @return CorrelationIdProvider|null
626
     */
627 73
    public function getCorrelationIdProvider()
628
    {
629 73
        if (!$this->isEnableCorrelationId()) {
630
            return null;
631
        }
632 73
        if (is_null($this->correlationIdProvider)) {
633 71
            $this->correlationIdProvider = DefaultCorrelationIdProvider::of($this->getProject());
634
        }
635 73
        return $this->correlationIdProvider;
636
    }
637
638
    /**
639
     * @param CorrelationIdProvider $correlationIdProvider
640
     * @return Config
641
     */
642 2
    public function setCorrelationIdProvider(CorrelationIdProvider $correlationIdProvider)
643
    {
644 2
        $this->correlationIdProvider = $correlationIdProvider;
645 2
        $this->setEnableCorrelationId(true);
646 2
        return $this;
647
    }
648
649
    /**
650
     * @return bool
651
     */
652 73
    public function isEnableCorrelationId()
653
    {
654 73
        return $this->enableCorrelationId;
655
    }
656
657
    /**
658
     * @param bool $enableCorrelationId
659
     * @return Config
660
     */
661 40
    public function setEnableCorrelationId($enableCorrelationId)
662
    {
663 40
        $this->enableCorrelationId = (bool)$enableCorrelationId;
664 40
        return $this;
665
    }
666
667
    /**
668
     * @return array
669
     */
670 58
    public function getClientOptions()
671
    {
672 58
        return $this->clientOptions;
673
    }
674
675
    /**
676
     * @param array $clientOptions
677
     * @return Config
678
     */
679
    public function setClientOptions(array $clientOptions)
680
    {
681
        $this->clientOptions = $clientOptions;
682
        return $this;
683
    }
684
685
    /**
686
     * @return string
687
     */
688 2
    public function getBearerToken()
689
    {
690 2
        return $this->bearerToken;
691
    }
692
693
    /**
694
     * @param string $bearerToken
695
     * @return Config
696
     */
697 2
    public function setBearerToken($bearerToken)
698
    {
699 2
        $this->bearerToken = $bearerToken;
700 2
        return $this;
701
    }
702
}
703