4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
15 * The Psy Shell's execution scope.
17 class ExecutionClosure
19 const NOOP_INPUT = 'return null;';
24 * @param Shell $__psysh__
26 public function __construct(Shell $__psysh__)
28 $this->setClosure($__psysh__, function () use ($__psysh__) {
30 // Restore execution scope variables
31 extract($__psysh__->getScopeVariables(false));
33 // Buffer stdout; we'll need it later
34 ob_start([$__psysh__, 'writeStdout'], 1);
36 // Convert all errors to exceptions
37 set_error_handler([$__psysh__, 'handleError']);
39 // Evaluate the current code buffer
40 $_ = eval($__psysh__->onExecute($__psysh__->flushCode() ?: ExecutionClosure::NOOP_INPUT));
41 } catch (\Throwable $_e) {
42 // Clean up on our way out.
43 restore_error_handler();
44 if (ob_get_level() > 0) {
49 } catch (\Exception $_e) {
50 // Clean up on our way out.
51 restore_error_handler();
52 if (ob_get_level() > 0) {
59 // Won't be needing this anymore
60 restore_error_handler();
62 // Flush stdout (write to shell output, plus save to magic variable)
65 // Save execution scope variables for next time
66 $__psysh__->setScopeVariables(get_defined_vars());
73 * Set the closure instance.
76 * @param \Closure $closure
78 protected function setClosure(Shell $shell, \Closure $closure)
80 if (self::shouldBindClosure()) {
81 $that = $shell->getBoundObject();
82 if (is_object($that)) {
83 $closure = $closure->bindTo($that, get_class($that));
85 $closure = $closure->bindTo(null, $shell->getBoundClass());
89 $this->closure = $closure;
93 * Go go gadget closure.
97 public function execute()
99 $closure = $this->closure;
105 * Decide whether to bind the execution closure.
109 protected static function shouldBindClosure()
111 // skip binding on HHVM < 3.5.0
112 // see https://github.com/facebook/hhvm/issues/1203
113 if (defined('HHVM_VERSION')) {
114 return version_compare(HHVM_VERSION, '3.5.0', '>=');