I am trying to update a legacy php code (7.0) for php 7.4 >=
and one of the new features that I would like to use the new fn() =>
syntax, instead of function() use () {}
Unfortunately, I have hundreds of anonymous functions using CakePHP ORM like:
$query->matching('Tags', function ($q) {
return $q->where(['Tags.name' => 'CakePHP']);
});
Using php 7.4 >= could be:
$query->matching('Tags', fn($q) =>
$q->where(['Tags.name' => 'CakePHP'])
);
Sometimes using "use":
$query = $articles->find()->matching('Comments.Users', function ($q) use ($username) {
return $q->where(['username' => $username]);
});
php 7.4 >= (use is not needed):
$query = $articles->find()->matching('Comments.Users', fn ($q) =>
$q->where(['username' => $username])
);
Or using two or more params:
$query->where(function (QueryExpression $exp, Query $q) {
return $exp->eq('published', true);
});
But when you have more than one instruction, fn () cannot be used, for example:
$results->map(function ($row) {
$row['age'] = $row['birth_date']->diff(new \DateTime)->y;
return $row;
});
I would like to use notepad++ regex and replace in all files feature to execute a regex and replace all "possible" functions()
for fn()
.
So, What REGEX could achieve this goal?
Find: function\s*\(([^\(\)]*)\)[^\{]*\{\s*return\s*([^;]*)\s*;\s*\}
Replace: fn\(\1\) => \2