{"size": 1715, "ext": "js", "max_stars_repo_path": "src/validators/patternProperties.js", "max_stars_repo_name": "mokkabonna/vue-vuelidate-jsonschema", "max_stars_repo_stars_event_min_datetime": "2017-10-08T01:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T12:20:08.000Z", "max_issues_repo_path": "src/validators/patternProperties.js", "max_issues_repo_name": "mokkabonna/vue-vuelidate-jsonschema", "max_issues_repo_issues_event_min_datetime": "2017-10-09T15:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T17:31:50.000Z", "max_forks_repo_path": "src/validators/patternProperties.js", "max_forks_repo_name": "mokkabonna/vue-vuelidate-jsonschema", "max_forks_repo_forks_event_min_datetime": "2018-07-13T14:36:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T07:43:25.000Z"}
{"max_stars_count": 96, "max_issues_count": 21, "max_forks_count": 9, "avg_line_length": 32.358490566, "max_line_length": 117, "alphanum_fraction": 0.6787172012}
var vuelidate = require('vuelidate')
var isPlainObject = require('lodash/isPlainObject')
var every = require('lodash/every')
var reduce = require('lodash/reduce')
var filter = require('lodash/filter')
var validate = require('../validate')

module.exports = function patternPropertiesValidator(propertySchema, patternProperties, getPropertyValidationRules) {
  return vuelidate.withParams({
    type: 'schemaPatternProperties',
    patternProperties: patternProperties,
    schema: propertySchema
  }, function(object) {
    if (!isPlainObject(object)) return true

    if (propertySchema.additionalProperties !== undefined &&
      !isPlainObject(propertySchema.additionalProperties) &&
      propertySchema.additionalProperties !== true
    ) {
      var allowedKeys = Object.keys(patternProperties).map(function(key) {
        return new RegExp(key)
      })

      var allKeysAreValid = Object.keys(object).every(function(key) {
        // we have key, therefore it is valid
        if (propertySchema.properties && propertySchema.properties[key]) return true

        return allowedKeys.some(function(regexp) {
          return regexp.test(key)
        })
      })

      // fail early if some keys are not present
      if (!allKeysAreValid) {
        return false
      }
    }

    var schemasForKeys = reduce(object, function(all, value, key) {
      all[key] = filter(patternProperties, function(schema, pattern) {
        return new RegExp(pattern).test(key)
      })
      return all
    }, {})

    return every(schemasForKeys, function(schemas, key) {
      return schemas.every(function(itemSchema) {
        return validate(getPropertyValidationRules(itemSchema), object[key])
      })
    })
  })
}
