- var_dump: documentation ( source)
<?php
function decorate(callable $fn, callable $decorator)
{
$wrapper = $decorator();
return function() use ($fn, $wrapper) {
$gen = $wrapper();
// Only call the wrapped function if the decorator made "yield"
if (!$gen instanceof \Generator) {
return $gen;
}
// Use the yielded arguments, forward all if none given.
if (is_array($gen->current())) {
$arguments = $gen->current();
} else {
$arguments = func_get_args();
}
// Forward all throwed Exceptions
try {
// Send the decorated function's return value into the
// decorator as return value of "yield"
$gen->send(call_user_func_array($fn, $arguments));
} catch (\Exception $e) {
$gen->throw($e);
}
};
}
function foo($bar)
{
throw new Exception("Error $bar!");
}
function catch_all_exceptions()
{
return function() {
try {
(yield);
} catch (\Exception $e) {
echo "catch_all_exceptions: Caught Exception: $e\n";
}
};
}
function do_something_before()
{
return function() {
echo "Before!\n";
return "foo";
};
}
$foo = decorate(decorate("foo", "catch_all_exceptions"), "do_something_before");
var_dump($foo("bar"));