phpfluent/filter

0.3.0 2015-04-14 22:09 UTC

This package is auto-updated.

Last update: 2024-12-09 15:52:56 UTC


README

Build Status Total Downloads License Latest Stable Version Latest 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:

use PHPFluent\Filter\Builder as f;

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 = new PHPFluent\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.

use PHPFluent\Filter\FilterInterface;

class UrlFilter implements FilterInterface
{
    public function filter($value)
    {
        return filter_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 = new PHPFluent\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 = new PHPFluent\Filter\Factory();
$factory->prependPrefix('My\\Zend\\Filters\\');

$builder = new PHPFluent\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.