Passed
Push — master ( 4f5e8c...aa84a3 )
by
unknown
11:37 queued 05:17
created

ApiKeysTestCreator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * You can find more information about us on https://bitbag.io and write us
7
 * an email on [email protected].
8
 */
9
10
declare(strict_types=1);
11
12
namespace BitBag\SyliusMolliePlugin\Creator;
13
14
use BitBag\SyliusMolliePlugin\Client\MollieApiClient;
15
use BitBag\SyliusMolliePlugin\DTO\ApiKeyTest;
16
use Symfony\Contracts\Translation\TranslatorInterface;
17
18
final class ApiKeysTestCreator implements ApiKeysTestCreatorInterface
19
{
20
    /** @var MollieApiClient */
21
    private $mollieApiClient;
22
23
    /** @var TranslatorInterface */
24
    private $translator;
25
26
    public function __construct(
27
        MollieApiClient $mollieApiClient,
28
        TranslatorInterface $translator
29
    ) {
30
        $this->mollieApiClient = $mollieApiClient;
31
        $this->translator = $translator;
32
    }
33
34
    public function create(string $keyType, string $key = null): ApiKeyTest
35
    {
36
        $apiKeyTest = new ApiKeyTest(
37
            $keyType,
38
            $key ? true : false,
39
        );
40
41
        if (null === $key || empty(trim($key))) {
42
            $apiKeyTest->setStatus(self::ERROR_STATUS);
43
            $apiKeyTest->setMessage($this->translator->trans('bitbag_sylius_mollie_plugin.ui.inser_you_key_first'));
44
45
            return $apiKeyTest;
46
        }
47
48
        return $this->testApiKey($apiKeyTest, $key);
49
    }
50
51
    private function testApiKey(ApiKeyTest $apiKeyTest, string $apiKey): ApiKeyTest
52
    {
53
        try {
54
            $client = $this->mollieApiClient->setApiKey($apiKey);
55
56
            $methods = $client->methods->allActive(MollieMethodsCreatorInterface::PARAMETERS);
57
            $apiKeyTest->setMethods($methods);
58
59
            return $apiKeyTest;
60
        } catch (\Exception $exception) {
61
            $apiKeyTest->setStatus(self::ERROR_STATUS);
62
63
            if ($exception->getCode() === 0) {
64
                $apiKeyTest->setMessage($this->translator->trans(
65
                    \sprintf('bitbag_sylius_mollie_plugin.ui.api_key_start_with_%s', $apiKeyTest->getType())
66
                ));
67
68
                return $apiKeyTest;
69
            }
70
71
            $apiKeyTest->setMessage($this->translator->trans('bitbag_sylius_mollie_plugin.ui.failed_with_test_api_key'));
72
73
            return $apiKeyTest;
74
        }
75
    }
76
}
77