Passed
Push — trunk ( cca91d...e2f74b )
by Christian
13:28 queued 13s
created

TaxProviderExceptions::updateMessage()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 13
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 22
rs 9.8333
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Checkout\Cart\Exception;
4
5
use Shopware\Core\Framework\ShopwareHttpException;
6
7
/**
8
 * @package checkout
9
 */
10
class TaxProviderExceptions extends ShopwareHttpException
11
{
12
    public const ERROR_CODE = 'CHECKOUT__TAX_PROVIDER_EXCEPTION';
13
14
    private const DEFAULT_TEMPLATE = 'There was an error while calculating taxes';
15
    private const MESSAGE_TEMPLATE = 'There were %d errors while fetching taxes from providers: ' . \PHP_EOL . '%s';
16
17
    /**
18
     * @var array<string, \Throwable[]>
19
     */
20
    private array $exceptions = [];
21
22
    public function __construct()
23
    {
24
        parent::__construct(self::DEFAULT_TEMPLATE);
25
    }
26
27
    public function add(string $taxProviderIdentifier, \Throwable $e): void
28
    {
29
        if (!\array_key_exists($taxProviderIdentifier, $this->exceptions)) {
30
            $this->exceptions[$taxProviderIdentifier] = [];
31
        }
32
33
        $this->exceptions[$taxProviderIdentifier][] = $e;
34
        $this->updateMessage();
35
    }
36
37
    /**
38
     * @return \Throwable[]
39
     */
40
    public function getErrorsForTaxProvider(string $taxProvider): array
41
    {
42
        if (!\array_key_exists($taxProvider, $this->exceptions)) {
43
            return [];
44
        }
45
46
        return $this->exceptions[$taxProvider];
47
    }
48
49
    public function hasExceptions(): bool
50
    {
51
        return !empty($this->exceptions);
52
    }
53
54
    public function getErrorCode(): string
55
    {
56
        return self::ERROR_CODE;
57
    }
58
59
    private function updateMessage(): void
60
    {
61
        $message = '';
62
63
        if (!$this->hasExceptions()) {
64
            return;
65
        }
66
67
        foreach ($this->exceptions as $provider => $exceptions) {
68
            foreach ($exceptions as $exception) {
69
                $message .= \sprintf(
70
                    'Tax provider \'%s\' threw an exception: %s' . \PHP_EOL,
71
                    $provider,
72
                    $exception->getMessage()
73
                );
74
            }
75
        }
76
77
        $this->message = \sprintf(
78
            self::MESSAGE_TEMPLATE,
79
            \count($this->exceptions),
80
            $message
81
        );
82
    }
83
}
84