Brain-WP/BrainMonkey

Detecting closure for add_filter

Closed this issue · 6 comments

As a simple case, I've got:

add_filter( 'foo', function() {
	return '';
});

in a method.

When I call that method in my test, my assertion is:

static::assertTrue( has_filter( 'foo', 'function ()' ) );

...as this is how the docs say to do it.

The test fails however with a simple Failed asserting that false is true.

I've got another test in the same file, also using has_filter(), which suitably passes or fails when detecting a class method call.

What's the trick here?

BrainMonkey 1.4.2


The actual code I want to test is:

foreach ( $this->config->getArrayCopy() as $key => $value ) {
	add_filter( "genesis_pre_get_option_{$key}", function () use ( $value ) {
		return $value;
	} );
}

Works in BM 2, so I guess this just wasn't supported in BM 1.4.

@GaryJones The docs you are pointing are for version 2+, but the cose should work for v1.4.2 as well.

In v 1.* closures are all serialized to the string "function()" whereas in version 2 it is possbile to distinguish by closure arguments. But not having any arguments you test should not differ between the 2 version.

The issue is that in version 2.* the closure string form does not care about spaces, but in version 1 the string "function()" must be written exactly like that.

So your test will work if you use

static::assertTrue( has_filter( 'foo', 'function()' ) );

I'm reopening as it makes sense that in version 1.* both 'function()' and 'function ()' are accepted.

OK - the docs (v2) include the space, but it isn't clear whether this was required like that or not.

In v2, spaces are not an issue. So in v2 you already use function () and function(). I could mention that spaces are irrelevant.

I just checked and in v1 docs, the string was without spaces.

FIY There's a version/1 branch on the repo that contains last code for that series. You can look at /docs folder there, for a reference on v1 series, considering that GitHub pages does not allow for different version of the websites.

With d91ea9d function() can be used in v1.* with spaces anywhere and still valid, live in version 2.*. Will close when 1.4.3 will be out.

Done in v1.5.0.

Spaces are no more relevant: function(), and function ( ) are both valid now; actually anything matching ^\s*function\s*\(\s*\)\s*$ is valid.