Skip to content

Instantly share code, notes, and snippets.

@upsilon
Last active August 29, 2015 13:56
Show Gist options
  • Save upsilon/9031948 to your computer and use it in GitHub Desktop.
Save upsilon/9031948 to your computer and use it in GitHub Desktop.
<?php
class Filter
{
const REGEX_TRIM = "[\\x0-\x20\x7f]";
const REGEX_FTRIM = "[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]";
public static function presetUtf8($default = '')
{
return function($tainted) use ($default)
{
if (!is_scalar($tainted))
return $default;
return preg_replace('//u', '', $tainted) ?: $default;
};
}
public static function presetTrim()
{
return function($tainted)
{
if (!is_scalar($tainted))
return '';
return preg_replace(sprintf('/\A%1$s++|%1$s++\z/u', Filter::REGEX_TRIM), '', $tainted) ?: '';
};
}
public static function presetFullTrim()
{
return function($tainted)
{
if (!is_scalar($tainted))
return '';
return preg_replace(sprintf('/\A%1$s++|%1$s++\z/u', Filter::REGEX_FTRIM), '', $tainted) ?: '';
};
}
public static function presetRecursive(Closure $filter)
{
return function($taintedArray) use ($filter)
{
$clean = array();
foreach ((array)$taintedArray as $key => $taintedValue)
{
if (!preg_match('//u', $key))
continue;
$clean[$key] = $filter($taintedValue);
}
return $clean;
};
}
public static function schema(array $schema)
{
foreach ($schema as $key => &$value)
{
if (is_scalar($value))
$value = self::presetUtf8($value);
}
return function($taintedArray) use ($schema)
{
$clean = array();
foreach ($schema as $key => $filter)
{
$tainted = isset($taintedArray[$key]) ? $taintedArray[$key] : null;
$clean[$key] = $filter($tainted);
}
return $clean;
};
}
}
$filterDef = array(
'name' => '',
'age' => Filter::presetTrim(),
'email' => '',
'gender' => Filter::presetTrim(),
'comment' => '',
'options' => Filter::presetRecursive(Filter::presetFullTrim()),
'date' => function($tainted) {
return is_string($tainted) && preg_match('/^\d{4}-\d{2}-\d{2}$/u', $tainted)
? $tainted
: '';
},
);
$filter = Filter::schema($filterDef);
// 入力値
$tainted = array(
'name' => array('INVALID' => 'これは無効な値です'),
'age' => ' 20 ',
'gender' => ' male     ',
'comment' => ' はじめまして!!    ',
'options' => array(
'a' => '  yes ',
'b' => "\x0a\x0a\xff",
'c' => array('INVALID' => 'これは無効な値です'),
"\x0a\x0a\xff" => 'INVALID',
),
'date' => '2014-02-16',
);
$cleanValue = $filter($tainted);
var_dump($cleanValue);
/*
結果:
array(7) {
'name' =>
string(0) ""
'age' =>
string(2) "20"
'email' =>
string(0) ""
'gender' =>
string(17) "male     "
'comment' =>
string(39) " はじめまして!!    "
'options' =>
array(3) {
'a' =>
string(3) "yes"
'b' =>
string(0) ""
'c' =>
string(0) ""
}
'date' =>
string(10) "2014-02-16"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment