Completed
Push — develop ( fbac2a...fa8907 )
by Edwin
04:58
created

ShopifyException   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 0
dl 0
loc 69
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A getErrors() 0 4 1
A __toString() 0 4 1
A buildErrorString() 0 12 3
A buildErrorLine() 0 4 2
1
<?php
2
3
namespace ShopifyClient\Exception;
4
5
use Throwable;
6
7
class ShopifyException 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 3
    public function __construct($errors, $code = 0, Throwable $previous = null)
21
    {
22 3
        if (!is_array($errors)) {
23 1
            $errors = [$errors];
24
        }
25
26 3
        $this->errors = $errors;
27
28 3
        parent::__construct($this->__toString(), $code, $previous);
29 3
    }
30
31
    /**
32
     * @return array
33
     */
34 2
    public function getErrors()
35
    {
36 2
        return $this->errors;
37
    }
38
39
    /**
40
     * @return string
41
     */
42 3
    public function __toString()
43
    {
44 3
        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 3
    private function buildErrorString($errors, $errorString = '', string $field = null): string
54
    {
55 3
        foreach ($errors as $key => $value) {
56 3
            if (is_array($value)) {
57 1
                $errorString .= $this->buildErrorString($value, $errorString, $key);
58
            } else {
59 3
                $errorString .= $this->buildErrorLine($field, $value);
60
            }
61
        }
62
63 3
        return $errorString;
64
    }
65
66
    /**
67
     * @param $key
68
     * @param string $value
69
     * @return string
70
     */
71 3
    private function buildErrorLine($key, string $value = null): string
72
    {
73 3
        return sprintf('%s%s.', !empty($key) ? $key . ': ' : $key, $value) . PHP_EOL;
74
    }
75
}
76