Validates string keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool
175497
protected function validateString(/** @noinspection PhpUnusedParameterInspection */
        &$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
    {
        $ok = true;

        // minLength
        if (property_exists($schema, 'minLength')) {
            if (!is_int($schema->minLength)) {
                throw new SchemaKeywordException(
                    $schema,
                    'minLength',
                    $schema->minLength,
                    "'minLength' keyword must be an integer, " . gettype($schema->minLength) . " given"
                );
            }
            if ($schema->minLength < 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'minLength',
                    $schema->minLength,
                    "'minLength' keyword must be positive, " . $schema->minLength . " given"
                );
            }
            $len = $this->helper->stringLength($data);
            if ($len < $schema->minLength) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minLength', [
                    'min' => $schema->minLength,
                    'length' => $len,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($len);
        }

        // maxLength
        if (property_exists($schema, 'maxLength')) {
            if (!is_int($schema->maxLength)) {
                throw new SchemaKeywordException(
                    $schema,
                    'maxLength',
                    $schema->maxLength,
                    "'maxLength' keyword must be an integer, " . gettype($schema->maxLength) . " given"
                );
            }
            if ($schema->maxLength < 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'maxLength',
                    $schema->maxLength,
                    "'maxLength' keyword must be positive, " . $schema->maxLength . " given"
                );
            }
            $len = $this->helper->stringLength($data);
            if ($len > $schema->maxLength) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxLength', [
                    'max' => $schema->maxLength,
                    'length' => $len,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($len);
        }

        // pattern
        if (property_exists($schema, 'pattern')) {
            if (!is_string($schema->pattern)) {
                throw new SchemaKeywordException(
                    $schema,
                    'pattern',
                    $schema->pattern,
                    "'pattern' keyword must be a string, " . gettype($schema->pattern) . " given"
                );
            }
            if ($schema->pattern === '') {
                throw new SchemaKeywordException(
                    $schema,
                    'pattern',
                    $schema->pattern,
                    "'pattern' keyword must not be empty"
                );
            }
            $match = @preg_match(self::BELL . $schema->pattern . self::BELL . 'u', $data);
            if ($match === false) {
                throw new SchemaKeywordException(
                    $schema,
                    'pattern',
                    $schema->pattern,
                    "'pattern' keyword must be a valid regex"
                );
            }
            if (!$match) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'pattern', [
                    'pattern' => $schema->pattern,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // content encoding
        if (property_exists($schema, 'contentEncoding')) {
            if (!is_string($schema->contentEncoding)) {
                throw new SchemaKeywordException(
                    $schema,
                    'contentEncoding',
                    $schema->contentEncoding,
                    "'contentEncoding' keyword must be a string, " . gettype($schema->contentEncoding) . " given"
                );
            }

            switch ($schema->contentEncoding) {
                case "binary":
                    $decoded = $data;
                    break;
                case "base64":
                    $decoded = base64_decode($data, true);
                    break;
                default:
                    $decoded = false;
                    break;
            }

            if ($decoded === false) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentEncoding', [
                    'encoding' => $schema->contentEncoding,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // media type
        if (property_exists($schema, 'contentMediaType')) {
            if (!is_string($schema->contentMediaType)) {
                throw new SchemaKeywordException(
                    $schema,
                    'contentMediaType',
                    $schema->contentMediaType,
                    "'contentMediaType' keyword must be a string, " . gettype($schema->contentMediaType) . " given"
                );
            }

            if (!$this->mediaTypes) {
                throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
            }

            if (!isset($decoded)) {
                // is set in contentEncoding if any
                $decoded = $data;
            }

            $valid = false;

            if ($decoded !== false) {
                $media = $this->mediaTypes->resolve($schema->contentMediaType);
                if ($media === null) {
                    throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
                } else {
                    $valid = $media->validate($decoded, $schema->contentMediaType);
                }
            }

            if (!$valid) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentMediaType', [
                    'media' => $schema->contentMediaType,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        return $ok;
    }
694094
function validation($data, $files) {
        global $COURSE, $DB, $CFG;
        $errors = parent::validation($data, $files);

        $mform =& $this->_form;

        $errors = array();

        if ($mform->elementExists('name')) {
            $name = trim($data['name']);
            if ($name == '') {
                $errors['name'] = get_string('required');
            }
        }

        $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
                     'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
        if ($data['coursemodule']) {
            $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
        } else {
            $cm = null;
        }

        if ($mform->elementExists('cmidnumber')) {
            // verify the idnumber
            if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
                $errors['cmidnumber'] = get_string('idnumbertaken');
            }
        }

        // Ratings: Don't let them select an aggregate type without selecting a scale.
        // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
        // invalid. If ratings have been selected then the user must select either a scale or max points.
        // This matches (horrible) logic in data_preprocessing.
        if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
            $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
        }

        // Check that the grade pass is a valid number.
        $gradepassvalid = false;
        if (isset($data['gradepass'])) {
            if (unformat_float($data['gradepass'], true) === false) {
                $errors['gradepass'] = get_string('err_numeric', 'form');
            } else {
                $gradepassvalid = true;
            }
        }

        // Grade to pass: ensure that the grade to pass is valid for points and scales.
        // If we are working with a scale, convert into a positive number for validation.
        if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
            $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
            if ($scale < 0) {
                $scalevalues = $DB->get_record('scale', array('id' => -$scale));
                $grade = count(explode(',', $scalevalues->scale));
            } else {
                $grade = $scale;
            }
            if (unformat_float($data['gradepass']) > $grade) {
                $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
            }
        }

        // Completion: Don't let them choose automatic completion without turning
        // on some conditions. Ignore this check when completion settings are
        // locked, as the options are then disabled.
        if (array_key_exists('completion', $data) &&
                $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
                !empty($data['completionunlocked'])) {
            if (empty($data['completionview']) && empty($data['completionusegrade']) &&
                !$this->completion_rule_enabled($data)) {
                $errors['completion'] = get_string('badautocompletion', 'completion');
            }
        }

        // Availability: Check availability field does not have errors.
        if (!empty($CFG->enableavailability)) {
            \core_availability\frontend::report_validation_errors($data, $errors);
        }

        $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
        if (!empty($pluginerrors)) {
            $errors = array_merge($errors, $pluginerrors);
        }

        return $errors;
    }
678344
public function validate($data = null, $entity = null)
    {
        if (is_null($data)) {
            $data = $this->getData();
        }

        $this->data = $data;
        return !count(parent::validate($data, $entity));
    }
742773
function validation($data, $files) {
        global $COURSE, $DB;

        $errors = parent::validation($data, $files);

        $name = trim($data['name']);
        if (isset($data['idnumber'])) {
            $idnumber = trim($data['idnumber']);
        } else {
            $idnumber = '';
        }
        if ($data['id'] and $grouping = $DB->get_record('groupings', array('id'=>$data['id']))) {
            if (core_text::strtolower($grouping->name) != core_text::strtolower($name)) {
                if (groups_get_grouping_by_name($COURSE->id,  $name)) {
                    $errors['name'] = get_string('groupingnameexists', 'group', $name);
                }
            }
            if (!empty($idnumber) && $grouping->idnumber != $idnumber) {
                if (groups_get_grouping_by_idnumber($COURSE->id, $idnumber)) {
                    $errors['idnumber']= get_string('idnumbertaken');
                }
            }

        } else if (groups_get_grouping_by_name($COURSE->id, $name)) {
            $errors['name'] = get_string('groupingnameexists', 'group', $name);
        } else if (!empty($idnumber) && groups_get_grouping_by_idnumber($COURSE->id, $idnumber)) {
            $errors['idnumber']= get_string('idnumbertaken');
        }

        return $errors;
    }
