[wp-trac] [WordPress Trac] #46635: Improve identifying of non–trivial callbacks in hooks
WordPress Trac
noreply at wordpress.org
Wed Apr 3 16:28:31 UTC 2019
#46635: Improve identifying of non–trivial callbacks in hooks
-------------------------+-------------------------------
Reporter: Rarst | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version:
Severity: normal | Resolution:
Keywords: | Focuses: coding-standards
-------------------------+-------------------------------
Comment (by giuseppe.mazzapica):
> While this would have made sense if it was baked into API ''from the
start'', I feel it is a weak as an optional addition to a very established
one. It simply doesn't help the case when developer doesn't add an
identifier and we are back to square one. We do ''need'' to improve
removal for current state of API.
Yes, what I've in mind is a way to override an identifier which, by
default, would be auto-generated.
A fictional function that generates the string representation of a
callback could be like this (I speak PHP better than english):
{{{#!php
<?php
function _wp_serialize_callback( $callback, $identifier = null ) {
if ( ! is_callable( $callback, true ) ) {
return '';
}
// Dev-provided identifier, just use it
if ( $identifier ) {
// should be a string, but who knows
return maybe_serialize( $identifier );
}
// plain function (or static methds in the form "ClassName::methodName")
if ( is_string( $callback ) ) {
return $callback;
}
if ( $callback instanceof Closure ) {
// $r = new ReflectionFunction($f); return 'function()@' .
$r->getFileName();
return 'function()';
}
// invokables
if ( is_object( $callback ) ) {
$class = get_class( $callback );
if ( false !== strpos( $class, '@' ) ) {
// anonymous class
$class = 'class';
}
return $class . '()';
}
// methods
if ( is_array( $callback ) ) {
// static methods can be rendered as strings
if ( is_string( $callback[0] ) ) {
return $callback[0] . '::' . $callback[1];
}
$class = get_class( $callback );
if ( false !== strpos( $class, '@' ) ) {
// anonymous class
$class = 'class';
}
return $class . '->' . $callback[1];
}
}
}}}
With such function in place, `WP_Hook` could keep a map from callbacks
''IDs'' (created by `_wp_filter_build_unique_id`) to callback ''string
representations''.
If a string representation is passed to `remove_filter`, the callback ID
can be resolved from that map, and hook can be removed.
Of course, the map could have multiple IDs for a single string
representation, and in such case probably all matching hooks should be
removed.
With such approach ''at least'' we have something, but in best case
scenario (which imo should be recommended by WPCS) there's the possibility
to ''really'' uniquely identify closures.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/46635#comment:8>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list