ValidationException   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 10
c 0
b 0
f 0
wmc 3
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A jsonSerialize() 0 15 2
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2014 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Exception;
9
10
use Garden\Validation;
11
12
/**
13
 * An exception that was built from a {@link Validation} object.
14
 *
15
 * The validation object collects errors and is mutable. Once it's ready to be thrown as an exception it gets converted
16
 * to an instance of the immutable {@link ValidationException} class.
17
 */
18
class ValidationException extends ClientException {
19
    protected $validation;
20
21
    /**
22
     * Initialize an instance of the {@link ValidationException} class.
23
     *
24
     * @param Validation $validation The {@link Validation} object for the exception.
25
     */
26
    public function __construct(Validation $validation) {
27
        $this->validation = $validation;
28
        parent::__construct($validation->getMessage(), (int)$validation->status());
29
    }
30
31
    /**
32
     * Specify data which should be serialized to JSON.
33
     *
34
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
35
     * @return mixed data which can be serialized by <b>json_encode</b>,
36
     * which is a value of any type other than a resource.
37
     */
38
    public function jsonSerialize() {
39
        $errors = $this->validation->getErrorsFlat();
40
        if (count($errors) === 1) {
41
            $message = Validation::errorMessage($errors[0]);
42
        } else {
43
            $message = t('Validation failed.');
44
        }
45
46
        $result = [
47
            'message' => $message,
48
            'status' => $this->getCode(),
49
            'errors' => $errors
50
        ];
51
        return $result;
52
    }
53
}
54