Skip to content

Repository files navigation

PHPFluent\Filter

Build StatusTotal DownloadsLicenseLatest Stable VersionLatest Unstable Version

Provider a better API to handle Zend filters.

Installation

Package is available on Packagist, you can install it using Composer.

composer require phpfluent/filter

Usage

The static API was inspired on Respect\Validation.

Namespace Import

PHPFluent\Filter is namespaced, but you can make your life easier by importing a single class into your context:

usePHPFluent\Filter\Builderasf;

Calling a filter

f::stringToUpper()->filter('phpfluent'); // returns: 'PHPFLUENT'

Calling multiple filters

f::stringToUpper()
->stringTrim()
->filter('filter '); // returns 'FILTER'

Calling native PHP functions

f::json_encode(JSON_PRETTY_PRINT)
->filter(array('key' => 'value')); // returns: '{"key": "value"}'

Non-static API

You also can simply create an instance of PHPFluent\Filter\Builder.

$builder = newPHPFluent\Filter\Builder();
$builder->ucfirst();
$builder->str_pad(10, '-');
$builder->filter('filter'); // returns: 'Filter----'

Calling Builder class

PHPFluent\Filter\Builder implements __invoke() method, so you can do like:

$builder('filter'); // returns: 'Filter----'

Custom filters

You can use your own Zend filters.

f::myFilter();

For that purpose we provide a way to add your own namespaces/prefixes:

f::getDefaultFactory()->appendPrefix('My\\Filter\\Prefix');

So, in the example above v::myFilter() will call My\Filter\PrefixMyFilter.

You can implement your own filter.

usePHPFluent\Filter\FilterInterface;
class UrlFilter implements FilterInterface
{
publicfunctionfilter($value)
{
returnfilter_var($value, FILTER_SANITIZE_URL);
}
}

Filter factory

To create the filters by its name we use our Factory; there are two ways to change the Factory to be used.

Static calls

$factory = newPHPFluent\Filter\Factory();
$factory->prependPrefix('My\\Zend\\Filters\\');
PHPFluent\Filter\Builder::setDefaultFactory($factory);

In the example above the defined factory will be used for all static calls.

Non-static calls

$factory = newPHPFluent\Filter\Factory();
$factory->prependPrefix('My\\Zend\\Filters\\');
$builder = newPHPFluent\Filter\Builder($factory);

In the example above the defined factory will be used only for the $builder instance variable.

As you could note, the factory instance if optional, so, when you did defined a factory for the builder object it will use the default one, defined on getDefaultFactory().

PHPFluent filters

key()

Allows to perform filters over an array key.

f::key('foo', f::boolean())
->filter(array('foo' => 1, 'baz' => 'Whatever')); // array('foo' => true)

If you're looking for something more specific you should take a look on Zend\InputFilter.

About

A fluent filter library for PHP based on Zend\Filter

Resources

Stars

12 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages