A simple filtering library for PHP

Overview

Filterus - A flexible PHP 5.3 filter package

Filter Methods:

Each filter class has two primary methods:

  • $filter->filter($var) - returns a modified version of $var filtered to the options. If it cannot be safely modified, a default value will be returned.
  • $filter->validate($var) - Returns a boolean identifying if the value is valid.

Simple Filters (with options):

  • alnum - Alpha numeric
    • min - 0 - Minimum length
    • max - PHP_INT_MAX - Maximum length
    • default - '' - Default return value
  • array - Array matching
    • min - 0 - Minimum size
    • maximum - PHP_INT_MAX - Maximum size
    • keys - null - Filter to run on the keys
    • values - null - Filter to run on the values
    • default - array() - Default return value
  • bool - Boolean matching
    • default - null - Default return value
  • email - Matches emails
  • float - Floating point numbers
    • min - null - Minimum length
    • max - null - Maximum length
    • default - 0.0 - Default return value
  • int - Integers numbers
    • min - null - Minimum length
    • max - null - Maximum length
    • default - 0 - Default return value
  • ip - Matches IP addresses
    • ipv4 - true - Boolean to match IPv4 addresses
    • ipv6 - true - Boolean to match IPv6 addresses
    • private - true - Include private addresses?
    • reserved - true - Include reserved addresses?
  • object - Objects
    • class - '' - Required class or interface name
    • default - null - The default value
    • defaultFactory - null - A callback to instantiate a return value
  • raw - Returns whatever is passed in
  • regex - Matches strings via a regex
    • min - 0 - Minimum length
    • max - PHP_INT_MAX - Maximum length
    • default - '' - Default return value
    • regex - /.?/ - The regex to run
  • string - Matches strings
    • min - 0 - Minimum length
    • max - PHP_INT_MAX - Maximum length
    • default - '' - Default return value
  • url - Matches URLs
    • path - false - Force a path to be present
    • query - false - Force a query string to be present

Complex Filters

  • Filter::map(array()) - "maps" several filters over key-value pairs. Useful for filtering associative arrays or stdclass objects.
  • Filter::chain($filter1, $filter2...) - Chains multiple filters together to run on the same value (similar to AND joining filters).
  • Filter::pool($filter1, $filter2...) - Runs the same value through multiple filters using the first valid return (similar to OR joining filters)

Usage:

Simple filters can be specified using a comma-separated-value list. So a filter specifying a string with minimum length of 5 could be represented as:

$filter = Filter::factory('string,min:5');

Or

$filter = new Filters\String(array('min' => 5));

If you pass a filter to Filter::factory(), it will be returned unmodified. So you can write functions like:

function foo($bar, $filter) {
    // do something with $bar and set in $baz
    return Filter::factory($filter)->filter($baz);
}

Complex chaining can also be supported. So if you wanted to check if an array with a minimum size of 4, with numeric keys and containing strings of minimum length 5, that could be built like so:

$filter = Filter::array('min:4', 'int', 'string,min:5');

If we wanted to validate an associative array, we would use a "map" filter:

$array = array(
    'foo' => 2,
    'bar' => 'test',
);

$filter = Filter::map(array(
    'foo' => 'int',
    'bar' => 'string,min:4',
));

var_dump($filter->validate($array)); // true

Procedural Interface

Filterus also ships with a procedural interface for calling filters.

\Filterus\filter($var, $filter);

And

\Filterus\validate($var, $filter);

Any filter is supported (both are basically simple wrappers):

function \Filterus\filter($var, $filter) {
    return \Filterus\Filter::factory($filter)->filter($var);
}

Both are just convenience functions.

Security Vulnerabilities

If you have found a security issue, please contact the author directly at [email protected].

