Provider a better API to handle Zend filters.
Package is available on Packagist, you can install it using Composer.
composer require phpfluent/filter
The static API was inspired on Respect\Validation.
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;
f::stringToUpper()->filter('phpfluent'); // returns: 'PHPFLUENT'
f::stringToUpper()
->stringTrim()
->filter('filter '); // returns 'FILTER'
f::json_encode(JSON_PRETTY_PRINT)
->filter(array('key' => 'value')); // returns: '{"key": "value"}'
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----'
PHPFluent\Filter\Builder
implements __invoke()
method, so you can do like:
$builder('filter'); // returns: 'Filter----'
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);
}
}
To create the filters by its name we use our Factory; there are two ways to change the Factory to be used.
$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.
$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()
.
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.