From da57ccf8dea668f456d663f2fdf8e10ecd27aef9 Mon Sep 17 00:00:00 2001 From: Ben Roberts Date: Mon, 26 Dec 2011 00:52:10 +0000 Subject: [PATCH] Added first attempt at input validation framework --- .../lib/SihnonFramework/Exceptions.class.php | 3 + .../lib/SihnonFramework/Validation.class.php | 9 +++ .../SihnonFramework/Validation/Text.class.php | 55 +++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 source/lib/SihnonFramework/Validation.class.php create mode 100644 source/lib/SihnonFramework/Validation/Text.class.php diff --git a/source/lib/SihnonFramework/Exceptions.class.php b/source/lib/SihnonFramework/Exceptions.class.php index 0d90461..f7bfa87 100644 --- a/source/lib/SihnonFramework/Exceptions.class.php +++ b/source/lib/SihnonFramework/Exceptions.class.php @@ -44,5 +44,8 @@ class SihnonFramework_Exception_AuthException extends SihnonFramework_E class SihnonFramework_Exception_UnknownUser extends SihnonFramework_Exception_AuthException {}; class SihnonFramework_Exception_IncorrectPassword extends SihnonFramework_Exception_AuthException {}; +class SihnonFramework_Exception_ValidationException extends SihnonFramework_Exception {}; +class SihnonFramework_Exception_InvalidContent extends SihnonFramework_ValidationException {}; +class SihnonFramework_Exception_InvalidLength extends SihnonFramework_ValidationoException {}; ?> diff --git a/source/lib/SihnonFramework/Validation.class.php b/source/lib/SihnonFramework/Validation.class.php new file mode 100644 index 0000000..f9ac15f --- /dev/null +++ b/source/lib/SihnonFramework/Validation.class.php @@ -0,0 +1,9 @@ + \ No newline at end of file diff --git a/source/lib/SihnonFramework/Validation/Text.class.php b/source/lib/SihnonFramework/Validation/Text.class.php new file mode 100644 index 0000000..a906505 --- /dev/null +++ b/source/lib/SihnonFramework/Validation/Text.class.php @@ -0,0 +1,55 @@ + ':alpha:', + static::Digit => ':digit:', + static::Numeric => ':digit:\.-', + static::Symbol => ':punct:', + static::Whitespace => ':space:', + ); + + public static function charset($input, $charset = static::Defaults) { + static::pattern($input, static::buildCharsetPattern($charset)); + } + + public static function length($input, $min_length = null, $max_length = null) { + $length = strlen($input); + + if ($min_length !== null && $length < $min_length) { + throw new SihnonFramework_Exception_InvalidLength(); + } + + if ($max_length !== null && $length > $max_length) { + throw new SihnonFramework_Exception_InvalidLength(); + } + } + + public static function pattern($input, $pattern) { + if ( ! preg_match($pattern, $input)) { + throw new SihnonFramework_Exception_InvalidContent(); + } + } + + protected static function buildCharsetPattern($charset) { + $classes = ''; + foreach (static::$charsets as $set => $class) { + if ($charset & $set) { + $classes .= $class; + } + } + + return "/^[{$classes}]*$/"; + } + +} + +?> \ No newline at end of file