Comments
  • reserved

    reserved "Object" name

    Hi,

    I tried running the unit tests under php7.2.12 and it fails in

    Filterus\Filters\Object

    PHP Fatal error:  Cannot use 'Object' as class name as it is reserved
    

    I am planning to refactor it and submit a pull request, but before I make any changes do you have any ideas on what class name should it be changed to?

    opened by frostbane 1
  • Want some help triaging simple PRs?

    Want some help triaging simple PRs?

    Hi @ircmaxell

    There's some PRs that have languished for a while in this repo. If you are willing to make me a committer, I'd be happy to go through the trivial docs ones, check their validity, and merge them down if they are OK.

    opened by halfer 0
  • Email validation doesn't work on an empty string

    Email validation doesn't work on an empty string

    There isn't an implementation for validate for emails, so although an empty string will be correctly filtered to null, it will validate as true, which is not desirable.

    Repro code:

    $filter = \Filterus\Filter::factory('email');
    
    $result = $filter->filter('');
    var_dump($result); // Returns NULL, correct
    
    $ok = $filter->validate('');
    echo $ok ? 'Passed' : 'Failed'; // Incorrectly returns Passed
    

    A solution for now is to use a chain, like so:

    $filter = \Filterus\Filter::chain('email', 'string,min:1');
    
    $result = $filter->filter('');
    var_dump($result); // Returns NULL, correct
    
    $ok = $filter->validate('');
    echo $ok ? 'Passed' : 'Failed'; // Correctly returns Failed
    
    opened by halfer 0
  • Can I achieve optional keys by using a pool of maps?

    Can I achieve optional keys by using a pool of maps?

    I have a validation requirement where an array can look like either of these:

    [ 'name' => 'string',
      'from_address' => 'email',
      'from_name' => 'string',
      'subject' => 'string',
      'body_plain' => 'string',
      'to_address' => 'email', ] // Differs just in this key
    
    [ 'name' => 'string',
      'from_address' => 'email',
      'from_name' => 'string',
      'subject' => 'string',
      'body_plain' => 'string',
      'to_address_field' => 'string', ] // Differs just in this key
    

    My strategy is that, since there is no way to specify keys as optional, I could run a map for each one, and accept if either returns true. On that basis, I thought I could use a pool as well.

    use Filterus\Filter as F;
    
    $baseValidator = [
        'name' => 'string',
        'from_address' => 'email',
        'from_name' => 'string',
        'subject' => 'string',
        'body_plain' => 'string',
    ];
    
    // Use a pool of maps, should work?
    $eitherValidators = F::pool([
        F::map($baseValidator + ['to_address_field' => 'string', ]),
        F::map($baseValidator + ['to_address' => 'email', ]),
    ]);
    

    However, this blows up in the Filterus internals:

    explode() expects parameter 2 to be string, array given
    
    .../vendor/ircmaxell/filterus/lib/Filterus/Filter.php:98
    .../vendor/ircmaxell/filterus/lib/Filterus/Filter.php:52
    .../vendor/ircmaxell/filterus/lib/Filterus/Filters/Map.php:21
    .../vendor/ircmaxell/filterus/lib/Filterus/Filters/Map.php:45
    

    I'll write a custom validator for now, but would be interested to see how people would solve this.

    opened by halfer 0
  • What's the best way to allow strings to be null?

    What's the best way to allow strings to be null?

    Hi, thanks for providing this library. I have the following solution to allow "string or null", and will provide it below. However, if there is a better way to do this, please let me know.

    First a null validator:

    /**
     * Class to allow nulls
     */
    
    class AllowNull extends \Filterus\Filter
    {
        public function filter($var)
        {
            return $var;
        }
    
        public function validate($var)
        {
            return is_null($var);
        }
    }
    

    Then register like so:

    use Filterus\Filter as F;
    
    F::registerFilter('null', AllowNull::class);
    

    Finally use in a pool:

    $validator = F::pool('string', 'null');
    
    opened by halfer 0
  • Renamed reserved class names to {$classname}Type

    Renamed reserved class names to {$classname}Type

    In PHP7 some classnames are reserved and requires a change. This is discussed in https://github.com/Respect/Validation/issues/362

    Their suggestion is to use the prefix Type on the classes.

    opened by kalaspuffar 0
  • Possible bug? Invalid outcome of validation

    Possible bug? Invalid outcome of validation

    Having an array like

    array(19) {
      'sku' =>
      string(2) "SW"
      '_type' =>
      string(6) "simple"
      '_attribute_set' =>
      string(18) "xxxxx"
      '_product_websites' =>
      string(10) "xxxxx"
      'name' =>
      NULL
      'description' =>
      string(8) "TESTTEST"
      'short_description' =>
      string(8) "TESTTEST"
      'price' =>
      int(0)
      'url_key' =>
      NULL
      'cost' =>
      NULL
      'status' =>
      int(1)
      'visibility' =>
      int(4)
      'manufacturer' =>
      string(9) "xxxx"
      'tax_class_id' =>
      int(2)
      'base_price_unit' =>
      string(3) "PCS"
      'base_price_base_unit' =>
      string(3) "PCS"
      'country_of_manufacture' =>
      string(11) "xxxxx"
      'qty' =>
      int(0)
      'is_in_stock' =>
      int(1)
    }
    

    And with this filter:

    $filter = Filter::map(array(
                    'name'              => 'string,min:1', //anything above 1 should do
                    'sku'               => 'string,min:3', //prefix is hardcoded, so anything above strlen 2 will do
                    '_attribute_set'    => 'string,min:1', //TODO Should be hardcoded to whatever is in $conf
                    '_product_websites' => 'string,min:1',
                    '_type'             => 'string,min:1', //TODO Either configurable or simple
                ));
    

    I would suspect that $filter->validate($product) would throw back false since "name" is clearly a) not a string and b) is not having a stringlengh of atleast 1.

    But I do get true as a result, which is false.

    opened by pquerner 8
