Skip to content

Instantly share code, notes, and snippets.

@vertexvaar
Created December 4, 2020 17:16
Show Gist options
  • Save vertexvaar/c9d12138570971e2f6a1fa33ed624ab1 to your computer and use it in GitHub Desktop.
Save vertexvaar/c9d12138570971e2f6a1fa33ed624ab1 to your computer and use it in GitHub Desktop.
Create a filter function by assembling the factory function as PHP code and eval
<?php
define('FILTER_MATCH_EXACT', 1 << 0);
define('FILTER_MATCH_LOOSE', 1 << 1);
define('FILTER_INVERT', 1 << 2);
function filter(mixed $specimen, int $flags = FILTER_MATCH_EXACT): Closure
{
// Unset FILTER_MATCH_EXACT if FILTER_MATCH_LOOSE is set.
if ($flags & FILTER_MATCH_LOOSE) {
$flags &= ~FILTER_MATCH_EXACT;
}
// int, float, string or bool
if (is_scalar($specimen)) {
$function = <<<'PHP'
return static function (mixed $test) {
return $test ###COMPARISON### ###SPECIMEN###;
};
PHP;
$comparisonPrefix = ($flags & FILTER_INVERT) ? '!' : '=';
$comparison = ($flags & FILTER_MATCH_EXACT) ? $comparisonPrefix . '==' : $comparisonPrefix . '=';
$functionFactory = str_replace(
['###COMPARISON###', '###SPECIMEN###'],
[$comparison, var_export($specimen, true)],
$function
);
return eval($functionFactory);
}
// Not implemented
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment