- preg_match: documentation ( source)
- array_slice: documentation ( source)
- implode: documentation ( source)
- strlen: documentation ( source)
- file: documentation ( source)
<?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) {
// ...
}