📜 ⬆️ ⬇️

Filtering input for PHP

I want to share my thoughts on the organization of input filtering (php).

The first thought is the development of wrapper classes String, Integer, Float, Array for standard types. These classes are designed for more convenient work with strings, arrays, etc., as well as for their use in input data filters.

For example:
function test ( TFloat $a , TInteger $b ) {
}

//
test ( new TFloat( $_POST [ 'price' ]), new TInteger ( $_POST [ 'count' ]) );

Classes TFloat, TInteger in constructors perform some type conversion operations. TFloat, for example, replaces the character "," with ".", TFloat and TInteger also delete all non-digital characters (TFloat leaves e + -).

But it is difficult to get along with the “base” classes, because in different cases additional restrictions may be imposed on the same type of TInteger - for example, “minimum (0)”, “range (2.10)”, “maximum (5)”. For TString, “minimum length (5)”, “regexp (/.../)”, etc.
')
Therefore, the second thought was the additional functions-filters for each of the basic types.

For example:
TString:
- min #
- max #
- range # (min, max)
- match #

The filter should return true | false, so you can build a validation logic. Using filters you can also construct your own types.

For example:
Login :
TString :
#
# ""
- trim, toLowerCase
#
# ( !),
# ?
# error(some text) -
- ! match(/[a-z0-9_]/i) ? error( az, 0-9, _)

Password :
TString :
# /
- ! min(5) ? error( 5 )
- ! match(/[a-z0-9_]/i) ? error( az, 0-9, _)

Email :
TString :
- trim, toLowerCase
- ! match(/e-mail-regexp/) ? error(E-mail )

Further, the code uses new types (classes should be generated automatically, based on the configuration described above, and loaded via the autoload mechanism):
<br/> function register( Login $login , Password $password , Password $confirm_password , Email $email ) {
<br/>}

But in this case, additional checks are necessary - for example, $ password and $ confirm_password should be identical.
Therefore additional descriptions are needed for the function itself:
User : #
register : #
params : #
login :
type : Login
filters :
- empty ? error( )
# callback -
# , true|false
- ! callback(User->isLoginUnique($login)) ? error( , )

password :
type : Password
filters :
- empty ? error( )
# eq
# post.confirm_password - POST,
# get.confirm_password - GET - /path?confirm_password=123
- ! eq(post.confirm_password) ? error( "" " " )

confirm_password :
type : Password
filters :
- empty ? error( o)

All configuration syntax is Yaml. I also do not consider it a particularly successful way of describing filters, etc., but this is not so important, your thoughts on what is written are interesting.

Constructive comments and criticism are welcome ...

Source: https://habr.com/ru/post/52390/


All Articles