PHPCompatibility / PHPModernizer

External PHPCS standard with auto-fixers to modernize legacy codebases
GNU Lesser General Public License v3.0
10 stars 0 forks source link

New sniff: change `create_function()` code to closures #6

Open jrfnl opened 6 years ago

jrfnl commented 6 years ago
Sniff basics -
Fixable for PHP: 5.3+
Sniff type: Modernize
Fixer type: Risky

Short description

PHP 5.3 introduced anonymous functions - also called closures - for on the fly function creation. Previously this was only possible using a call to create_function(). Use of create_function() has been deprecated as of PHP 7.2 and is slated to be removed in PHP 8.0.

Related PHPCompatibility sniff(s):

PHP manual references:

Example code:

Detect the following code pattern(s):

$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');

$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . ", ".crc32($b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
);

array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));

And fix these to:

$newfunc = function($a,$b) { return "ln($a) + ln($b) = " . log($a * $b); };

$garr = array(
    function($b,$a) { if (strncmp($a, $b, 3) == 0) return "** \"$a\"
    and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";},
    function($a,$b) {; return "CRCs: " . crc32($a) . ", ".crc32($b);},
    function($a,$b) {; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";}
);

array_walk($av, function(&$v,$k) { $v = $v . "mango";});

Notes for implementation of the sniff:

For code which still has to support PHP < 5.3 as well as PHP 7.2+, the sniff could add the @ silence operator to the create_function() call to prevent the deprecated function notice from being thrown.