@ 2019-03-13T18:49:31Z <?php
namespace Fake\BuiltIn\Functions;
/**
* Executes the given statements using fake built-in functions.
*
* @param callable $statements Statements to execute.
* @return mixed Whatever $statements returns.
* @throws \ReflectionException
*/
function fake(callable $statements)
{
$function = new \ReflectionFunction($statements);
$start_line = $function->getStartLine();
$end_line = $function->getEndLine();
$function_source = implode('',
array_slice(file($function->getFileName()), $start_line - 1, $end_line - $start_line + 1));
if (preg_match('/(?<={).*(?=})/s', $function_source, $matches)) {
$function_body = $matches[0];
$namespace = __NAMESPACE__;
return eval("
namespace $namespace;
$function_body
");
}
throw new \RuntimeException('Failed to execute statements.');
}
function strlen($string)
{
return 'fake result';
}
namespace My\Name\Space;
use function Fake\BuiltIn\Functions\fake;
class MyClass
{
/**
* @throws \ReflectionException
*/
public function testMethodWithFakeStrlen()
{
fake(function () {
echo strlen('foo'), PHP_EOL;
});
}
public function testMethodWithoutFakeStrlen()
{
echo strlen('foo'), PHP_EOL;
}
}
$myObject = new MyClass();
try {
$myObject->testMethodWithFakeStrlen();
$myObject->testMethodWithoutFakeStrlen();
} catch (\ReflectionException $e) {
// ...
}
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 7.1.25 - 7.1.33 , 7.2.0 - 7.2.33 , 7.3.0 - 7.3.33 , 7.4.0 - 7.4.33 , 8.0.0 - 8.0.30 , 8.1.0 - 8.1.28 , 8.2.0 - 8.2.18 , 8.3.0 - 8.3.4 , 8.3.6 fake result
3
Output for 8.3.5 Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
fake result
3
preferences:dark mode live preview
200.36 ms | 402 KiB | 184 Q