Validate and sanitize arrays and objects.

Overview

Aura.Filter

This package provides tools to validate and sanitize objects and arrays.

Foreword

Installation

This library requires PHP 5.4 or later; we recommend using the latest available version of PHP as a matter of principle. It has no userland dependencies.

It is installable and autoloadable via Composer as aura/filter.

Alternatively, download a release or clone this repository, then require or include its autoload.php file.

Quality

Scrutinizer Code Quality Code Coverage Build Status

To run the unit tests at the command line, issue composer install and then ./vendor/bin/phpunit at the package root. This requires Composer to be available as composer.

This library attempts to comply with PSR-1, PSR-2, and PSR-4. If you notice compliance oversights, please send a patch via pull request.

Community

To ask questions, provide feedback, or otherwise communicate with the Aura community, please join our Google Group, follow @auraphp on Twitter, or chat with us on #auraphp on Freenode.

Documentation

This package is fully documented here.

Comments
  • Multibyte strings, various problems with the lack thereof

    Multibyte strings, various problems with the lack thereof

    I was looking at the code and found that currently the non-mb string functions are being used: ex:

    Aura\Filter\Rule\Sanitize\Strlen
    
    if (strlen($value) < $len) {
         $subject->$field = str_pad($value, $len, $pad_string, $pad_type);
    }
    if (strlen($value) > $len) {
         $subject->$field = substr($value, 0, $len);
    }
    

    Here we have strlen, substr and str_pad which are non-mb safe. Which will result in various problems:

    Ex. take a cyrillic script string's length - strlen("тесттест") = 16 instead of 8, so our validation will fail if we ask for strings of less than 15 characters.

    An even bigger issue will ensue with the substr which may cut a unicode character in half(offtopic: slashing symbols sounds funny though) - we will get a random ascii character.

    Shouldn't we instead switch to the mb functions?

    opened by mivanov93 37
  • can't use validate rule 'blank' at

    can't use validate rule 'blank' at "2.0.0"

    Hi, my name is Satomi. I'm using aurafilter, but upon doing composer update, I updated from "2.0.0-beta2" to "2.0.0", and it seems like the "blank" validation rule went away. I'm getting this error: Aura\Filter\Exception\RuleNotMapped: blank. Did the name of this validation rule change? Thank very much!

    enhancement question v2 
    opened by satomif 35
  • Removed Translator and various other improvements and corrections for version 2 of the component framework

    Removed Translator and various other improvements and corrections for version 2 of the component framework

    | Q | A | | --- | --- | | Bug Fix? | yes | | New Feature? | yes | | BC Breaks? | expected | | Deprecations? | translator related | | Tests Pass? | yes | | Fixed Tickets | none | | License | Aura/MIT | | Doc PR | no |

    Sent using Gush

    Description

    This PR was started after today's conversation on IRC, we synced with Hari and Paul to remove translator as a dependency from this component. There were some additional cleanups, moving to PSR-4, updating the readme, making the tests pass, correcting some typos on the tests, adding an autoload.php, creating a factory for the service instantiation and registry initialization and some other minor issues.

    todo:

    • [x] update README.md with new structure
    opened by cordoval 34
  • Email validation

    Email validation

    Currently, it's acceptable to have numbers in the top level domain. Which should only be used for internationalized domains(starting with xn-- as stated in https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

    Ex. [email protected] should be invalid, but it's not.

    Com1 doesn't start with xn and is not an internationalized domain either.

    It's okay to be able to use an IP instead of a domain name(ex. [email protected]), but not a mix of both.

    Also, as far as I know domains must be at least 2 symbols long(did a search). Hence: [email protected] should be invalid as well.

    Another thing is - what about strong email validation using https://secure.php.net/manual/en/function.checkdnsrr.php

    Since it makes a network call, maybe it should be in another rule, EmailMX or something.

    opened by mivanov93 25
  • Validation arguments should be constants

    Validation arguments should be constants

    We are currently allowing users to validate by using a string value to indicate the validator they wish to use:

    $filter->validate('credit_card')->is('creditCard');
    

    For built-in validators, we should instead use constants:

    $filter->validate('credit_card')->is(Filter::CREDIT_CARD);
    
    opened by brandonsavage 23
  • How to get the tokens

    How to get the tokens

    When working with Aura.Intl how could we get the tokens that need to be passed .

    Eg :

    "FILTER_RULE_FAILURE_IS_NOT_BETWEEN" => "Please do not use a value between {min} and {max}.",
    

    The min and max , may be something like getTokens() on the RuleCollection::addMessageFromRule will help ?

    array(
        'min' => $min,
        'max' => $max,
    );
    

    / cc @cordoval

    v2 
    opened by harikt 13
  • Wishlist

    Wishlist

    One thing I like in v2 is usage of

    $email = new Aura\Filter\Email('[email protected]');
    $email->isValid();
    

    like interface. I am not sure whether this is possible currently.

    But just a wishlist . The idea is usage of filters in DDD as Mathias Verras mentioned in some slides. So we don't need to inject anything to factory or use it.

    opened by harikt 13
  • Add Character Case Rules

    Add Character Case Rules

    Adds Filter/Sanitize for:

    • caseUpper : strtoupper,
    • caseLower : strtolower,
    • caseTitle : ucwords,
    • caseLowerFirst : lcfirst,
    • caseUpperFirst : ucfirst.

    All use mbstring if available.

    The 'first' rules are a little odd because I think you gotta do that since there's no mb_ucfirst or mb_lcfirst.

    opened by jakejohns 11
  • Filtering a missing field

    Filtering a missing field

    Bugfix for missing properties(current version has no checks for such) + a new method for instead of Blank, just Null since sometimes we'd rather treat null and '' as two distinct things.

    opened by mivanov93 11
  • custom rules not applying when field is blank

    custom rules not applying when field is blank

    Hello @pmjones I was trying to make 'required-if' rule, where the field would be required only in some conditions, but because of the fact that rules are not called to blank fields there is no workaround about this issue.

    Thanks for help George

    bug 
    opened by php- 10
  • dev branch isNotBlank not working as expected

    dev branch isNotBlank not working as expected

    My expectation is that isNotBlank would give me an error message if the passed in field was blank.

    When I pass a field in that has a value, this validation returns an error.

    opened by designermonkey 10
  • Fix Subfilter support

    Fix Subfilter support

    Related to https://github.com/auraphp/Aura.Filter/issues/155 .

    Support maximum of 2.

    <?php
    require __DIR__ . '/vendor/autoload.php';
    $filter_factory = new \Aura\Filter\FilterFactory();
    $filter = $filter_factory->newSubjectFilter();
    
    $filter->validate('id')->is('int');
    $filter->validate('url')->is('url');
    
    $user_spec = $filter->subfilter('user'); // add a "SubSpec"
    $user_filter = $user_spec->filter();  // Get the "SubSpec" SubjectFilter
    
    $user_filter->validate('given-name')->isNotBlank();
    $user_filter->validate('age')->is('int');
    $user_filter->validate('gender')->is('strlen', 1);
    
    $data = (object) [];
    
    $result = $filter->apply($data);
    $messages = $filter->getFailures()->getMessages();
    
    var_dump($messages);
    

    RESULT :

    array(3) {
      ["id"]=>
      array(1) {
        [0]=>
        string(31) "id should have validated as int"
      }
      ["url"]=>
      array(1) {
        [0]=>
        string(32) "url should have validated as url"
      }
      ["user"]=>
      array(3) {
        ["given-name"]=>
        array(1) {
          [0]=>
          string(37) "given-name should not have been blank"
        }
        ["age"]=>
        array(1) {
          [0]=>
          string(32) "age should have validated as int"
        }
        ["gender"]=>
        array(1) {
          [0]=>
          string(41) "gender should have validated as strlen(1)"
        }
      }
    }
    
    opened by harikt 2
  • 4.x :: Multidimensional support and failures

    4.x :: Multidimensional support and failures

    This is related to https://github.com/auraphp/Aura.Filter/issues/117 .

    As we add type definition like

    public function add(string $field, string $message, array $args = array()): FailureInterface
    

    The message is no longer a string, it can become an array when it is using subfilter .

    @pmjones have forseen this

    things are going to be difficult and ugly

    I am still checking whether there is a way.

    opened by harikt 0
