4 * This file is part of the JsonSchema package.
6 * For the full copyright and license information, please view the LICENSE
7 * file that was distributed with this source code.
10 namespace JsonSchema\Constraints;
12 use JsonSchema\Entity\JsonPointer;
13 use JsonSchema\Exception\InvalidArgumentException;
14 use JsonSchema\Exception\ValidationException;
15 use JsonSchema\Validator;
18 * A more basic constraint definition - used for the public
19 * interface to avoid exposing library internals.
26 protected $errors = array();
29 * @var int All error types which have occurred
31 protected $errorMask = Validator::ERROR_NONE;
39 * @param Factory $factory
41 public function __construct(Factory $factory = null)
43 $this->factory = $factory ?: new Factory();
46 public function addError(JsonPointer $path = null, $message, $constraint = '', array $more = null)
49 'property' => $this->convertJsonPointerIntoPropertyPath($path ?: new JsonPointer('')),
50 'pointer' => ltrim(strval($path ?: new JsonPointer('')), '#'),
51 'message' => $message,
52 'constraint' => $constraint,
53 'context' => $this->factory->getErrorContext(),
56 if ($this->factory->getConfig(Constraint::CHECK_MODE_EXCEPTIONS)) {
57 throw new ValidationException(sprintf('Error validating %s: %s', $error['pointer'], $error['message']));
60 if (is_array($more) && count($more) > 0) {
64 $this->errors[] = $error;
65 $this->errorMask |= $error['context'];
68 public function addErrors(array $errors)
71 $this->errors = array_merge($this->errors, $errors);
72 $errorMask = &$this->errorMask;
73 array_walk($errors, function ($error) use (&$errorMask) {
74 if (isset($error['context'])) {
75 $errorMask |= $error['context'];
81 public function getErrors($errorContext = Validator::ERROR_ALL)
83 if ($errorContext === Validator::ERROR_ALL) {
87 return array_filter($this->errors, function ($error) use ($errorContext) {
88 if ($errorContext & $error['context']) {
94 public function numErrors($errorContext = Validator::ERROR_ALL)
96 if ($errorContext === Validator::ERROR_ALL) {
97 return count($this->errors);
100 return count($this->getErrors($errorContext));
103 public function isValid()
105 return !$this->getErrors();
109 * Clears any reported errors. Should be used between
110 * multiple validation checks.
112 public function reset()
114 $this->errors = array();
115 $this->errorMask = Validator::ERROR_NONE;
123 public function getErrorMask()
125 return $this->errorMask;
129 * Recursively cast an associative array to an object
131 * @param array $array
135 public static function arrayToObjectRecursive($array)
137 $json = json_encode($array);
138 if (json_last_error() !== \JSON_ERROR_NONE) {
139 $message = 'Unable to encode schema array as JSON';
140 if (function_exists('json_last_error_msg')) {
141 $message .= ': ' . json_last_error_msg();
143 throw new InvalidArgumentException($message);
146 return (object) json_decode($json);