Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve node_autocomplete_validate() code to be less confusing #6762

Open
NormPlum opened this issue Nov 23, 2024 · 0 comments
Open

Improve node_autocomplete_validate() code to be less confusing #6762

NormPlum opened this issue Nov 23, 2024 · 0 comments

Comments

@NormPlum
Copy link

Description of the need

Some of the code in node_autocomplete_validate() is confusing and, if people are reading it to understand how something works, can give them the wrong idea.

The code in question is:

$result = preg_match('/\[([0-9]+)\]$/', $string, $matches);
  if ($result > 0) {
    // If $result is nonzero, we found a match and can use it as the index into
    // $matches.
    $nid = $matches[$result];

if ($result > 0) { seems to imply that $result can be 1, 2, 3, etc. Whereas the PHP manual says:

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or false on failure.

This is also reinforced by $nid = $matches[$result]; where it seems that whatever the $result value is, that's what you need to use as the key to get the value of the match. However the PHP manual says:

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

So you may not always want the first parenthesized match, but that's all you'll ever get if you use $result as the key.

Proposed solution

Here's what I propose changing it to:

$result = preg_match('/\[([0-9]+)\]$/', $string, $matches);
  // If $result equals 1, we found a match.
  if ($result == 1) {
    // Get the first parenthesized match.
    $nid = $matches[1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants