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 $exec = 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());
71 if (self::shouldBindClosure()) {
72 $that = $__psysh__->getBoundObject();
73 if (is_object($that)) {
74 $this->closure = $exec->bindTo($that, get_class($that));
76 $this->closure = $exec->bindTo(null, null);
82 $this->closure = $exec;
86 * Go go gadget closure.
90 public function execute()
92 $closure = $this->closure;
98 * Decide whether to bind the execution closure.
102 protected static function shouldBindClosure()
104 // skip binding on HHVM < 3.5.0
105 // see https://github.com/facebook/hhvm/issues/1203
106 if (defined('HHVM_VERSION')) {
107 return version_compare(HHVM_VERSION, '3.5.0', '>=');