Completed
Push — master ( 686b71...786636 )
by Alexandr
03:06
created

ErrorContainerTrait::mergeErrors()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 5
nc 2
nop 1
crap 3
1
<?php
2
/**
3
 * Date: 01.12.15
4
 *
5
 * @author Portey Vasil <[email protected]>
6
 */
7
8
namespace Youshido\GraphQL\Validator\ErrorContainer;
9
10
11
use Youshido\GraphQL\Exception\Interfaces\DatableExceptionInterface;
12
use Youshido\GraphQL\Exception\Interfaces\LocationableExceptionInterface;
13
14
trait ErrorContainerTrait
15
{
16
17
    /** @var \Exception[] */
18
    protected $errors = [];
19
20 41
    public function addError(\Exception $exception)
21
    {
22 41
        $this->errors[] = $exception;
23
24 41
        return $this;
25
    }
26
27 87
    public function hasErrors()
28
    {
29 87
        return !empty($this->errors);
30
    }
31
32 1
    public function getErrors()
33
    {
34 1
        return $this->errors;
35
    }
36
37 1
    public function mergeErrors(ErrorContainerInterface $errorContainer)
38
    {
39 1
        if ($errorContainer->hasErrors()) {
40 1
            foreach ($errorContainer->getErrors() as $error) {
41 1
                $this->addError($error);
42
            }
43
        }
44
45 1
        return $this;
46
    }
47
48 41
    public function getErrorsArray($inGraphQLStyle = true)
49
    {
50 41
        $errors = [];
51
52 41
        foreach ($this->errors as $error) {
53 41
            if ($inGraphQLStyle) {
54 20
                if ($error instanceof DatableExceptionInterface) {
55 1
                    $errors[] = array_merge(
56 1
                        ['message' => $error->getMessage()],
57 1
                        $error->getData() ?: [],
58 1
                        $error->getCode() ? ['code' => $error->getCode()] : []
59
                    );
60
                } elseif ($error instanceof LocationableExceptionInterface) {
61 17
                    $errors[] = array_merge(
62 17
                        ['message' => $error->getMessage()],
63 17
                        $error->getLocation() ? ['locations' => [$error->getLocation()->toArray()]] : [],
64 17
                        $error->getCode() ? ['code' => $error->getCode()] : []
65
                    );
66
                } else {
67 4
                    $errors[] = array_merge(
68 4
                        ['message' => $error->getMessage()],
69 20
                        $error->getCode() ? ['code' => $error->getCode()] : []
70
                    );
71
                }
72
            } else {
73 41
                $errors[] = $error->getMessage();
74
            }
75
        }
76
77 41
        return $errors;
78
    }
79
80 112
    public function clearErrors()
81
    {
82 112
        $this->errors = [];
83
84 112
        return $this;
85
    }
86
87
}