Skip to content

Commit

Permalink
Added striptags sanitizer
Browse files Browse the repository at this point in the history
  • Loading branch information
jenwachter committed Sep 20, 2016
1 parent 344d205 commit 1775f64
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 8 deletions.
47 changes: 43 additions & 4 deletions src/Utility/Sanitizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,59 @@ public function __construct($data = array())
$this->data = $data;
}

public function stripslashes()
/**
* Apply a function to each value
* @param string $function Function name (ex: "stripslashes")
* @param array $args Function arguments
* @return null
*/
protected function apply($function, $args = array())
{
foreach ($this->data as $key => &$value) {

if (!is_array($value)) {
$value = stripslashes($value);
$value = $this->applyToValue($function, $args, $value);
} else {
$value = array_map(function ($v) {
return stripslashes($v);
$value = array_map(function ($v) use ($function, $args) {
return $this->applyToValue($function, $args, $v);
}, $value);
}

}
}

/**
* Apply a function to a single form value
* @param string $function Function name
* @param array $args Function arguments
* @param string $value Value to apply functon to
* @return string Sanitized value
*/
protected function applyToValue($function, $args, $value)
{
array_unshift($args, $value);
return call_user_func_array($function, $args);
}

/**
* Strip slashes from data
* @return object self
*/
public function stripslashes()
{
$this->apply("stripslashes");
return $this;
}

/**
* Remove tags from data
* @param array $except Array of tags ex: <br>
* @return object self
*/
public function striptags($except = array())
{
$except = implode("", $except);
$this->apply("strip_tags", array($except));
return $this;
}
}
9 changes: 5 additions & 4 deletions tests/Utility/SanitizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@

class SanitizerTest extends \PHPUnit_Framework_TestCase
{
public function testValidateHtmlAndAddable()
public function testSanitize()
{
$given = array(
"field1" => "A string with an escaped apostrophe: it\'s",
"field1" => "<p>A <strong>string</strong> with an <script></script>escaped apostrophe: it\'s</p>",
"field2" => array(
"it\'s cool",
"yeah it\'s cool"
)
);

$expected = array(
"field1" => "A string with an escaped apostrophe: it's",
"field1" => "<p>A <strong>string</strong> with an escaped apostrophe: it's</p>",
"field2" => array(
"it's cool",
"yeah it's cool"
Expand All @@ -25,7 +25,8 @@ public function testValidateHtmlAndAddable()
$sanitizer = new Sanitizer($given);

$sanitizer
->stripslashes();
->stripslashes()
->striptags(array("<p>", "<strong>"));

$this->assertEquals($expected, $sanitizer->data);
}
Expand Down

0 comments on commit 1775f64

Please sign in to comment.