442831
protected function validateNumber(/** @noinspection PhpUnusedParameterInspection */
        &$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
    {
        $ok = true;

        // minimum, exclusiveMinimum
        if (property_exists($schema, 'minimum')) {
            if (!is_int($schema->minimum) && !is_float($schema->minimum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'minimum',
                    $schema->minimum,
                    "'minimum' keyword must be an integer or a float, " . gettype($schema->minimum) . " given"
                );
            }

            $exclusive = false;
            if (property_exists($schema, 'exclusiveMinimum')) {
                if (!is_bool($schema->exclusiveMinimum)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'exclusiveMinimum',
                        $schema->exclusiveMinimum,
                        "'exclusiveMinimum' keyword must be a boolean if 'minimum' keyword is present, " . gettype($schema->exclusiveMinimum) . " given"
                    );
                }
                $exclusive = $schema->exclusiveMinimum;
            }

            if ($exclusive && $data == $schema->minimum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
                    'min' => $schema->minimum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            } elseif ($data < $schema->minimum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minimum', [
                    'min' => $schema->minimum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        } elseif (property_exists($schema, 'exclusiveMinimum')) {
            if (!is_int($schema->exclusiveMinimum) && !is_float($schema->exclusiveMinimum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'exclusiveMinimum',
                    $schema->exclusiveMinimum,
                    "'exclusiveMinimum' keyword must be an integer or a float if 'minimum' keyword is not present, " . gettype($schema->exclusiveMinimum) . " given"
                );
            }
            if ($data <= $schema->exclusiveMinimum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
                    'min' => $schema->exclusiveMinimum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // maximum, exclusiveMaximum
        if (property_exists($schema, 'maximum')) {
            if (!is_int($schema->maximum) && !is_float($schema->maximum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'maximum',
                    $schema->maximum,
                    "'maximum' keyword must be an integer or a float, " . gettype($schema->maximum) . " given"
                );
            }

            $exclusive = false;
            if (property_exists($schema, 'exclusiveMaximum')) {
                if (!is_bool($schema->exclusiveMaximum)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'exclusiveMaximum',
                        $schema->exclusiveMaximum,
                        "'exclusiveMaximum' keyword must be a boolean is 'maximum' keyword is present, " . gettype($schema->exclusiveMaximum) . " given"
                    );
                }
                $exclusive = $schema->exclusiveMaximum;
            }

            if ($exclusive && $data == $schema->maximum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
                    'max' => $schema->maximum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            } elseif ($data > $schema->maximum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maximum', [
                    'max' => $schema->maximum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        } elseif (property_exists($schema, 'exclusiveMaximum')) {
            if (!is_int($schema->exclusiveMaximum) && !is_float($schema->exclusiveMaximum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'exclusiveMaximum',
                    $schema->exclusiveMaximum,
                    "'exclusiveMaximum' keyword must be an integer or a float if 'maximum' keyword is not present, " . gettype($schema->exclusiveMaximum) . " given"
                );
            }
            if ($data >= $schema->exclusiveMaximum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
                    'max' => $schema->exclusiveMaximum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // multipleOf
        if (property_exists($schema, 'multipleOf')) {
            if (!is_int($schema->multipleOf) && !is_float($schema->multipleOf)) {
                throw new SchemaKeywordException(
                    $schema,
                    'multipleOf',
                    $schema->multipleOf,
                    "'multipleOf' keyword must be an integer or a float, " . gettype($schema->multipleOf) . " given"
                );
            }
            if ($schema->multipleOf <= 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'multipleOf',
                    $schema->multipleOf,
                    "'multipleOf' keyword must be greater than 0"
                );
            }
            if (!$this->helper->isMultipleOf($data, $schema->multipleOf)) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'multipleOf', [
                    'divisor' => $schema->multipleOf
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        return $ok;
    }
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)
591504
function validation($data, $files) {
        global $DB, $CFG;

        $errors = parent::validation($data, $files);

        if ($data['courseid'] > 0) {
            if ($course = $DB->get_record('course', array('id'=>$data['courseid']))) {
                if ($data['timestart'] < $course->startdate) {
                    $errors['timestart'] = get_string('errorbeforecoursestart', 'calendar');
                }
            } else {
                $errors['courseid'] = get_string('invalidcourse', 'error');
            }

        }

        if ($data['duration'] == 1 && $data['timestart'] > $data['timedurationuntil']) {
            $errors['timedurationuntil'] = get_string('invalidtimedurationuntil', 'calendar');
        } else if ($data['duration'] == 2 && (trim($data['timedurationminutes']) == '' || $data['timedurationminutes'] < 1)) {
            $errors['timedurationminutes'] = get_string('invalidtimedurationminutes', 'calendar');
        }

        return $errors;
    }
1336639
private function validateNode($node, CustomArrayObject $schema, $element = [])
    {
        $nodeSchema = new CustomArrayObject($schema[$node]);

        foreach ($nodeSchema->getArrayKeys() as $key) {
            $this->currentNode = $node . '.' . $key;
            $this->getLogger()->info("We are in element: {$this->currentNode}");

            $nodeData = isset($element[$key]) ? $element[$key] : null;


            $this->validateTypeFieldIsPresent($nodeSchema[$key]);

            $validator = $this->getClassValidator($nodeSchema[$key]);
            $validator->setParams($this->params);

            $isRequired = $this->requiredMode ? $validator->isRequired() : false;

            if ($isRequired === false && empty($nodeData)) {
                $this->getLogger()->info("Element: {$this->currentNode} has empty non-required data. We skip other check");
                continue;
            }

            $this->validateRequiredFieldIsPresent($nodeData);

            $this->validateExcessiveKeys($validator, new CustomArrayObject($nodeSchema[$key]), $nodeData);

            $this->validateNodeValue($validator, $nodeData);

            $this->validateNesting($validator, $nodeData);

            if ($validator->isNested()) {
                $this->getLogger()->info("Element: {$this->currentNode} has children");

                foreach ($nodeData as $record) {
                    $this->validateNode($key, $nodeSchema, $record);
                }
            } else {
                $this->validateNode($key, $nodeSchema, $nodeData);
            }

            $this->getLogger()->info("Element: {$this->currentNode} finished checking successfully.");
        }
    }
1258273
function validation($data, $files) {
        global $USER;
        $errors = parent::validation($data, $files);
        $reason = null;

        // ignore submitted username
        if (!$user = authenticate_user_login($USER->username, $data['password'], true, $reason, false)) {
            $errors['password'] = get_string('invalidlogin');
            return $errors;
        }

        if ($data['newpassword1'] <> $data['newpassword2']) {
            $errors['newpassword1'] = get_string('passwordsdiffer');
            $errors['newpassword2'] = get_string('passwordsdiffer');
            return $errors;
        }

        if ($data['password'] == $data['newpassword1']){
            $errors['newpassword1'] = get_string('mustchangepassword');
            $errors['newpassword2'] = get_string('mustchangepassword');
            return $errors;
        }

        if (user_is_previously_used_password($USER->id, $data['newpassword1'])) {
            $errors['newpassword1'] = get_string('errorpasswordreused', 'core_auth');
            $errors['newpassword2'] = get_string('errorpasswordreused', 'core_auth');
        }

        $errmsg = '';//prevents eclipse warnings
        if (!check_password_policy($data['newpassword1'], $errmsg)) {
            $errors['newpassword1'] = $errmsg;
            $errors['newpassword2'] = $errmsg;
            return $errors;
        }

        return $errors;
    }
1008651
function validation($data, $files) {
        global $CFG, $COURSE;
        $errors = parent::validation($data, $files);

        if ($data['allocateby'] != 'no') {
            $source = array();
            if ($data['cohortid']) {
                $source['cohortid'] = $data['cohortid'];
            }
            if ($data['groupingid']) {
                $source['groupingid'] = $data['groupingid'];
            }
            if ($data['groupid']) {
                $source['groupid'] = $data['groupid'];
            }
            if (!$users = groups_get_potential_members($data['courseid'], $data['roleid'], $source)) {
                $errors['roleid'] = get_string('nousersinrole', 'group');
            }

           /// Check the number entered is sane
            if ($data['groupby'] == 'groups') {
                $usercnt = count($users);

                if ($data['number'] > $usercnt || $data['number'] < 1) {
                    $errors['number'] = get_string('toomanygroups', 'group', $usercnt);
                }
            }
        }

        //try to detect group name duplicates
        $name = groups_parse_name(trim($data['namingscheme']), 0);
        if (groups_get_group_by_name($COURSE->id, $name)) {
            $errors['namingscheme'] = get_string('groupnameexists', 'group', $name);
        }

        // check grouping name duplicates
        if ( isset($data['grouping']) && $data['grouping'] == '-1') {
            $name = trim($data['groupingname']);
            if (empty($name)) {
                $errors['groupingname'] = get_string('required');
            } else if (groups_get_grouping_by_name($COURSE->id, $name)) {
                $errors['groupingname'] = get_string('groupingnameexists', 'group', $name);
            }
        }

       /// Check the naming scheme
        if ($data['groupby'] == 'groups' and $data['number'] == 1) {
            // we can use the name as is because there will be only one group max
        } else {
            $matchcnt = preg_match_all('/[#@]{1,1}/', $data['namingscheme'], $matches);
            if ($matchcnt != 1) {
                $errors['namingscheme'] = get_string('badnamingscheme', 'group');
            }
        }

        return $errors;
    }
266939
function validation($data, $files) {
        $errors = parent::validation($data, $files);

        $mform =& $this->_form;

        // check the calculation formula
        if ($data['calculation'] != '') {
            $grade_item = grade_item::fetch(array('id'=>$data['id'], 'courseid'=>$data['courseid']));
            $calculation = calc_formula::unlocalize(stripslashes($data['calculation']));
            $result = $grade_item->validate_formula($calculation);
            if ($result !== true) {
                $errors['calculation'] = $result;
            }
        }

        return $errors;
    }
1182480
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        // We don't need to verify the email address if we're clearing a pending email verification attempt.
        if (!isset($data['revertbutton'])) {
            $check = new stdClass();
            $check->backpackurl = BADGE_BACKPACKURL;
            $check->email = $data['email'];

            $bp = new OpenBadgesBackpackHandler($check);
            $request = $bp->curl_request('user');
            if (isset($request->status) && $request->status == 'missing') {
                $errors['email'] = get_string('error:nosuchuser', 'badges');
            } else if (!isset($request->status) || $request->status !== 'okay') {
                $errors['email'] = get_string('backpackconnectionunexpectedresult', 'badges');
            }
        }
        return $errors;
    }
681780
def validate_single_doc(schema, doc)
      schema = Nokogiri::XML::Schema(File.open(schema))
      doc = Nokogiri::XML(doc)
      errors = []
      schema.validate(doc).each do |error|
        errors << error
      end
      errors
    end
429607
protected function validateData()
    {
        foreach ($this->relationalData as $attribute => &$data) {
            /** @var ActiveRecord $model */
            /** @var ActiveQuery $activeQuery */
            $activeQuery = $data['activeQuery'];
            foreach ($data['newModels'] as &$model) {
                if (!$model->validate()) {
                    $_errors = $model->getErrors();
                    $errors = [];

                    foreach ($_errors as $relatedAttribute => $error) {
                        if (!$activeQuery->multiple || !isset($activeQuery->link[$relatedAttribute])) {
                            $errors[$relatedAttribute] = $error;
                        }
                    }

                    if (count($errors)) {
                        $this->owner->addError($attribute, $errors);

                        return false;
                    }
                }
            }
        }

        return true;
    }
1022576
protected function validateObject(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array &$defaults = null): bool
    {
        $ok = true;

        // required
        if (property_exists($schema, 'required')) {
            if (!is_array($schema->required)) {
                throw new SchemaKeywordException(
                    $schema,
                    'required',
                    $schema->required,
                    "'required' keyword must be an array, " . gettype($schema->required) . " given"
                );
            }
            foreach ($schema->required as $prop) {
                if (!is_string($prop)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'required',
                        $schema->required,
                        "'required' keyword items must be strings, found " . gettype($prop)
                    );
                }
                if (!property_exists($data, $prop) && !($defaults && array_key_exists($prop, $defaults))) {
                    $ok = false;
                    $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'required', [
                        'missing' => $prop,
                    ]));
                    if ($bag->isFull()) {
                        return false;
                    }
                }
            }
        }

        // dependencies
        if (property_exists($schema, 'dependencies')) {
            if (!is_object($schema->dependencies)) {
                throw new SchemaKeywordException(
                    $schema,
                    'dependencies',
                    $schema->dependencies,
                    "'dependencies' keyword must be an object, " . gettype($schema->dependencies) . " given"
                );
            }
            foreach ($schema->dependencies as $name => &$value) {
                if (!property_exists($data, $name)) {
                    unset($value);
                    continue;
                }
                if (is_array($value)) {
                    foreach ($value as $prop) {
                        if (!is_string($prop)) {
                            throw new SchemaKeywordException(
                                $schema,
                                'dependencies',
                                $schema->dependencies,
                                "'dependencies' keyword items can only be array of strings, objects or booleans, found array with " . gettype($prop)
                            );
                        }
                        if (!property_exists($data, $prop) && !($defaults && array_key_exists($prop, $defaults))) {
                            $ok = false;
                            $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'dependencies', [
                                'missing' => $prop,
                            ]));
                            if ($bag->isFull()) {
                                return false;
                            }
                        }
                    }
                    unset($prop, $value);
                    continue;
                }

                if (!is_bool($value) && !is_object($value)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'dependencies',
                        $schema->dependencies,
                        "'dependencies' keyword items can only be array of strings, objects or booleans, found " . gettype($value)
                    );
                }

                $this->setObjectDefaults($data, $defaults);
                $valid = $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $value, $bag);
                if (!$valid) {
                    $ok = false;
                    if ($bag->isFull()) {
                        return false;
                    }
                }
                unset($valid, $value);
            }
        }

        $properties = array_keys(get_object_vars($data));

        // minProperties
        if (property_exists($schema, 'minProperties')) {
            if (!is_int($schema->minProperties)) {
                throw new SchemaKeywordException(
                    $schema,
                    'minProperties',
                    $schema->minProperties,
                    "'minProperties' keyword must be an integer, " . gettype($schema->minProperties) . " given"
                );
            }
            if ($schema->minProperties < 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'minProperties',
                    $schema->minProperties,
                    "'minProperties' keyword must be positive, " . $schema->minProperties . " given"
                );
            }
            $count = count($properties);
            if ($defaults) {
                $count += count($defaults);
            }
            if ($count < $schema->minProperties) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minProperties', [
                    'min' => $schema->minProperties,
                    'count' => $count,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($count);
        }

        // maxProperties
        if (property_exists($schema, 'maxProperties')) {
            if (!is_int($schema->maxProperties)) {
                throw new SchemaKeywordException(
                    $schema,
                    'maxProperties',
                    $schema->maxProperties,
                    "'maxProperties' keyword must be an integer, " . gettype($schema->maxProperties) . " given"
                );
            }
            if ($schema->maxProperties < 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'maxProperties',
                    $schema->maxProperties,
                    "'maxProperties' keyword must be positive, " . $schema->maxProperties . " given"
                );
            }

            $count = count($properties);
            if ($defaults) {
                $count += count($defaults);
            }
            if ($count > $schema->maxProperties) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxProperties', [
                    'min' => $schema->maxProperties,
                    'count' => $count,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($count);
        }

        // propertyNames
        if (property_exists($schema, 'propertyNames')) {
            if (!is_bool($schema->propertyNames) && !is_object($schema->propertyNames)) {
                throw new SchemaKeywordException(
                    $schema,
                    'propertyNames',
                    $schema->propertyNames,
                    "'propertyNames' keyword must be a boolean or an object, " . gettype($schema->propertyNames) . " given"
                );
            }
            $newbag = $bag->createByDiff();
            foreach ($properties as $property) {
                if (!$this->validateSchema($document_data, $property, $data_pointer, $parent_data_pointer, $document, $schema->propertyNames, $newbag)) {
                    $ok = false;
                    $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'propertyNames', [
                        'property' => $property
                    ], $newbag->getErrors()));
                    if ($bag->isFull()) {
                        return false;
                    }
                }
                $newbag->clear();
            }
            unset($newbag);
        }

        $checked_properties = [];

        // properties
        if (property_exists($schema, 'properties')) {
            if (!is_object($schema->properties)) {
                throw new SchemaKeywordException(
                    $schema,
                    'properties',
                    $schema->properties,
                    "'properties' keyword must be an object, " . gettype($schema->properties) . " given"
                );
            }
            foreach ($schema->properties as $name => &$property) {
                if (!is_bool($property) && !is_object($property)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'properties',
                        $schema->properties,
                        "'properties' keyword items must be booleans or objects, found " . gettype($property)
                    );
                }
                $checked_properties[] = $name;
                if (property_exists($data, $name)) {
                    $data_pointer[] = $name;
                    $valid = $this->validateSchema($document_data, $data->{$name}, $data_pointer, $parent_data_pointer, $document, $property, $bag);
                    array_pop($data_pointer);
                    if (!$valid) {
                        $ok = false;
                        if ($bag->isFull()) {
                            return false;
                        }
                    }
                }
                unset($property, $name);
            }
        }

        // patternProperties
        if (property_exists($schema, 'patternProperties')) {
            if (!is_object($schema->patternProperties)) {
                throw new SchemaKeywordException(
                    $schema,
                    'patternProperties',
                    $schema->patternProperties,
                    "'patternProperties' keyword must be an object, " . gettype($schema->patternProperties) . " given"
                );
            }

            $newbag = $bag->createByDiff();
            foreach ($schema->patternProperties as $pattern => &$property_schema) {
                $regex = self::BELL . $pattern . self::BELL . 'u';
                foreach ($properties as $name) {
                    $match = @preg_match($regex, $name);
                    if ($match === false) {
                        throw new SchemaKeywordException(
                            $schema,
                            'patternProperties',
                            $schema->patternProperties,
                            "'patternProperties' keyword must have as properties valid regex expressions, found " . $pattern
                        );
                    }
                    if (!$match) {
                        continue;
                    }
                    if (!in_array($name, $checked_properties)) {
                        $checked_properties[] = $name;
                    }
                    $data_pointer[] = $name;
                    $valid = $this->validateSchema($document_data, $data->{$name}, $data_pointer, $parent_data_pointer, $document, $property_schema, $newbag);
                    array_pop($data_pointer);
                    if (!$valid && $newbag->isFull()) {
                        break 2;
                    }
                }
            }
            unset($property_schema, $regex);
            if ($newbag->hasErrors()) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'patternProperties', [], $newbag->getErrors()));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($newbag);
        }

        // additionalProperties
        if (property_exists($schema, 'additionalProperties')) {
            if (!is_bool($schema->additionalProperties) && !is_object($schema->additionalProperties)) {
                throw new SchemaKeywordException(
                    $schema,
                    'additionalProperties',
                    $schema->additionalProperties,
                    "'additionalProperties' keyword must be a boolean or an object, " . gettype($schema->additionalProperties) . " given"
                );
            }
            $newbag = $bag->createByDiff();
            foreach (array_diff($properties, $checked_properties) as $property) {
                $data_pointer[] = $property;
                $valid = $this->validateSchema($document_data, $data->{$property}, $data_pointer, $parent_data_pointer, $document, $schema->additionalProperties, $newbag);
                array_pop($data_pointer);
                unset($property);
                if (!$valid && $newbag->isFull()) {
                    break;
                }
            }
            if ($newbag->hasErrors()) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'additionalProperties', [], $newbag->getErrors()));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($newbag);
        }

        // set defaults
        $this->setObjectDefaults($data, $defaults);

        return $ok;
    }
1348168
public boolean canValidate(Document doc) {
        XsdSchema schema = schemaMappingStrategy.getSchema(schemas, doc);
        return schema != null;
    }
801129
private function isChildElementHasStrictKeys(CustomArrayObject $nodeSchema, $nodeData)
    {
        $returnValue = false;

        if (!empty($nodeData) && is_array($nodeData)) {
            $schemaKeys = $nodeSchema->getArrayKeys();
            $dataKeys = count(array_filter(array_keys($nodeData), 'is_string')) ? array_keys($nodeData) : [];
            $returnValue = (bool)array_diff($dataKeys, $schemaKeys);
        }

        return $returnValue;
    }