Skip to content

Commit

Permalink
Adds support for Closure rules (#45)
Browse files Browse the repository at this point in the history
* Support Closure rules

* Test Closure rules

* Bug fix

* Fix test

* Fix test
  • Loading branch information
sharifzadesina authored and William committed Nov 14, 2019
1 parent 1f0b7c9 commit 73675ac
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 35 deletions.
68 changes: 34 additions & 34 deletions src/Sanitizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationRuleParser;
use Illuminate\Validation\ClosureValidationRule;
use InvalidArgumentException;

class Sanitizer
Expand Down Expand Up @@ -49,7 +50,7 @@ class Sanitizer
public function __construct(array $data, array $rules, array $customFilters = [])
{
$this->data = $data;
$this->rules = $this->parseRulesArray($rules);
$this->rules = $this->parseRules($rules);
$this->filters = array_merge($this->filters, $customFilters);
}

Expand All @@ -59,15 +60,15 @@ public function __construct(array $data, array $rules, array $customFilters = []
* @param array $rules
* @return array
*/
protected function parseRulesArray(array $rules)
protected function parseRules(array $rules)
{
$parsedRules = [];

$rawRules = (new ValidationRuleParser($this->data))->explode($rules);

foreach ($rawRules->rules as $attribute => $attributeRules) {
foreach ($attributeRules as $attributeRule) {
$parsedRule = $this->parseRuleString($attributeRule);
$parsedRule = $this->parseRule($attributeRule);
if ($parsedRule) {
$parsedRules[$attribute][] = $parsedRule;
}
Expand All @@ -77,6 +78,23 @@ protected function parseRulesArray(array $rules)
return $parsedRules;
}

/**
* Parse a rule.
*
* @param string|Closure $rule
* @return array|Closure
*/
protected function parseRule($rule)
{
if (is_string($rule)) {
return $this->parseRuleString($rule);
} elseif ($rule instanceof ClosureValidationRule) {
return $rule->callback;
} else {
throw new InvalidArgumentException("Unsupported rule type.");
}
}

/**
* Parse a rule string formatted as filterName:option1, option2 into an array formatted as [name => filterName, options => [option1, option2]]
*
Expand All @@ -100,27 +118,36 @@ protected function parseRuleString($rule)

/**
* Apply the given filter by its name
* @param $name
*
* @param string|Closure $rule
* @return Filter
*/
protected function applyFilter($name, $value, $options = [])
protected function applyFilter($rule, $value)

This comment has been minimized.

Copy link
@alariva

alariva Nov 14, 2019

Contributor

Inconsistent change here: The signature of the function is string|Closure $rule but then $rule is being treated as an array.

This comment has been minimized.

Copy link
@marcosmartinezeu

marcosmartinezeu Nov 20, 2019

Error:

"message": "Illegal string offset 'name'",
"trace": [
    {
        "file": "/var/www/vendor/waavi/sanitizer/src/Sanitizer.php",
        "line": 131,
        "function": "handleError",
        "class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
        "type": "->",
        "args": [
            2,
            "Illegal string offset 'name'",
            "/var/www/vendor/waavi/sanitizer/src/Sanitizer.php",
            131,
            {
                "rule": "trim",
                "value": "usertest@meneame.net"
            }
        ]
    },
{
if ($rule instanceof Closure) {
return call_user_func($rule, $value);
}

$name = $rule['name'];
$options = $rule['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");
}

$filter = $this->filters[$name];

if ($filter instanceof Closure) {
return call_user_func_array($filter, [$value, $options]);
} else {

This comment has been minimized.

Copy link
@omd166

omd166 Sep 20, 2020

ok

$filter = new $filter;
return $filter->apply($value, $options);
return (new $filter)->apply($value, $options);
}
}

/**
* Sanitize the given data
*
* @return array
*/
public function sanitize()
Expand Down Expand Up @@ -151,31 +178,4 @@ public function sanitize()

return $sanitized;
}

/**
* Sanitize the given attribute
*
* @param string $attribute Attribute name
* @param mixed $value Attribute value
* @return mixed Sanitized value
*/
protected function sanitizeAttribute($attribute, $value)
{
if (isset($this->rules[$attribute])) {
$sanitize = true;
$original = $value;
foreach ($this->rules[$attribute] as $rule) {
if ($rule['name'] === 'filter_if') {
$sanitize = $this->applyFilter($rule['name'], $value, $rule['options']);
} else {
$value = $this->applyFilter($rule['name'], $value, $rule['options']);
}
}

if (!$sanitize) {
return $original;
}
}
return $value;
}
}
19 changes: 18 additions & 1 deletion tests/SanitizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public function test_input_unchanged_if_no_filter()
$this->assertEquals(' HellO EverYboDy ', $data['name']);
}

public function test_array_filters() {
public function test_array_filters()
{
$data = [
'name' => ' HellO EverYboDy ',
];
Expand Down Expand Up @@ -109,4 +110,20 @@ public function test_it_should_only_sanitize_passed_data()
$this->assertArrayHasKey('title', $data);
$this->assertEquals(1, count($data));
}

public function test_closure_rule()
{
$data = [
'name' => ' Sina '
];

$rules = [
'name' => ['trim', function ($value) {
return strtoupper($value);
}]
];

$data = $this->sanitize($data, $rules);
$this->assertEquals('SINA', $data['name']);
}
}

0 comments on commit 73675ac

Please sign in to comment.