Completed
Push — develop ( 02e6e4...770dc9 )
by Edwin
14:52
created

ClientException::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace ShopifyClient\Exception;
4
5
use Throwable;
6
7
class ClientException extends \Exception
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $errors;
13
14
    /**
15
     * ClientException constructor.
16
     * @param string|array $errors
17
     * @param int $code
18
     * @param Throwable|null $previous
19
     */
20
    public function __construct($errors, $code = 0, Throwable $previous = null)
21
    {
22
        if (!is_array($errors)) {
23
            $errors = [$errors];
24
        }
25
26
        $this->errors = $errors;
27
28
        parent::__construct('Shopify exception: ' . $this->__toString(), $code, $previous);
29
    }
30
31
    /**
32
     * @return array
33
     */
34
    public function getErrors()
35
    {
36
        return $this->errors;
37
    }
38
39
    /**
40
     * @return string
41
     */
42
    public function __toString()
43
    {
44
        return $this->buildErrorString($this->errors);
45
    }
46
47
    /**
48
     * @param $errors
49
     * @param string $errorString
50
     * @param null|string $field
51
     * @return string
52
     */
53
    private function buildErrorString($errors, $errorString = '', string $field = null): string
54
    {
55
        foreach ($errors as $key => $value) {
56
            if (is_array($value)) {
57
                $errorString .= $this->buildErrorString($value, $errorString, $key);
58
            } else {
59
                $errorString .= $this->buildErrorLine($field, $value);
60
            }
61
        }
62
63
        return $errorString;
64
    }
65
66
    /**
67
     * @param $key
68
     * @param string $value
69
     * @return string
70
     */
71
    private function buildErrorLine($key, string $value): string
72
    {
73
        return sprintf('%s%s.', !empty($key) ? $key . ': ' : $key, $value) . PHP_EOL;
74
    }
75
}
76