Passed
Push — master ( 751f0f...c8e8f6 )
by Pieter
01:39
created

ValidationException::__construct()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 6
eloc 7
c 3
b 0
f 1
nc 6
nop 2
dl 0
loc 11
rs 9.2222
1
<?php
2
3
namespace W2w\Lib\ApieObjectAccessNormalizer\Exceptions;
4
5
use Throwable;
6
use W2w\Lib\ApieObjectAccessNormalizer\Errors\ErrorBag;
7
use W2w\Lib\ApieObjectAccessNormalizer\Normalizers\ApieObjectAccessNormalizer;
8
9
/**
10
 * Exception thrown if the constructor could not be called or if a setter threw an error.
11
 *
12
 * @see ApieObjectAccessNormalizer::denormalize()
13
 */
14
class ValidationException extends ApieException implements LocalizationableException, ErrorBagAwareException
15
{
16
    /**
17
     * @var ErrorBag
18
     */
19
    private $errors;
20
    /**
21
     * @var Throwable[][]|null
22
     */
23
    private $exceptions;
24
25
    /**
26
     * @param string[][]|ErrorBag $errors
27
     * @param Throwable|null $previous
28
     */
29
    public function __construct($errors, Throwable $previous = null)
30
    {
31
        $this->errors = $errors instanceof ErrorBag ? $errors : ErrorBag::fromArray((array) $errors);
32
        if (!$previous && $this->errors->hasErrors()) {
33
            $this->exceptions = $this->errors->getExceptions();
34
            $tmp = reset($this->exceptions);
35
            if ($tmp) {
36
                $previous = reset($tmp) ? : null;
37
            }
38
        }
39
        parent::__construct(422, 'A validation error occurred', $previous);
40
    }
41
42
    /**
43
     * Returns the validation errors.
44
     *
45
     * @return string[][]
46
     */
47
    public function getErrors(): array
48
    {
49
        return $this->errors->getErrors();
50
    }
51
52
    /**
53
     * @deprecated use getErrorBag instead.
54
     *
55
     * @return Throwable[][]
56
     */
57
    public function getExceptions(): ?array
58
    {
59
        return $this->exceptions;
60
    }
61
62
    public function getI18n(): LocalizationInfo
63
    {
64
        return new LocalizationInfo('general.validation', ['errors' => $this->getErrors()]);
65
    }
66
67
    public function getErrorBag(): ErrorBag
68
    {
69
        return $this->errors;
70
    }
71
}
72