Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sharifzadesina committed Aug 11, 2020
0 parents commit b8e156d
Show file tree
Hide file tree
Showing 36 changed files with 1,456 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/vendor/
composer.lock
.phpunit.result.cache
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
language: php

php:
- 7.4

before_script:
- travis_retry composer self-update
- travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source

script:
- phpunit
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) <William Wallace>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
189 changes: 189 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# WAAVI Sanitizer

[![Latest Version on Packagist](https://img.shields.io/packagist/v/waavi/sanitizer.svg?style=flat-square)](https://packagist.org/packages/waavi/sanitizer)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Build Status](https://img.shields.io/travis/waavi/sanitizer/master.svg?style=flat-square)](https://travis-ci.org/waavi/sanitizer)
[![Total Downloads](https://img.shields.io/packagist/dt/waavi/sanitizer.svg?style=flat-square)](https://packagist.org/packages/waavi/sanitizer)

## 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](http://waavi.com/en/contactanos).

## 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:

```php
$data = [
'first_name' => 'john',
'last_name' => '<strong>DOE</strong>',
'email' => ' JOHn@DoE.com',
'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:
```php
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:
```php
[
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'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:
```php
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:

```php
'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:
```php
$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:

```php
\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.

```php
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](http://opensource.org/licenses/MIT)
44 changes: 44 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "elegantweb/sanitizer",
"description": "Data sanitizer and Laravel 7 form requests with input sanitation.",
"keywords": ["laravel", "sanitation", "input sanitation", "input sanitizer", "input", "transform input", "input filter"],
"license": "MIT",
"authors": [
{
"name": "William Wallace San Paulo",
"email": "info@waavi.com"
},
{
"name": "Sina Sharifzade",
"email": "sharifzadesina@gmail.com"
}
],
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"illuminate/support": "^6.0|^7.0",
"illuminate/validation": "^6.0|^7.0",
"nesbot/carbon": "^1.0|^2.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0"
},
"autoload": {
"psr-4": {
"Elegant\\Sanitizer\\": "src/"
}
},
"autoload-dev": {
"classmap": ["tests"]
},
"extra": {
"laravel": {
"providers": [
"Elegant\\Sanitizer\\Laravel\\SanitizerServiceProvider"
],
"aliases": {
"Sanitizer": "Elegant\\Sanitizer\\Laravel\\Facade"
}
}
}
}
17 changes: 17 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite name="Sanitizer Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
14 changes: 14 additions & 0 deletions src/Contracts/Filter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Elegant\Sanitizer\Contracts;

interface Filter
{
/**
* Return the result of applying this filter to the given input.
*
* @param mixed $value
* @return mixed
*/
public function apply($value, $options = []);
}
19 changes: 19 additions & 0 deletions src/Filters/Capitalize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Elegant\Sanitizer\Filters;

use Elegant\Sanitizer\Contracts\Filter;

class Capitalize implements Filter
{
/**
* Capitalize the given string.
*
* @param mixed $value
* @return mixed
*/
public function apply($value, $options = [])
{
return is_string($value) ? mb_convert_case(mb_strtolower($value, 'UTF-8'), MB_CASE_TITLE) : $value;
}
}
43 changes: 43 additions & 0 deletions src/Filters/Cast.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Elegant\Sanitizer\Filters;

use Illuminate\Support\Collection;
use Elegant\Sanitizer\Contracts\Filter;

class Cast implements Filter
{
/**
* Capitalize the given string.
*
* @param mixed $value
* @return mixed
*/
public function apply($value, $options = [])
{
$type = isset($options[0]) ? $options[0] : null;
switch ($type) {
case 'int':
case 'integer':
return (int) $value;
case 'real':
case 'float':
case 'double':
return (float) $value;
case 'string':
return (string) $value;
case 'bool':
case 'boolean':
return (bool) $value;
case 'object':
return is_array($value) ? (object) $value : json_decode($value, false);
case 'array':
return json_decode($value, true);
case 'collection':
$array = is_array($value) ? $value : json_decode($value, true);
return new Collection($array);
default:
throw new \InvalidArgumentException("Wrong Sanitizer casting format: {$type}.");
}
}
}
19 changes: 19 additions & 0 deletions src/Filters/Digit.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Elegant\Sanitizer\Filters;

use Elegant\Sanitizer\Contracts\Filter;

class Digit implements Filter
{
/**
* Get only digit characters from the string.
*
* @param mixed $value
* @return mixed
*/
public function apply($value, $options = [])
{
return preg_replace('/[^0-9]/si', '', $value);
}
}
Loading

0 comments on commit b8e156d

Please sign in to comment.