run static method Null safety

ValidationContext run(
  1. ManagedObject object,
  2. {Validating event = Validating.insert}
)

Executes all Validates for object.

Validates the properties of object according to its validator annotations. Validators are added to properties using Validate metadata.

This method does not invoke ManagedObject.validate - any customization provided by a ManagedObject subclass that overrides this method will not be invoked.

Implementation

static ValidationContext run(
  ManagedObject object, {
  Validating event = Validating.insert,
}) {
  final context = ValidationContext();

  for (final validator in object.entity.validators) {
    context.property = validator!.property;
    context.event = event;
    context.state = validator.state;
    if (!validator.definition.runOnInsert && event == Validating.insert) {
      continue;
    }

    if (!validator.definition.runOnUpdate && event == Validating.update) {
      continue;
    }

    var contents = object.backing.contents;
    String? key = validator.property!.name;

    if (validator.definition.type == ValidateType.present) {
      if (validator.property is ManagedRelationshipDescription) {
        final inner = object[validator.property!.name] as ManagedObject?;
        if (inner == null ||
            !inner.backing.contents!.containsKey(inner.entity.primaryKey)) {
          context.addError("key '${validator.property!.name}' is required "
              "for ${_getEventName(event)}s.");
        }
      } else if (!contents!.containsKey(key)) {
        context.addError("key '${validator.property!.name}' is required "
            "for ${_getEventName(event)}s.");
      }
    } else if (validator.definition.type == ValidateType.absent) {
      if (validator.property is ManagedRelationshipDescription) {
        final inner = object[validator.property!.name] as ManagedObject?;
        if (inner != null) {
          context.addError("key '${validator.property!.name}' is not allowed "
              "for ${_getEventName(event)}s.");
        }
      } else if (contents!.containsKey(key)) {
        context.addError("key '${validator.property!.name}' is not allowed "
            "for ${_getEventName(event)}s.");
      }
    } else {
      if (validator.property is ManagedRelationshipDescription) {
        final inner = object[validator.property!.name] as ManagedObject?;
        if (inner == null ||
            inner.backing.contents![inner.entity.primaryKey] == null) {
          continue;
        }
        contents = inner.backing.contents;
        key = inner.entity.primaryKey;
      }

      final value = contents![key];
      if (value != null) {
        validator.validate(context, value);
      }
    }
  }

  return context;
}