1 | <?php |
||
2 | |||
3 | namespace SilverStripe\ORM; |
||
4 | |||
5 | use Exception; |
||
6 | use InvalidArgumentException; |
||
7 | use SilverStripe\Core\Injector\Injectable; |
||
8 | |||
9 | /** |
||
10 | * Exception thrown by {@link DataObject}::write if validation fails. By throwing an |
||
11 | * exception rather than a user error, the exception can be caught in unit tests and as such |
||
12 | * can be used as a successful test. |
||
13 | */ |
||
14 | class ValidationException extends Exception |
||
15 | { |
||
16 | use Injectable; |
||
17 | |||
18 | /** |
||
19 | * The contained ValidationResult related to this error |
||
20 | * |
||
21 | * @var ValidationResult |
||
22 | */ |
||
23 | protected $result; |
||
24 | |||
25 | /** |
||
26 | * Construct a new ValidationException with an optional ValidationResult object |
||
27 | * |
||
28 | * @param ValidationResult|string $result The ValidationResult containing the |
||
29 | * failed result, or error message to build error from |
||
30 | * @param integer $code The error code number |
||
31 | */ |
||
32 | public function __construct($result = null, $code = 0) |
||
33 | { |
||
34 | // Catch legacy behaviour where second argument was not code |
||
35 | if ($code && !is_numeric($code)) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
36 | throw new InvalidArgumentException("Code must be numeric"); |
||
37 | } |
||
38 | |||
39 | // Set default message and result |
||
40 | $exceptionMessage = _t("SilverStripe\\ORM\\ValidationException.DEFAULT_ERROR", "Validation error"); |
||
41 | if (!$result) { |
||
42 | $result = $exceptionMessage; |
||
43 | } |
||
44 | |||
45 | // Check result type |
||
46 | if ($result instanceof ValidationResult) { |
||
47 | $this->result = $result; |
||
48 | // Pick first message |
||
49 | foreach ($result->getMessages() as $message) { |
||
50 | $exceptionMessage = $message['message']; |
||
51 | break; |
||
52 | } |
||
53 | } elseif (is_string($result)) { |
||
54 | $this->result = ValidationResult::create()->addError($result); |
||
55 | $exceptionMessage = $result; |
||
56 | } else { |
||
57 | throw new InvalidArgumentException( |
||
58 | "ValidationExceptions must be passed a ValdiationResult, a string, or nothing at all" |
||
59 | ); |
||
60 | } |
||
61 | |||
62 | parent::__construct($exceptionMessage, $code); |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Retrieves the ValidationResult related to this error |
||
67 | * |
||
68 | * @return ValidationResult |
||
69 | */ |
||
70 | public function getResult() |
||
71 | { |
||
72 | return $this->result; |
||
73 | } |
||
74 | } |
||
75 |