Completed
Push — master ( 0a3381...51a727 )
by Todd
01:47
created

ValidationException::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2017 Vanilla Forums Inc.
5
 * @license GPLv2
6
 */
7
8
namespace Garden\Schema;
9
10
/**
11
 * An exception that was built from a {@link Validation} object.
12
 *
13
 * The validation object collects errors and is mutable. Once it's ready to be thrown as an exception it gets converted
14
 * to an instance of the immutable {@link ValidationException} class.
15
 */
16
class ValidationException extends \Exception implements \JsonSerializable {
17
    /**
18
     * @var Validation
19
     */
20
    private $validation;
21
22
    /**
23
     * Initialize an instance of the {@link ValidationException} class.
24
     *
25
     * @param Validation $validation The {@link Validation} object for the exception.
26
     */
27 41
    public function __construct(Validation $validation) {
28 41
        $this->validation = $validation;
29 41
        parent::__construct($validation->getMessage(), (int)$validation->getStatus());
30 41
    }
31
32
    /**
33
     * Specify data which should be serialized to JSON.
34
     *
35
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
36
     * @return mixed data which can be serialized by <b>json_encode</b>,
37
     * which is a value of any type other than a resource.
38
     */
39
    public function jsonSerialize() {
40
        $errors = $this->validation->getErrors();
41
        if (count($errors) === 1) {
42
            $message = Validation::errorMessage($errors[0]);
0 ignored issues
show
Bug introduced by
The method errorMessage() does not exist on Garden\Schema\Validation. Did you maybe mean getErrorMessage()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
43
        } else {
44
            $message = 'Validation failed.';
45
        }
46
47
        $result = [
48
            'message' => $message,
49
            'status' => $this->getCode(),
50
            'errors' => $errors
51
        ];
52
        return $result;
53
    }
54
55
    /**
56
     * Get the validation object that contain specific errors.
57
     *
58
     * @return Validation Returns a validation object.
59
     */
60 30
    public function getValidation() {
61 30
        return $this->validation;
62
    }
63
}
64