Releases(2.3.1)
  • 2.3.1(Apr 20, 2017)

    • (DOC) Update the documentation 128, 129
    • (FIX) PHP Notice when trying to sanitize a string to integer 132
    • (ADD) 'phpunit/phpunit' as require-dev dependency in composer.json .
    • (ADD) Added CHANGELOG.md file.
    • (REMOVE) Removed CHANGES.md file.
    Source code(tar.gz)
    Source code(zip)
  • 2.3.0(Oct 3, 2016)

    • (ADD) Implement JsonSerializable in the Failure class
    • (DOC) Update the documentation
    • (FIX) Removed undefined but registered sanitizers from SanitizerLocator
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Mar 23, 2016)

    This release adds new validation and sanitizing rules:

    • lowerCase for all-lower-case values
    • upperCase for all-upper-case values
    • titleCase for title-cased values
    • lowerCaseFirst for values where the first character is lower-case
    • upperCaseFirst for values where the first character is upper-case
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Mar 4, 2016)

  • 2.0.0(Feb 20, 2016)

  • 2.0.0-beta3(Jan 27, 2016)

    Third beta release.

    • (BRK) Due to new blank-checking in ValidateSpec::applyRule(), remove 'blank' validation rule, and add 'isBlank()' validation spec method.
    • (FIX) Filter arguments using arrays, resources, and objects (including closures) no longer cause errors when creating the default filter message.
    • (ADD) Validation now fails on missing (unset or null) fields.
    • (DOC) Update documentation.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-beta2(Oct 13, 2015)

    Second beta release.

    • (ADD) Add UTF-8 support in Alpha, Alnum, Strlen*, and Word filters with help from @mivanov93.
      • All string-length filters are now multi-byte aware using either mbstring or iconv extensions.
      • In alnum and alpha rules, use unicode letters and digits instead of ctype.
      • In word rules, use unicode letters and digits instead of \w and \W.
    • (ADD) More robust email validation based on is_email() from @dominicsayers, plus IDN support as suggested by @dg via the intl extension.
    • (TEST) Update Travis-CI config to use containers.
    • (DOCS) Update relevant documentation.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-beta1(Jul 6, 2015)

    First 2.0 beta release.

    • BREAK: Renamed class Filter to SubjectFilter.
    • BREAK: Removed method SubjectFilter::strict() and all "strict" behavior, as get_object_vars() is not guaranteed in some objects (e.g. magic get/set vs public properties)
    • BREAK: Replaced method SubjectFilter::getMessages() et al with getFailures(); failures are now reported as a FailureCollection instead of as an array of text messages.
    • BREAK: Removed classes Rule\Validate\Ipv4 and Ipv6 in favor of allowing flags on Rule\Validate\Ip.
    • BREAK: Removed class Rule\Validate\InTableColumn entirely, as it requires a PDO connection. This is better implemented as part of a group of database-related filters, rather than as a special case herein.
    • BREAK: Moved namespace Rule\Locator to Locator.
    • BREAK: Renamed class Spec\AbstractSpec to Spec\Spec.
    • BREAK: Removed method Spec\Spec::getFailureMode().
    • BREAK: Moved constants from SubjectFilter to Spec\Spec.
    • BREAK: Removed methods ValueFilter::assert() and setExceptionClass().
    • ADD: Class FilterFactory now takes two constructor params, $validate_factories and $sanitize_factories, to allow injection of rule factories at construction time.
    • ADD: Class AbstractStaticFilter to allow users to create static value filters.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-alpha1(Jul 2, 2015)

