Coder Social home page Coder Social logo

sanitizer's Introduction

sanitizer

GitHub release (latest by date) GitHub Workflow Status

Sanitization library for PHP and the Laravel framework.

Installation

composer require elegantweb/sanitizer

Usage

use Elegant\Sanitizer\Sanitizer;
use Elegant\Sanitizer\Filters\Enum;

$data = [
    'title' => ' ',
    'name' => ' sina ',
    'birth_date' => '06/25/1980',
    'email' => '[email protected]',
    'json' => '{"name":"value"}',
    'enum' => 'H',
];

$filters = [
    'title' => 'trim|empty_string_to_null',
    'name' => 'trim|empty_string_to_null|capitalize',
    'birth_date' => 'trim|empty_string_to_null|format_date:"m/d/Y","F j, Y"',
    'email' => ['trim', 'empty_string_to_null', 'lowercase'],
    'json' => 'cast:array',
    'enum' => ['trim', new Enum(BackedEnum::class)],
];

$sanitizer = new Sanitizer($data, $filters);

var_dump($sanitizer->sanitize());

Will result in:

[
    'title' => null,
    'name' => 'Sina',
    'birth_date' => 'June 25, 1980',
    'email' => '[email protected]',
    'json' => ['name' => 'value'],
    'enum' => BackedEnum::Hearts,
];

Laravel

In Laravel, you can use the Sanitizer through the Facade:

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

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 Elegant\Sanitizer\Laravel\SanitizesInput;

class MyAwesomeRequest extends Request
{
    use SanitizesInput;
    
    public function filters()
    {
        return [
            'name' => 'trim|capitalize',
        ];
    }
}

Optional

If you are planning to use sanitizer for all of your HTTP requests, you can optionally disable Laravel's TrimStrings and ConvertEmptyStringsToNull middleware from your HTTP kernel.

protected $middleware = [
    [...]
    // \App\Http\Middleware\TrimStrings::class,
    // \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    [...]
];

Then, instead, you can use trim and empty_string_to_null filters:

$filters = [
    'some_string_parameter' => 'trim|empty_string_to_null',
];

Available Filters

The following filters are available out of the box:

Filter Description
trim Trims the given string
empty_string_to_null If the given string is empty set it to null
escape Removes HTML tags and encodes special characters of the given string
lowercase Converts the given string to all lowercase
uppercase Converts the given string to all uppercase
capitalize Capitalizes the given string
cast Casts the given value into the given type. Options are: integer, float, string, boolean, object, array and Laravel Collection.
format_date Always takes two arguments, the given date's format and the target format, following DateTime notation.
strip_tags Strips HTML and PHP tags from the given string
digit Removes all characters except digits from the given string
enum Casts the given value to its corresponding enum type

Custom Filters

It is possible to use a closure or name of a class that implements Elegant\Sanitizer\Contracts\Filter interface.

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

$filters = [
    'remove_strings' => RemoveStringsFilter::class,
    'password' => fn ($value, array $options = []) => sha1($value),
];

$sanitize = new Sanitizer($data, $filters);

Laravel

You can 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, $closureOrClassName);

Inspiration

sanitizer's People

Contributors

alexjezior avatar francoism90 avatar korridor avatar onlime avatar sharifzadesina 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

sanitizer's Issues

Problem with 'extend' method

I have problems using the 'extend' method in Laravel 10.

image

I added the extension method in the AppServiceProvider, and the intelephense cannot identify the package

image

Am I doing something wrong?

Update to support Laravel 10

Just creating this issue so that you're aware that there's interest. We rely on your fantastic package for one of our projects, and we've updated to Laravel 10.

I can see that you have #14. Currently we're relying on a vcs setting which seems to work perfectly fine with the changes made in that PR (https://github.com/codea-au/sanitizer).

Keeping in mind that I don't think we've fully tested the code, the only thing that stands out to me as a glaring issue is that Laravel 10 doesn't work with PHP 8.0 so the test workflow needs to be rewritten, possibly to have a second matrix or the main composer.json file could remove support from old Laravel versions.

PHP 7.4 requirement

