user610342
user610342

Reputation: 235

PHP change create_function to anonymous function

I have inherited some old code and need to convert the create_function to an anonymous function. I have done that but since I cannot see the code in the anonymous function I do not know if it equals the code in the former create_function.

Here is the code and my question is: is 'my translation' equal to the 'original code'?

public static function makePhpVdtorFromRegex($regex, $match = TRUE)
{
    //original code
    $s = 'return '.($match?'':'0 == ').'preg_match(\'/'.addslashes($regex).'/\',$v);';
    return create_function('$v', $s);

    // my translation
    return function($v) use ($regex, $match) {
        return ($match?'':'0 == ').preg_match('/'.addslashes($regex).'/',$v);
    };
}

I believe makePhpVdtorFromRegex stands for 'Make PHP Validator From Regex'. The problem in validating this is I am not sure where the actual validator is used as this anonymous function is stored in an array which is used to validate input at some later time doing form input validation.

Because $regex and $match only exist within makePhpVdtorFromRegex() they will not be available when the validator is ultimately run, right? So I suspect my translation is not going to work?

Upvotes: 0

Views: 249

Answers (1)

nosurs
nosurs

Reputation: 665

To mimic the original behaviour, you should be able to replace it with (for testing purposes, I turned the method into a function):

function makePhpVdtorFromRegex($regex, $match = true) {

    if ($match) {

        return function($value) use ($regex) {

            return preg_match('/'.addslashes($regex).'/', $value);
        };
    }
    
    return function($value) use ($regex) {
        
        // Same as '0 == preg_match(...)' from original code
        return !preg_match('/'.addslashes($regex).'/', $value);
    };
}

$validator = makePhpVdtorFromRegex('^[a-z]+$');

// Check if something matches

var_dump($validator('abc')); // true

// Check if something doesn't match
 
$validator = makePhpVdtorFromRegex('^[a-z]+$', false);

var_dump($validator('123')); // true

If you've the chance to look into the actual form validation later on & maybe even take control of the regular expressions themselves, you could rewrite this code to something much simpler, like:

function getRegexValidator() {

    return function($regex, $value) {

        return preg_match($regex, $value);
    };
}

$validator = getRegexValidator();

// Check if something matches

var_dump($validator('/^[a-z]+$/', 'abc')); // true

// Check if something doesn't match

var_dump(!$validator('/^[a-z]+$/', '123')); // true

Upvotes: 1

Related Questions