| 1 | <?php |
| 2 | /** |
| 3 | * Psy CodeCleaner to allow PHP super globals. |
| 4 | * |
| 5 | * https://github.com/bobthecow/psysh/issues/353 |
| 6 | * |
| 7 | * Copyright © 2017 Justin Hileman <[email protected]> |
| 8 | * |
| 9 | * This program is free software; you can redistribute it and/or modify |
| 10 | * it under the terms of the GNU General Public License as published by |
| 11 | * the Free Software Foundation; either version 2 of the License, or |
| 12 | * (at your option) any later version. |
| 13 | * |
| 14 | * This program is distributed in the hope that it will be useful, |
| 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | * GNU General Public License for more details. |
| 18 | * |
| 19 | * You should have received a copy of the GNU General Public License along |
| 20 | * with this program; if not, write to the Free Software Foundation, Inc., |
| 21 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 22 | * http://www.gnu.org/copyleft/gpl.html |
| 23 | * |
| 24 | * @file |
| 25 | * @ingroup Maintenance |
| 26 | * |
| 27 | * @author Justin Hileman <[email protected]> |
| 28 | */ |
| 29 | |
| 30 | /** |
| 31 | * Prefix the real command with a 'global $VAR, $VAR2, ...;' command, where $VAR etc. |
| 32 | * are the current global variables. This will make the shell behave as if it was running |
| 33 | * in the global scope (almost; variables created in the shell won't become global if no |
| 34 | * global variable by that name existed before) so debugging MediaWikis globals-based |
| 35 | * configuration settings is less cumbersome, and behavior is closer to that of eval.php. |
| 36 | */ |
| 37 | class CodeCleanerGlobalsPass extends \Psy\CodeCleaner\CodeCleanerPass { |
| 38 | private const SUPERGLOBALS = [ |
| 39 | 'GLOBALS', '_SERVER', '_ENV', '_FILES', '_COOKIE', '_POST', '_GET', '_SESSION' |
| 40 | ]; |
| 41 | |
| 42 | public function beforeTraverse( array $nodes ) { |
| 43 | $globalVars = array_diff( array_keys( $GLOBALS ), self::SUPERGLOBALS ); |
| 44 | $validGlobalVars = array_filter( $globalVars, static function ( string $name ) { |
| 45 | // https://www.php.net/manual/en/language.variables.basics.php |
| 46 | return preg_match( '/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $name ); |
| 47 | } ); |
| 48 | |
| 49 | if ( $validGlobalVars ) { |
| 50 | $globalCommand = new \PhpParser\Node\Stmt\Global_( array_map( static function ( string $name ) { |
| 51 | return new \PhpParser\Node\Expr\Variable( $name ); |
| 52 | }, $validGlobalVars ) ); |
| 53 | array_unshift( $nodes, $globalCommand ); |
| 54 | } |
| 55 | |
| 56 | return $nodes; |
| 57 | } |
| 58 | } |