Owner
Aura for PHP
High-quality, well-tested, standards-compliant, decoupled libraries that can be used in any codebase.
Aura for PHP
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
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 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
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
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Dec 27, 2022
Abstracts HTTP request input handling, providing an easy interface for data hydration and validation

Linio Input Linio Input is yet another component of the Linio Framework. It aims to abstract HTTP request input handling, allowing a seamless integrat

Linio 41 Dec 12, 2021
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
Improved abstraction for dealing with union and named types.

Check whether a reflection type or method accepts a given input

Spatie 26 Dec 26, 2022
Validation rules for Money and Currency

money-validation-laravel Validation rules for Money and Currency Installation composer require brokeyourbike/money-validation-laravel Usage Package us

Ivan Stasiuk 1 Oct 25, 2021
Argentinian CUIT and CUIL Validator

CUIT/CUIL Validator Argentinian CUIT and CUIL Rules for laravel validation Installation $ composer require iutrace/laravel-cuit-validator Usage Exampl

iutrace 6 Sep 20, 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
This package provides tools to validate and sanitize objects and arrays.

Aura.Filter This package provides tools to validate and sanitize objects and arrays. Foreword Installation This library requires PHP 7.2 or later; we

Aura for PHP 153 Jan 2, 2023
Dobren Dragojević 6 Jun 11, 2023
PHP functions that help you validate structure of complex nested PHP arrays.

PHP functions that help you validate structure of complex nested PHP arrays.

cd rubin 7 May 22, 2022
An Hydrator class that can be used for filling object from array and extracting data from objects back to arrays.

Hydrator namespace: Meow\Hydrator Library that can hydrate (fill object with data from array) and extract data from object back to array. Installation

Meow 2 Feb 3, 2022
Safely break down arrays or objects, and put them back together in new shapes.

traverse/reshape traverse() and reshape() are companion functions that safely break down arrays or objects and put them back together in new shapes. t

Alley Interactive 2 Aug 4, 2022
PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

?? Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Zeeshan Ahmad 20 Dec 8, 2018
Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Super Simple DTO Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Mohammed Manssour 8 Jun 8, 2023
Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.DeepEqual().

Deeper Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.De

Joubert RedRat 4 Feb 12, 2022