Owner
Anthony Ferrara
Anthony Ferrara
Library that offers Input Filtering based on Annotations for use with Objects. Check out 2.dev for 2.0 pre-release.

DMS Filter Component This library provides a service that can be used to filter object values based on annotations Install Use composer to add DMS\Fil

Rafael Dohms 89 Nov 28, 2022
Valitron is a simple, elegant, stand-alone validation library with NO dependencies

Valitron: Easy Validation That Doesn't Suck Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron us

Vance Lucas 1.5k Dec 30, 2022
PHP library for ArCaptcha. This package supports PHP 7.3+.

PHP ArCaptcha Library PHP library for ArCaptcha. This package supports PHP 7.3+. List of contents PHP ArCaptcha Library List of contents Installation

Mohammad Abbasi 10 Aug 12, 2022
PHP library - Validators for standards from ISO, International Finance, Public Administrations, GS1, Manufacturing Industry, Phone numbers & Zipcodes for many countries

IsoCodes PHP library - Validators for standards from ISO, International Finance, Public Administrations, GS1, Book Industry, Phone numbers & Zipcodes

Ronan Guilloux 767 Jan 2, 2023
PHP library to validate and convert ISBNs and EANs

biblys/isbn biblys/isbn can be used to: validate a string against the ISBN-10, ISBN-13 and EAN-13 formats convert an ISBN to ISBN-10, ISBN-13, EAN-13

Biblys 48 Apr 10, 2022
PHP library to validate and format license plate numbers.

License plate validator and formatter CI Status Lint Coverage Tests This library can be used to validate and format license plate numbers. Countries s

Automex.website 1 Oct 19, 2022
PHP Email address validator - A library for validating emails against several RFC.

EmailValidator A library for validating emails against several RFC. Supported RFCs This library aims to support RFCs: 5321, 5322, 6530, 6531, 6532, 10

Eduardo Gulias Davis 10.7k Jun 13, 2022
FyreValidation is a free, open-source validation library for PHP.

FyreValidation FyreValidation is a free, validation library for PHP. Table Of Contents Installation Validators Rules Error Messages Installation Using

Elusive 0 Jan 15, 2022
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
Light and extendable schema validation library

Light PHP validation library For everyone who uses MongoDB or other NoSQL solution and cares about what client sends to his/her database and looking f

Alexander Serkin 43 Sep 28, 2022
An extensible validation library for your data with sane defaults.

Hird Hirds, also known as housecarls, was a gathering of hirdmen, who functioned as the king's personal guards during the viking age and the early mid

Asko Nõmm 13 Apr 23, 2022
A re-write of rakit/validation, a standalone validation library inspired by Laravel Validation

Somnambulist Validation This is a re-write of rakit/validation, a standalone validator like Laravel Validation. In keeping with rakit/validation, this

Somnambulist Tech 18 Dec 14, 2022
A simple package to validate against common passwords and help keep your application secure.

common-passwords A simple package to validate against common passwords and help keep your application secure. composer require crumbls/common-password

Crumbls 4 Oct 16, 2021
php binding for IUP toolkit

php-iup php-ffi experiment php7.4 interface to the IUP toolkit for building GUI's. Description IUP-Toolkit IUP is a multi-platform toolkit for buildin

Shubham Chaudhary 20 Nov 13, 2022
A PHP package for validating/generating/formatting an IRS document number (CPF/CNPJ)

A PHP package for validating/generating/formatting an IRS document number (CPF/CNPJ)

null 7 Dec 15, 2022
Modern PHP validator on steroids for validating forms and/or array's.

Modern PHP Validator - Standalone Validation on Steroids Introduction Head first example Installation Adding fields for validation Execute validation

Kris Kuiper 5 Oct 5, 2022
A simple filtering library for PHP

Filterus - A flexible PHP 5.3 filter package Filter Methods: Each filter class has two primary methods: $filter->filter($var) - returns a modified ver

Anthony Ferrara 451 Dec 27, 2022
A simple and modern approach to stream filtering in PHP

clue/stream-filter A simple and modern approach to stream filtering in PHP Table of contents Why? Support us Usage append() prepend() fun() remove() I

Christian Lück 1.5k Dec 29, 2022
Library that offers Input Filtering based on Annotations for use with Objects. Check out 2.dev for 2.0 pre-release.

DMS Filter Component This library provides a service that can be used to filter object values based on annotations Install Use composer to add DMS\Fil

Rafael Dohms 89 Nov 28, 2022
Library that offers Input Filtering based on Annotations for use with Objects. Check out 2.dev for 2.0 pre-release.

DMS Filter Component This library provides a service that can be used to filter object values based on annotations Install Use composer to add DMS\Fil

Rafael Dohms 89 Nov 28, 2022