Skip to content

Commit 98b1e4d

Browse files
committed
Callback::closure() uses native Closure::fromCallable in PHP 7.1 (BC break)
BC break: is unable to create closure for private/protected methods from a different scope
1 parent 0fddd5d commit 98b1e4d

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/Utils/Callback.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,14 @@ public static function closure($callable, string $method = NULL): \Closure
2727
{
2828
if ($method !== NULL) {
2929
$callable = [$callable, $method];
30+
}
3031

32+
if (PHP_VERSION_ID >= 70100) {
33+
try {
34+
return \Closure::fromCallable($callable);
35+
} catch (\TypeError $e) {
36+
throw new Nette\InvalidArgumentException($e->getMessage());
37+
}
3138
} elseif (is_string($callable) && count($tmp = explode('::', $callable)) === 2) {
3239
$callable = $tmp;
3340

tests/Utils/Callback.closure.phpt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ test(function () { // global function
8686

8787
Assert::exception(function () {
8888
Callback::closure('undefined');
89-
}, Nette\InvalidArgumentException::class, "Callback 'undefined' is not callable.");
89+
}, Nette\InvalidArgumentException::class, PHP_VERSION_ID >= 70100 ? "%a% function 'undefined' not found %a%" : "Callback 'undefined' is not callable.");
9090

9191
Assert::exception(function () {
9292
Callback::toReflection('undefined');
@@ -142,7 +142,7 @@ test(function () { // object methods
142142
Assert::same('Test::privateFun', getName(Callback::toReflection([$test, 'privateFun'])));
143143
Assert::same('Test::privateFun', getName(Callback::toReflection(Callback::closure($test, 'privateFun'))));
144144

145-
Assert::same('Test::privateFun*', Callback::closure($test, 'privateFun')->__invoke('*'));
145+
Assert::same(PHP_VERSION_ID >= 70100 ? 'Test::__call privateFun *' : 'Test::privateFun*', Callback::closure($test, 'privateFun')->__invoke('*'));
146146

147147
Assert::same('Test::ref', Callback::closure($test, 'ref')(...[&$res]));
148148
Assert::same('Test::ref', $res);
@@ -175,7 +175,7 @@ test(function () { // static methods
175175
Assert::same('Test::privateStatic', getName(Callback::toReflection('Test::privateStatic')));
176176
Assert::same('Test::privateStatic', getName(Callback::toReflection(Callback::closure('Test::privateStatic'))));
177177

178-
Assert::same('Test::privateStatic*', Callback::closure('Test::privateStatic')->__invoke('*'));
178+
Assert::same(PHP_VERSION_ID >= 70100 ? 'Test::__callStatic privateStatic *' : 'Test::privateStatic*', Callback::closure('Test::privateStatic')->__invoke('*'));
179179
});
180180

181181

0 commit comments

Comments
 (0)