Back to index

plone3  3.1.7
service.py
Go to the documentation of this file.
00001 try:
00002     from Products.validation.interfaces.IValidationService import IValidationService
00003     from Products.validation.interfaces.IValidator import IValidator
00004 except ImportError:
00005     from validation.interfaces.IValidationService import IValidationService
00006     from validation.interfaces.IValidator import IValidator
00007 
00008 from exceptions import UnknowValidatorError, FalseValidatorError, AlreadyRegisteredValidatorError
00009 from types import StringType, StringTypes
00010 
00011 class Service:
00012     __implements__ = IValidationService
00013 
00014     def __init__(self):
00015         self._validator = {}
00016 
00017     def validate(self, name_or_validator, value, *args, **kwargs):
00018         v = self.validatorFor(name_or_validator)
00019         return v(value, *args, **kwargs)
00020 
00021     __call__ = validate
00022 
00023     def validatorFor(self, name_or_validator):
00024         if type(name_or_validator) in StringTypes:
00025             try:
00026                 return self._validator[name_or_validator]
00027             except KeyError:
00028                 raise UnknowValidatorError, name_or_validator
00029         elif IValidator.isImplementedBy(name_or_validator):
00030             return name_or_validator
00031         else:
00032             raise FalseValidatorError, name_or_validator
00033 
00034     def register(self, validator):
00035         if not IValidator.isImplementedBy(validator):
00036             IValidator.isImplementedBy(validator)
00037             raise FalseValidatorError, validator
00038         name = validator.name
00039         # The following code prevents refreshing
00040         ##if self._validator.has_key(name):
00041         ##    raise AlreadyRegisteredValidatorError, name
00042         self._validator[name] = validator
00043 
00044     def items(self):
00045         return self._validator.items()
00046 
00047     def keys(self):
00048         return [k for k, v in self.items()]
00049 
00050     def values(self):
00051         return [v for k, v in self.items()]
00052 
00053     def unregister(self, name_or_validator):
00054         if type(name_or_validator) is StringType:
00055             name = name_or_validator
00056         elif IValidator.isImplementedBy(name_or_validator):
00057             name = name_or_validator.name
00058         if self._validator.has_key(name):
00059             del self._validator[name]