I trying install this package on my project and received this error:

  Problem 1
    - elegantweb/sanitizer v1.0.3 requires php ^7.4 -> your PHP version (7.3.19) does not satisfy that requirement.
    - Conclusion: don't install elegantweb/sanitizer v1.0.2
    - Conclusion: don't install elegantweb/sanitizer v1.0.1
    - Conclusion: remove laravel/framework v8.10.0
    - Installation request for elegantweb/sanitizer ^1.0 -> satisfiable by elegantweb/sanitizer[v1.0.0, v1.0.1, v1.0.2, v1.0.3].
    - Conclusion: don't install laravel/framework v8.10.0
    - elegantweb/sanitizer v1.0.0 requires illuminate/validation ^6.0|^7.0 -> satisfiable by illuminate/validation[6.x-dev, 7.x-dev].
    - don't install illuminate/validation 6.x-dev|don't install laravel/framework v8.10.0
    - don't install illuminate/validation 7.x-dev|don't install laravel/framework v8.10.0
    - Installation request for laravel/framework (locked at v8.10.0, required as ^8.10) -> satisfiable by laravel/framework[v8.10.0].
"require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "illuminate/validation": "^8.10",
        "laravel/framework": "^8.10",
        "laravel/tinker": "^2.0",
        "lucascudo/laravel-pt-br-localization": "^1.1"
},

php 7.4 is really necessary ?

Laravel 10 & php 8.2 - Filter [captilize] not found.

I'm getting Filter [captilize] not found.
here is my code`<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\Countries;
use Illuminate\Validation\Rules\Password;
use Elegant\Sanitizer\Laravel\SanitizesInput;

class StoreUserRequest extends FormRequest
{
use SanitizesInput;
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
//TODO::Need to check Auth User in Rules
// Example to add would be Auth::user()->can('add-users')
return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
 */
public function rules(): array
{
    $countryCode = 'US';

    if (!empty($this->countryid)) {
        $countryCode = (new Countries)->find($this->countryid)->country_code;
    }

    return [
        'title' => 'nullable|max:255',
        'firstname' => 'required|max:255',
        'lastname' => 'required|max:255',
        'email' => 'required|max:255|unique:users,email',
        'active' => 'required|boolean|sometimes',
        'password' => ['required', 'nullable', Password::min(6)
            ->letters()
            ->mixedCase()
            ->numbers()
            ->symbols()
            ->uncompromised()],
        'comfirmpassword' => 'required|same:password',
        'address1' => 'nullable|max:255',
        'address2' => 'nullable|max:255',
        'city' => 'nullable|max:255',
		'state' => 'nullable|max:255',
        'zipcode' => 'nullable|postal_code:'. $countryCode,
        'phone' => 'nullable|numeric|min:10',
        'cellphone' => 'nullable|numeric|min:10'
    ];
}

public function filters()
{
    return [
        'email' => 'trim|lowercase',
        'firstname' => 'trim|empty_string_to_null|captilize|escape',
        'lastname' => 'trim|empty_string_to_null|captilize|escape',
        'title' => 'trim|empty_string_to_null|captilize|escape',
        'active' => 'cast:boolean',
        'address1' => 'trim|empty_string_to_null|escape',
        'address2' => 'trim|empty_string_to_null|escape',
        'city' => 'trim|empty_string_to_null|escape',
        'state' => 'trim|empty_string_to_null|escape',
        'phone' => 'trim|empty_string_to_null|digit|escape',
        'cellphone' => 'trim|empty_string_to_null|digit|escape'
    ];
}

}`

Did I miss something??

[Feature Request] Default catch-all filter

Instead of having to identify all requests and which filters to apply, it would be greatly helpful if we could have a default filter to apply if the string parameter is not present in the $filters array.

Just wanted to thank you

Hey i just wanted to thank you for this package, cause i use WAAVI Sanitizer and it is less maintained. So thank you for your work.

Suggestion: Lower your minimum required php version.

Is there a specific reason php 7.4 is required?
You drastically limited you package for usability.

Laravel 8 (latest) is set to php 7.3 minimum and so are the most packages.

If there is no specific requirement for the use of php 7.4...
I would suggest lowering the required minimum version version an add a test (git action) for both (7.3, 7.4) php versions.

Add support for Laravel 11

Currently laravel have version 11 on dev stage, and developer can try, can you add support for laravel 11

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.