Class: Castkit::Contract::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/castkit/contract/validator.rb

Overview

Responsible for validating input against a set of Castkit::Attribute definitions.

The validator supports:

  • Primitive type validation

  • Nested Castkit::DataObject validation

  • Collections of DataObjects

  • Strict or relaxed key handling

Returns a hash of errors if validation fails, keyed by attribute name.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(attributes, input, **options) ⇒ Hash{Symbol => String, Hash, nil}

Validates input against the provided attribute definitions.

Parameters:

  • attributes (Array<Castkit::Attribute>)

    the attributes to validate

  • input (Hash)

    the raw input data

  • options (Hash)

    validator options:

    • strict: whether unknown keys should raise

    • allow_unknown: whether unknown keys are permitted

    • warn_on_unknown: whether to log warnings for unknown keys

Returns:

  • (Hash{Symbol => String, Hash, nil})

    validation errors per attribute



28
29
30
# File 'lib/castkit/contract/validator.rb', line 28

def call(attributes, input, **options)
  new(attributes, **options).call(input)
end

.call!(attributes, input, **options) ⇒ Object



32
33
34
35
# File 'lib/castkit/contract/validator.rb', line 32

def call!(attributes, input, **options)
  errors = call(attributes, input, **options)
  raise Castkit::ContractError.new("Validation failed", errors: errors) if errors.any?
end

Instance Method Details

#call(input) ⇒ Hash{Symbol => String, Hash}

Executes validation against the input data.

Parameters:

  • input (Hash)

    the incoming data to validate

Returns:

  • (Hash{Symbol => String, Hash})

    validation errors, empty if valid



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/castkit/contract/validator.rb', line 42

def call(input)
  validate_access_config!
  errors = {}

  @attributes.each do |attribute|
    value = resolve_input_value(input, attribute)
    error = validate_attribute(attribute, value)

    errors[attribute.field] = error if error
  end

  validate_unknown_attributes!(input, errors)
  errors
end