Skip to content

Function names can be reused across multiple PHP snippets #230

Open
@georgestephanis

Description

@georgestephanis

Current behavior

This behavior can cause fatal errors on site front-ends.

Image

Expected behavior

It would be useful if the PHP Validator's check for duplicate identifiers would keep an index of other defined functions in other snippets, and if someone attempts to redeclare an existing function name, prompt the user to change it.

/**
* Check whether a particular identifier has been used previously.
*
* @param string $type Which type of identifier this is. Supports T_FUNCTION, T_CLASS and T_INTERFACE.
* @param string $identifier The name of the identifier itself.
*
* @return bool true if the identifier is not unique.
*/
private function check_duplicate_identifier( string $type, string $identifier ): bool {
if ( ! isset( $this->defined_identifiers[ $type ] ) ) {
switch ( $type ) {
case T_FUNCTION:
$defined_functions = get_defined_functions();
$this->defined_identifiers[ T_FUNCTION ] = array_merge( $defined_functions['internal'], $defined_functions['user'] );
break;
case T_CLASS:
$this->defined_identifiers[ T_CLASS ] = get_declared_classes();
break;
case T_INTERFACE:
$this->defined_identifiers[ T_INTERFACE ] = get_declared_interfaces();
break;
default:
return false;
}
}
$duplicate = in_array( $identifier, $this->defined_identifiers[ $type ], true );
array_unshift( $this->defined_identifiers[ $type ], $identifier );
return $duplicate && ! ( isset( $this->exceptions[ $type ] ) && in_array( $identifier, $this->exceptions[ $type ], true ) );
}

Alternately, if the function names declared in each snippet could be stored in meta for the snippet, with function_exists() checks for each before it is eval'd, to avoid fataling a site?

Steps to reproduce

To reproduce, activate these two (simple) test snippets and view the front-end of the site.

test-fn-1.code-snippets.json
test-fn-2.code-snippets.json

WordPress version

6.7.2

Code Snippets version

3.6.8

Code Snippets license

Core (free)

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions