Coder Social home page Coder Social logo

sanitizer's Introduction

WAAVI Sanitizer

Latest Version on Packagist Software License Build Status Total Downloads

About WAAVI

WAAVI is a Spanish web development and product consulting agency, working with Startups and other online businesses since 2013. Need to get work done in Laravel or PHP? Contact us through waavi.com.

Introduction

WAAVI Sanitizer provides an easy way to format user input, both through the provided filters or through custom ones that can easily be added to the sanitizer library.

Although not limited to Laravel 5 users, there are some extensions provided for this framework, like a way to easily Sanitize user input through a custom FormRequest and easier extensibility.

Example

Given a data array with the following format:

    $data = [
        'first_name'    =>  'john',
        'last_name'     =>  '<strong>DOE</strong>',
        'email'         =>  '  [email protected]',
        'birthdate'     =>  '06/25/1980',
        'jsonVar'       =>  '{"name":"value"}',
        'description'   =>  '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>',
        'phone'         =>  '+08(096)90-123-45q',
        'country'       =>  'GB',
        'postcode'      =>  'ab12 3de',
    ];

We can easily format it using our Sanitizer and the some of Sanitizer's default filters:

    use \Waavi\Sanitizer\Sanitizer;

    $filters = [
        'first_name'    =>  'trim|escape|capitalize',
        'last_name'     =>  'trim|escape|capitalize',
        'email'         =>  'trim|escape|lowercase',
        'birthdate'     =>  'trim|format_date:m/d/Y, Y-m-d',
        'jsonVar'       =>  'cast:array',
        'description'   =>  'strip_tags',
        'phone'         =>  'digit',
        'country'       =>  'trim|escape|capitalize',
        'postcode'      =>  'trim|escape|uppercase|filter_if:country,GB',
    ];

    $sanitizer  = new Sanitizer($data, $filters);
    var_dump($sanitizer->sanitize());

Which will yield:

    [
        'first_name'    =>  'John',
        'last_name'     =>  'Doe',
        'email'         =>  '[email protected]',
        'birthdate'     =>  '1980-06-25',
        'jsonVar'       =>  '["name" => "value"]',
        'description'   =>  'Test paragraph. Other text',
        'phone'         =>  '080969012345',
        'country'       =>  'GB',
        'postcode'      =>  'AB12 3DE',
    ];

It's usage is very similar to Laravel's Validator module, for those who are already familiar with it, although Laravel is not required to use this library.

Filters are applied in the same order they're defined in the $filters array. For each attribute, filters are separered by | and options are specified by suffixing a comma separated list of arguments (see format_date).

Available filters

The following filters are available out of the box:

Filter Description
trim Trims a string
escape Escapes HTML and special chars using php's filter_var
lowercase Converts the given string to all lowercase
uppercase Converts the given string to all uppercase
capitalize Capitalize a string
cast Casts a variable into the given type. Options are: integer, float, string, boolean, object, array and Laravel Collection.
format_date Always takes two arguments, the date's given format and the target format, following DateTime notation.
strip_tags Strip HTML and PHP tags using php's strip_tags
digit Get only digit characters from the string
filter_if Applies filters if an attribute exactly matches value

Adding custom filters

You can add your own filters by passing a custom filter array to the Sanitize constructor as the third parameter. For each filter name, either a closure or a full classpath to a Class implementing the Waavi\Sanitizer\Contracts\Filter interface must be provided. Closures must always accept two parameters: $value and an $options array:

    class RemoveStringsFilter implements Waavi\Sanitizer\Contracts\Filter
    {
        public function apply($value, $options = [])
        {
            return str_replace($options, '', $value);
        }
    }

    $customFilters = [
        'hash'   =>  function($value, $options = []) {
                return sha1($value);
            },
        'remove_strings' => RemoveStringsFilter::class,
    ];

    $filters = [
        'secret'    =>  'hash',
        'text'      =>  'remove_strings:Curse,Words,Galore',
    ];

    $sanitize = new Sanitize($data, $filters, $customFilters);

Install

To install, just run:

composer require waavi/sanitizer ~1.0

And you're done! If you're using Laravel, in order to be able to access some extra functionality you must register both the Service provider in the providers array in config/app.php, as well as the Sanitizer Facade:

    'providers' => [
        ...
        Waavi\Sanitizer\Laravel\SanitizerServiceProvider::class,
    ];

    'aliases' => [
        ...
        'Sanitizer' => Waavi\Sanitizer\Laravel\Facade::class,
    ];

Laravel goodies

If you are using Laravel, you can use the Sanitizer through the Facade:

    $newData = \Sanitizer::make($data, $filters)->sanitize();

You can also easily extend the Sanitizer library by adding your own custom filters, just like you would the Validator library in Laravel, by calling extend from a ServiceProvider like so:

    \Sanitizer::extend($filterName, $closureOrClassPath);

You may also Sanitize input in your own FormRequests by using the SanitizesInput trait, and adding a filters method that returns the filters that you want applied to the input.

    namespace App\Http\Requests;

    use App\Http\Requests\Request;
    use Waavi\Sanitizer\Laravel\SanitizesInput;

    class SanitizedRequest extends Request
    {
        use SanitizesInput;

        public function filters()
        {
            return [
                'name'  => 'trim|capitalize',
                'email' => 'trim',
                'text'  => 'remove_strings:Curse,Words,Galore',
            ];
        }

        public function customFilters()
        {
            return [
                'remove_strings' => RemoveStringsFilter::class,
            ];
        }

        /* ... */

To generate a Sanitized Request just execute the included Artisan command:

php artisan make:sanitized-request TestSanitizedRequest

The only difference with a Laravel FormRequest is that now you'll have an extra 'fields' method in which to enter the input filters you wish to apply, and that input will be sanitized before being validated.

License

WAAVI Sanitizer is open-sourced software licensed under the MIT license

sanitizer's People

Contributors

alariva avatar fomvasss avatar francoism90 avatar grpaiva avatar jijoel avatar lasserafn avatar mozammil avatar norbybaru avatar sharifzadesina avatar shekharkhatri avatar sildraug avatar smknstd avatar spodnet avatar tiagosilvapereira avatar tlapi avatar zarianec avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sanitizer's Issues

ErrorException Illegal string offset 'name'

ErrorException
Illegal string offset 'name'

Screenshot_1

I am not sure if someone checked properly before merging to the master branch. Even the Travis also failing that latest change. Developers should have tested the breakdown issues before merging the commit.

Also, there should have some changelog information if any new options were added or removed.

I do not get the filtered data back when validation succeeds.

Found this package yesterday and tried to use the example as shown in the readme.

Now I am running into a problem.
When validation succeeds I still get the raw data from the input fields ( not filtered ).

Not sure if this is intentional but it was not what I expected.
I managed to solve this by creating a private function in the form request where I call the sanitizer myself. ( and merge the result of the sanitizer over the request that is coming in ).

Using laravel 5.6.*

Question: It is possible to use custom filters when using SanitizesInput on my FormRequest?

Hello. it is possible to do this?

This is my Request class:

`namespace App\Http\Requests\API;

use App\Models\Concept;
use InfyOm\Generator\Request\APIRequest;
use Waavi\Sanitizer\Laravel\SanitizesInput;

class CreateConceptAPIRequest extends APIRequest
{
use SanitizesInput;

public function filters() {
    return [
        'name'  => 'trim|strip_tags|escape|lowercase',
    ];
}
/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}
/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return Concept::$rules;
}

}`

Add a filter for sometimes rules

I think is interesting add a filter to check "sometimes" laravel rule and just apply the filter if the field isset, because this way if field is not set raise the error that the field is required.

No filter found by the name of digit

Installing Sanitizer via composer [composer require waavi/sanitizer ~1.0 --dev] or [composer require waavi/sanitizer --dev] the Digit class is not included.

I can include it manually but it beats the purpose! :)

Question: How to convert from UTF-8 general_ci ?

I'm using with Laravel

$filters = [
                'company_name_en' => 'trim|escape|capitalize',
                'company_name_kh' => 'trim|escape|capitalize',
            ];

            $sanitizer  = new Sanitizer($input, $filters);
            $input = $sanitizer->sanitize();

When i'm dd($input); it not show text that i'm input. It show like this
company_name_en => "Ážÿáÿšáž¸ážÿáÿšáž¸"

I'm try many way. But still not work.
Thanks for your answer.

Sanitizing arrays

Great Idea! It would be nice to add ability to sanitize arrays the way Laravel validator does it, with rules like 'array.*.key' => 'trim|capitalize', so it will go through array and sanitize each item.

filter_if: Option?

Laravel validation has a required_if:field,value... Is there any option like that for the filters?

(The use case here has to do with postal codes. I want to run a custom ZIP validator I wrote only if the country = 'USA', but I can't think of a way to do this.

If there is no option for something like this, is there a way to pass another field to a custom filter? Then I could pass the country and just do an if there...

Usage in FormRequest

I can not get the filter to work in the FormRequest. I must be missing something.

Added

use Waavi\Sanitizer\Laravel\SanitizesInput;

and

use SanitizesInput; 

And simple function

public function filters() {
    return [
      'name'  => 'trim|strip_tags|escape|uppercase',
      'headline'  => 'trim|strip_tags|escape|uppercase',
    ];
  }

Any input in the form for these fields remains untouched.

Must be something missing.

Update in packagist

Please update the package in Packagist the latest release is not available.

Sanitize for all item in array

Hi
I want to define filter which given array and sanitize all item in array ('*' => 'trim|escape|capitalize').
Please guide me
Thanks,

FormRequest SanitizesInput trait adds attribute when they are not present

The sanitizer applies the filter on inputs even if they are not present in the request which breaks the validation logic. There can be a workaround but I think the default behavior should be only applying filters on the present attributes and maybe add an extra filter that fills the nonexistent attributes if needed (e.g. defaul:{value})

Why use empty instead of is_null?

I think that would be better to use is_null to verify if the input is "empty" on the applyField method.

Like this:

    /**
     *  Apply the given filter by its name
     *  @param  $name
     *  @return Filter
     */
    protected function applyFilter($name, $value, $options = [])
    {
        // If the filter does not exist, throw an Exception:
        if (!isset($this->filters[$name])) {
            throw new InvalidArgumentException("No filter found by the name of $name");
        }
        // If the given value is null, skip the sanitizer
        if (is_null($value)) {
            return $value;
        }
        $filter = $this->filters[$name];
        if ($filter instanceof Closure) {
            return call_user_func_array($filter, [$value, $options]);
        } else {
            $filter = new $filter;
            return $filter->apply($value, $options);
        }
    }

I want use a filter that trim empty fields to null instead of leaving just an empty string.

If you accept it I can make a pull request with the feature.

I really like the package and would be very nice to contribute with you guys! There are some features that you need some help to implement? I have some in mind...

Using the Trait wont work when using request('input_name')

I am using the trait on one of my requests but noticed that the input remains untouched when using request('input_name');.

Lets say the input is "<h1>Hi there</h1>" and the filter is strip_tags.

public function update(CreateReviewRequest $request)
{
        $message = request('message');
}

$message = "<h1>Hi there</h1>"

public function update(CreateReviewRequest $request)
{
        $message = $request->get('message');
}

$message = "Hi there"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.