AnPv2/Python/Utils/Validate.py
2026-05-01 10:12:58 +02:00

49 lines
1.6 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Any, Self
from Utils.Patterns import RE
class Validate:
IGNORE_NULL_OR_UNDEFINED:int = 1 << 0
EMPTY:int = 1 << 1
TRIM:int = 1 << 2
KEY:int = 1 << 3
FROM_TYPE:int = 1 << 4
@classmethod
def null_or_undefined(cls:type[Self], value:Any|None, options:int = 0) -> int:
""" 2 Options. 2 bits. """
return 0 if options & (cls.IGNORE_NULL_OR_UNDEFINED | cls.FROM_TYPE) else (
# 1 if value is undefined else
2 if value is None else
0)
@staticmethod
def null_or_undefined_message(key:str) -> list[str]:
return [
f"{key}_undefined",
f"{key}_null"
]
@classmethod
def string(cls:type[Self], value:Any|None, options:int = 0) -> int:
""" 7 options. 3 bits. """
return cls.null_or_undefined(value, options) or (
3 if not (options & cls.FROM_TYPE) and not isinstance(value, str) else
(4 if options & cls.EMPTY else 0) if value == "" else
(5 if options & cls.TRIM else 0) if value != (value := value.strip()) else
(6 if options & (cls.TRIM | cls.EMPTY) else 0) if value == "" else
(7 if options & cls.KEY else 0) if not RE.KEY.match(value) else
0)
@classmethod
def string_message(cls:type[Self], key:str) -> list[str]:
return cls.null_or_undefined_message(key) + [
f"{key}_not_string",
f"{key}_empty",
f"{key}_not_trimmed",
f"{key}_empty_trimmed",
f"{key}_not_key"
]