idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
13,000
public function getConfigFile ( ) { if ( isset ( $ this -> configFile ) ) { return $ this -> configFile ; } $ files = ConfigPaths :: getConfigFiles ( [ 'config.php' , 'rc.php' ] , $ this -> configDir ) ; if ( ! empty ( $ files ) ) { if ( $ this -> warnOnMultipleConfigs && \ count ( $ files ) > 1 ) { $ msg = \ sprintf ( 'Multiple configuration files found: %s. Using %s' , \ implode ( $ files , ', ' ) , $ files [ 0 ] ) ; \ trigger_error ( $ msg , E_USER_NOTICE ) ; } return $ files [ 0 ] ; } }
Get the current PsySH config file .
13,001
public function loadConfig ( array $ options ) { foreach ( self :: $ AVAILABLE_OPTIONS as $ option ) { if ( isset ( $ options [ $ option ] ) ) { $ method = 'set' . \ ucfirst ( $ option ) ; $ this -> $ method ( $ options [ $ option ] ) ; } } if ( isset ( $ options [ 'tabCompletion' ] ) ) { $ msg = '`tabCompletion` is deprecated; use `useTabCompletion` instead.' ; @ \ trigger_error ( $ msg , E_USER_DEPRECATED ) ; $ this -> setUseTabCompletion ( $ options [ 'tabCompletion' ] ) ; } foreach ( [ 'commands' , 'matchers' , 'casters' ] as $ option ) { if ( isset ( $ options [ $ option ] ) ) { $ method = 'add' . \ ucfirst ( $ option ) ; $ this -> $ method ( $ options [ $ option ] ) ; } } if ( isset ( $ options [ 'tabCompletionMatchers' ] ) ) { $ msg = '`tabCompletionMatchers` is deprecated; use `matchers` instead.' ; @ \ trigger_error ( $ msg , E_USER_DEPRECATED ) ; $ this -> addMatchers ( $ options [ 'tabCompletionMatchers' ] ) ; } }
Load configuration values from an array of options .
13,002
public function getRuntimeDir ( ) { if ( ! isset ( $ this -> runtimeDir ) ) { $ this -> runtimeDir = ConfigPaths :: getRuntimeDir ( ) ; } if ( ! \ is_dir ( $ this -> runtimeDir ) ) { \ mkdir ( $ this -> runtimeDir , 0700 , true ) ; } return $ this -> runtimeDir ; }
Get the shell s temporary directory location .
13,003
public function getHistoryFile ( ) { if ( isset ( $ this -> historyFile ) ) { return $ this -> historyFile ; } $ files = ConfigPaths :: getConfigFiles ( [ 'psysh_history' , 'history' ] , $ this -> configDir ) ; if ( ! empty ( $ files ) ) { if ( $ this -> warnOnMultipleConfigs && \ count ( $ files ) > 1 ) { $ msg = \ sprintf ( 'Multiple history files found: %s. Using %s' , \ implode ( $ files , ', ' ) , $ files [ 0 ] ) ; \ trigger_error ( $ msg , E_USER_NOTICE ) ; } $ this -> setHistoryFile ( $ files [ 0 ] ) ; } else { $ dir = $ this -> configDir ? : ConfigPaths :: getCurrentConfigDir ( ) ; $ this -> setHistoryFile ( $ dir . '/psysh_history' ) ; } return $ this -> historyFile ; }
Get the readline history file path .
13,004
public function useReadline ( ) { return isset ( $ this -> useReadline ) ? ( $ this -> hasReadline && $ this -> useReadline ) : $ this -> hasReadline ; }
Check whether to use Readline .
13,005
public function getReadline ( ) { if ( ! isset ( $ this -> readline ) ) { $ className = $ this -> getReadlineClass ( ) ; $ this -> readline = new $ className ( $ this -> getHistoryFile ( ) , $ this -> getHistorySize ( ) , $ this -> getEraseDuplicates ( ) ) ; } return $ this -> readline ; }
Get the Psy Shell readline service .
13,006
public function usePcntl ( ) { return isset ( $ this -> usePcntl ) ? ( $ this -> hasPcntl && $ this -> usePcntl ) : $ this -> hasPcntl ; }
Check whether to use Pcntl .
13,007
public function useTabCompletion ( ) { return isset ( $ this -> useTabCompletion ) ? ( $ this -> hasReadline && $ this -> useTabCompletion ) : $ this -> hasReadline ; }
Check whether to use tab completion .
13,008
public function getOutput ( ) { if ( ! isset ( $ this -> output ) ) { $ this -> output = new ShellOutput ( ShellOutput :: VERBOSITY_NORMAL , $ this -> getOutputDecorated ( ) , null , $ this -> getPager ( ) ) ; } return $ this -> output ; }
Get a Shell Output service instance .
13,009
public function setPager ( $ pager ) { if ( $ pager && ! \ is_string ( $ pager ) && ! $ pager instanceof OutputPager ) { throw new \ InvalidArgumentException ( 'Unexpected pager instance' ) ; } $ this -> pager = $ pager ; }
Set the OutputPager service .
13,010
public function getPager ( ) { if ( ! isset ( $ this -> pager ) && $ this -> usePcntl ( ) ) { if ( $ pager = \ ini_get ( 'cli.pager' ) ) { $ this -> pager = $ pager ; } elseif ( $ less = \ exec ( 'which less 2>/dev/null' ) ) { $ this -> pager = $ less . ' -R -S -F -X' ; } } return $ this -> pager ; }
Get an OutputPager instance or a command for an external Proc pager .
13,011
public function addMatchers ( array $ matchers ) { $ this -> newMatchers = \ array_merge ( $ this -> newMatchers , $ matchers ) ; if ( isset ( $ this -> shell ) ) { $ this -> doAddMatchers ( ) ; } }
Add tab completion matchers to the AutoCompleter .
13,012
private function doAddMatchers ( ) { if ( ! empty ( $ this -> newMatchers ) ) { $ this -> shell -> addMatchers ( $ this -> newMatchers ) ; $ this -> newMatchers = [ ] ; } }
Internal method for adding tab completion matchers . This will set any new matchers once a Shell is available .
13,013
public function addCommands ( array $ commands ) { $ this -> newCommands = \ array_merge ( $ this -> newCommands , $ commands ) ; if ( isset ( $ this -> shell ) ) { $ this -> doAddCommands ( ) ; } }
Add commands to the Shell .
13,014
private function doAddCommands ( ) { if ( ! empty ( $ this -> newCommands ) ) { $ this -> shell -> addCommands ( $ this -> newCommands ) ; $ this -> newCommands = [ ] ; } }
Internal method for adding commands . This will set any new commands once a Shell is available .
13,015
public function setShell ( Shell $ shell ) { $ this -> shell = $ shell ; $ this -> doAddCommands ( ) ; $ this -> doAddMatchers ( ) ; }
Set the Shell backreference and add any new commands to the Shell .
13,016
public function getManualDbFile ( ) { if ( isset ( $ this -> manualDbFile ) ) { return $ this -> manualDbFile ; } $ files = ConfigPaths :: getDataFiles ( [ 'php_manual.sqlite' ] , $ this -> dataDir ) ; if ( ! empty ( $ files ) ) { if ( $ this -> warnOnMultipleConfigs && \ count ( $ files ) > 1 ) { $ msg = \ sprintf ( 'Multiple manual database files found: %s. Using %s' , \ implode ( $ files , ', ' ) , $ files [ 0 ] ) ; \ trigger_error ( $ msg , E_USER_NOTICE ) ; } return $ this -> manualDbFile = $ files [ 0 ] ; } }
Get the current PHP manual database file .
13,017
public function getManualDb ( ) { if ( ! isset ( $ this -> manualDb ) ) { $ dbFile = $ this -> getManualDbFile ( ) ; if ( \ is_file ( $ dbFile ) ) { try { $ this -> manualDb = new \ PDO ( 'sqlite:' . $ dbFile ) ; } catch ( \ PDOException $ e ) { if ( $ e -> getMessage ( ) === 'could not find driver' ) { throw new RuntimeException ( 'SQLite PDO driver not found' , 0 , $ e ) ; } else { throw $ e ; } } } } return $ this -> manualDb ; }
Get a PHP manual database connection .
13,018
public function getPresenter ( ) { if ( ! isset ( $ this -> presenter ) ) { $ this -> presenter = new Presenter ( $ this -> getOutput ( ) -> getFormatter ( ) , $ this -> forceArrayIndexes ( ) ) ; } return $ this -> presenter ; }
Get the Presenter service .
13,019
public function setColorMode ( $ colorMode ) { $ validColorModes = [ self :: COLOR_MODE_AUTO , self :: COLOR_MODE_FORCED , self :: COLOR_MODE_DISABLED , ] ; if ( \ in_array ( $ colorMode , $ validColorModes ) ) { $ this -> colorMode = $ colorMode ; } else { throw new \ InvalidArgumentException ( 'invalid color mode: ' . $ colorMode ) ; } }
Set the current color mode .
13,020
public function getChecker ( ) { if ( ! isset ( $ this -> checker ) ) { $ interval = $ this -> getUpdateCheck ( ) ; switch ( $ interval ) { case Checker :: ALWAYS : $ this -> checker = new GitHubChecker ( ) ; break ; case Checker :: DAILY : case Checker :: WEEKLY : case Checker :: MONTHLY : $ checkFile = $ this -> getUpdateCheckCacheFile ( ) ; if ( $ checkFile === false ) { $ this -> checker = new NoopChecker ( ) ; } else { $ this -> checker = new IntervalChecker ( $ checkFile , $ interval ) ; } break ; case Checker :: NEVER : $ this -> checker = new NoopChecker ( ) ; break ; } } return $ this -> checker ; }
Get an update checker service instance .
13,021
public function setUpdateCheck ( $ interval ) { $ validIntervals = [ Checker :: ALWAYS , Checker :: DAILY , Checker :: WEEKLY , Checker :: MONTHLY , Checker :: NEVER , ] ; if ( ! \ in_array ( $ interval , $ validIntervals ) ) { throw new \ InvalidArgumentException ( 'invalid update check interval: ' . $ interval ) ; } $ this -> updateCheck = $ interval ; }
Set the update check interval .
13,022
private function parse ( $ code ) { try { return $ this -> parser -> parse ( $ code ) ; } catch ( \ PhpParser \ Error $ e ) { if ( \ strpos ( $ e -> getMessage ( ) , 'unexpected EOF' ) === false ) { throw $ e ; } return $ this -> parser -> parse ( $ code . ';' ) ; } }
Lex and parse a string of code into statements .
13,023
public function run ( Shell $ shell ) { $ this -> loadIncludes ( $ shell ) ; $ closure = new ExecutionLoopClosure ( $ shell ) ; $ closure -> execute ( ) ; }
Run the execution loop .
13,024
protected function loadIncludes ( Shell $ shell ) { $ load = function ( Shell $ __psysh__ ) { \ set_error_handler ( [ $ __psysh__ , 'handleError' ] ) ; foreach ( $ __psysh__ -> getIncludes ( ) as $ __psysh_include__ ) { try { include $ __psysh_include__ ; } catch ( \ Error $ _e ) { $ __psysh__ -> writeException ( ErrorException :: fromError ( $ _e ) ) ; } catch ( \ Exception $ _e ) { $ __psysh__ -> writeException ( $ _e ) ; } } \ restore_error_handler ( ) ; unset ( $ __psysh_include__ ) ; \ extract ( $ __psysh__ -> getScopeVariables ( false ) ) ; $ __psysh__ -> setScopeVariables ( \ get_defined_vars ( ) ) ; } ; $ load ( $ shell ) ; }
Load user - defined includes .
13,025
public function beforeTraverse ( array $ nodes ) { if ( ! $ this -> atLeastPhp7 ) { return ; } $ prependStrictTypes = $ this -> strictTypes ; foreach ( $ nodes as $ key => $ node ) { if ( $ node instanceof Declare_ ) { foreach ( $ node -> declares as $ declare ) { $ declareKey = $ declare -> key instanceof Identifier ? $ declare -> key -> toString ( ) : $ declare -> key ; if ( $ declareKey === 'strict_types' ) { $ value = $ declare -> value ; if ( ! $ value instanceof LNumber || ( $ value -> value !== 0 && $ value -> value !== 1 ) ) { throw new FatalErrorException ( self :: EXCEPTION_MESSAGE , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } $ this -> strictTypes = $ value -> value === 1 ; } } } } if ( $ prependStrictTypes ) { $ first = \ reset ( $ nodes ) ; if ( ! $ first instanceof Declare_ ) { $ declare = new Declare_ ( [ new DeclareDeclare ( 'strict_types' , new LNumber ( 1 ) ) ] ) ; \ array_unshift ( $ nodes , $ declare ) ; } } return $ nodes ; }
If this is a standalone strict types declaration remember it for later .
13,026
public static function get ( $ value , $ member = null , $ filter = 15 ) { if ( $ member === null && \ is_string ( $ value ) ) { if ( \ function_exists ( $ value ) ) { return new \ ReflectionFunction ( $ value ) ; } elseif ( \ defined ( $ value ) || ReflectionConstant_ :: isMagicConstant ( $ value ) ) { return new ReflectionConstant_ ( $ value ) ; } } $ class = self :: getClass ( $ value ) ; if ( $ member === null ) { return $ class ; } elseif ( $ filter & self :: CONSTANT && $ class -> hasConstant ( $ member ) ) { return ReflectionClassConstant :: create ( $ value , $ member ) ; } elseif ( $ filter & self :: METHOD && $ class -> hasMethod ( $ member ) ) { return $ class -> getMethod ( $ member ) ; } elseif ( $ filter & self :: PROPERTY && $ class -> hasProperty ( $ member ) ) { return $ class -> getProperty ( $ member ) ; } elseif ( $ filter & self :: STATIC_PROPERTY && $ class -> hasProperty ( $ member ) && $ class -> getProperty ( $ member ) -> isStatic ( ) ) { return $ class -> getProperty ( $ member ) ; } else { throw new RuntimeException ( \ sprintf ( 'Unknown member %s on class %s' , $ member , \ is_object ( $ value ) ? \ get_class ( $ value ) : $ value ) ) ; } }
Get a Reflector for a function class or instance constant method or property .
13,027
protected function prepareInterfaces ( array $ interfaces ) { \ natcasesort ( $ interfaces ) ; $ ret = [ ] ; foreach ( $ interfaces as $ name ) { if ( $ this -> showItem ( $ name ) ) { $ ret [ $ name ] = [ 'name' => $ name , 'style' => self :: IS_CLASS , 'value' => $ this -> presentSignature ( $ name ) , ] ; } } return $ ret ; }
Prepare formatted interface array .
13,028
public function enterNode ( Node $ node ) { if ( $ this -> atLeastPhp55 ) { return ; } if ( ! $ node instanceof Empty_ ) { return ; } if ( ! $ node -> expr instanceof Variable ) { $ msg = \ sprintf ( 'syntax error, unexpected %s' , $ this -> getUnexpectedThing ( $ node -> expr ) ) ; throw new ParseErrorException ( $ msg , $ node -> expr -> getLine ( ) ) ; } }
Validate use of empty in PHP < 5 . 5 .
13,029
private function prepareArgs ( $ code = null ) { if ( ! $ code ) { return [ new Arg ( new Variable ( '_e' ) ) ] ; } if ( \ strpos ( '<?' , $ code ) === false ) { $ code = '<?php ' . $ code ; } $ nodes = $ this -> parse ( $ code ) ; if ( \ count ( $ nodes ) !== 1 ) { throw new \ InvalidArgumentException ( 'No idea how to throw this' ) ; } $ node = $ nodes [ 0 ] ; $ expr = isset ( $ node -> expr ) ? $ node -> expr : $ node ; $ args = [ new Arg ( $ expr , false , false , $ node -> getAttributes ( ) ) ] ; if ( $ expr instanceof String_ ) { return [ new New_ ( new FullyQualifiedName ( 'Exception' ) , $ args ) ] ; } return $ args ; }
Parse the supplied command argument .
13,030
protected function initEnumerators ( ) { if ( ! isset ( $ this -> enumerators ) ) { $ mgr = $ this -> presenter ; $ this -> enumerators = [ new ClassConstantEnumerator ( $ mgr ) , new ClassEnumerator ( $ mgr ) , new ConstantEnumerator ( $ mgr ) , new FunctionEnumerator ( $ mgr ) , new GlobalVariableEnumerator ( $ mgr ) , new PropertyEnumerator ( $ mgr ) , new MethodEnumerator ( $ mgr ) , new VariableEnumerator ( $ mgr , $ this -> context ) , ] ; } }
Initialize Enumerators .
13,031
private function validateInput ( InputInterface $ input ) { if ( ! $ input -> getArgument ( 'target' ) ) { foreach ( [ 'properties' , 'methods' , 'no-inherit' ] as $ option ) { if ( $ input -> getOption ( $ option ) ) { throw new RuntimeException ( '--' . $ option . ' does not make sense without a specified target' ) ; } } foreach ( [ 'globals' , 'vars' , 'constants' , 'functions' , 'classes' , 'interfaces' , 'traits' ] as $ option ) { if ( $ input -> getOption ( $ option ) ) { return ; } } $ input -> setOption ( 'vars' , true ) ; } else { foreach ( [ 'vars' , 'globals' , 'functions' , 'classes' , 'interfaces' , 'traits' ] as $ option ) { if ( $ input -> getOption ( $ option ) ) { throw new RuntimeException ( '--' . $ option . ' does not make sense with a specified target' ) ; } } foreach ( [ 'constants' , 'properties' , 'methods' ] as $ option ) { if ( $ input -> getOption ( $ option ) ) { return ; } } $ input -> setOption ( 'constants' , true ) ; $ input -> setOption ( 'properties' , true ) ; $ input -> setOption ( 'methods' , true ) ; } }
Validate that input options make sense provide defaults when called without options .
13,032
private function getEndCall ( Expr $ arg = null ) { if ( $ arg === null ) { $ arg = NoReturnValue :: create ( ) ; } return new StaticCall ( new FullyQualifiedName ( 'Psy\Command\TimeitCommand' ) , 'markEnd' , [ new Arg ( $ arg ) ] ) ; }
Get PhpParser AST nodes for a markEnd call .
13,033
public function setPresenter ( Presenter $ presenter ) { $ this -> presenter = clone $ presenter ; $ this -> presenter -> addCasters ( [ 'PhpParser\Node' => function ( Node $ node , array $ a ) { $ a = [ Caster :: PREFIX_VIRTUAL . 'type' => $ node -> getType ( ) , Caster :: PREFIX_VIRTUAL . 'attributes' => $ node -> getAttributes ( ) , ] ; foreach ( $ node -> getSubNodeNames ( ) as $ name ) { $ a [ Caster :: PREFIX_VIRTUAL . $ name ] = $ node -> $ name ; } return $ a ; } , ] ) ; }
PresenterAware interface .
13,034
public function beforeTraverse ( array $ nodes ) { if ( empty ( $ nodes ) ) { return $ nodes ; } $ last = \ end ( $ nodes ) ; if ( $ last instanceof Namespace_ ) { $ kind = $ last -> getAttribute ( 'kind' ) ; if ( $ kind === null || $ kind === Namespace_ :: KIND_SEMICOLON ) { $ this -> setNamespace ( $ last -> name ) ; } else { $ this -> setNamespace ( null ) ; } return $ nodes ; } return $ this -> namespace ? [ new Namespace_ ( $ this -> namespace , $ nodes ) ] : $ nodes ; }
If this is a standalone namespace line remember it for later .
13,035
public function enterNode ( Node $ node ) { if ( ! $ node instanceof Assign ) { return ; } if ( ! $ node -> var instanceof Array_ && ! $ node -> var instanceof List_ ) { return ; } if ( ! $ this -> atLeastPhp71 && $ node -> var instanceof Array_ ) { $ msg = "syntax error, unexpected '='" ; throw new ParseErrorException ( $ msg , $ node -> expr -> getLine ( ) ) ; } $ items = isset ( $ node -> var -> items ) ? $ node -> var -> items : $ node -> var -> vars ; if ( $ items === [ ] || $ items === [ null ] ) { throw new ParseErrorException ( 'Cannot use empty list' , $ node -> var -> getLine ( ) ) ; } $ itemFound = false ; foreach ( $ items as $ item ) { if ( $ item === null ) { continue ; } $ itemFound = true ; if ( ! $ this -> atLeastPhp71 && $ item instanceof ArrayItem && $ item -> key !== null ) { $ msg = 'Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting \',\' or \')\'' ; throw new ParseErrorException ( $ msg , $ item -> key -> getLine ( ) ) ; } if ( ! self :: isValidArrayItem ( $ item ) ) { $ msg = 'Assignments can only happen to writable values' ; throw new ParseErrorException ( $ msg , $ item -> getLine ( ) ) ; } } if ( ! $ itemFound ) { throw new ParseErrorException ( 'Cannot use empty list' ) ; } }
Validate use of list assignment .
13,036
private static function isValidArrayItem ( Expr $ item ) { $ value = ( $ item instanceof ArrayItem ) ? $ item -> value : $ item ; while ( $ value instanceof ArrayDimFetch || $ value instanceof PropertyFetch ) { $ value = $ value -> var ; } return $ value instanceof Variable || $ value instanceof MethodCall || $ value instanceof FuncCall ; }
Validate whether a given item in an array is valid for short assignment .
13,037
protected function getVariables ( $ showAll ) { $ scopeVars = $ this -> context -> getAll ( ) ; \ uksort ( $ scopeVars , function ( $ a , $ b ) { $ aIndex = \ array_search ( $ a , self :: $ specialNames ) ; $ bIndex = \ array_search ( $ b , self :: $ specialNames ) ; if ( $ aIndex !== false ) { if ( $ bIndex !== false ) { return $ aIndex - $ bIndex ; } return 1 ; } if ( $ bIndex !== false ) { return - 1 ; } return \ strnatcasecmp ( $ a , $ b ) ; } ) ; $ ret = [ ] ; foreach ( $ scopeVars as $ name => $ val ) { if ( ! $ showAll && \ in_array ( $ name , self :: $ specialNames ) ) { continue ; } $ ret [ $ name ] = $ val ; } return $ ret ; }
Get scope variables .
13,038
protected function prepareVariables ( array $ variables ) { $ ret = [ ] ; foreach ( $ variables as $ name => $ val ) { if ( $ this -> showItem ( $ name ) ) { $ fname = '$' . $ name ; $ ret [ $ fname ] = [ 'name' => $ fname , 'style' => \ in_array ( $ name , self :: $ specialNames ) ? self :: IS_PRIVATE : self :: IS_PUBLIC , 'value' => $ this -> presentRef ( $ val ) , ] ; } } return $ ret ; }
Prepare formatted variable array .
13,039
public static function fromError ( \ Error $ e ) { return new self ( $ e -> getMessage ( ) , $ e -> getCode ( ) , 1 , $ e -> getFile ( ) , $ e -> getLine ( ) , $ e ) ; }
Create an ErrorException from an Error .
13,040
private function extractRange ( $ range ) { if ( \ preg_match ( '/^\d+$/' , $ range ) ) { return [ $ range , $ range + 1 ] ; } $ matches = [ ] ; if ( $ range !== '..' && \ preg_match ( '/^(\d*)\.\.(\d*)$/' , $ range , $ matches ) ) { $ start = $ matches [ 1 ] ? \ intval ( $ matches [ 1 ] ) : 0 ; $ end = $ matches [ 2 ] ? \ intval ( $ matches [ 2 ] ) + 1 : PHP_INT_MAX ; return [ $ start , $ end ] ; } throw new \ InvalidArgumentException ( 'Unexpected range: ' . $ range ) ; }
Extract a range from a string .
13,041
private function getHistorySlice ( $ show , $ head , $ tail ) { $ history = $ this -> readline -> listHistory ( ) ; \ array_pop ( $ history ) ; if ( $ show ) { list ( $ start , $ end ) = $ this -> extractRange ( $ show ) ; $ length = $ end - $ start ; } elseif ( $ head ) { if ( ! \ preg_match ( '/^\d+$/' , $ head ) ) { throw new \ InvalidArgumentException ( 'Please specify an integer argument for --head' ) ; } $ start = 0 ; $ length = \ intval ( $ head ) ; } elseif ( $ tail ) { if ( ! \ preg_match ( '/^\d+$/' , $ tail ) ) { throw new \ InvalidArgumentException ( 'Please specify an integer argument for --tail' ) ; } $ start = \ count ( $ history ) - $ tail ; $ length = \ intval ( $ tail ) + 1 ; } else { return $ history ; } return \ array_slice ( $ history , $ start , $ length , true ) ; }
Retrieve a slice of the readline history .
13,042
public function beforeRun ( Shell $ shell ) { list ( $ up , $ down ) = \ stream_socket_pair ( STREAM_PF_UNIX , STREAM_SOCK_STREAM , STREAM_IPPROTO_IP ) ; if ( ! $ up ) { throw new \ RuntimeException ( 'Unable to create socket pair' ) ; } $ pid = \ pcntl_fork ( ) ; if ( $ pid < 0 ) { throw new \ RuntimeException ( 'Unable to start execution loop' ) ; } elseif ( $ pid > 0 ) { \ fclose ( $ up ) ; $ read = [ $ down ] ; $ write = null ; $ except = null ; do { $ n = @ \ stream_select ( $ read , $ write , $ except , null ) ; if ( $ n === 0 ) { throw new \ RuntimeException ( 'Process timed out waiting for execution loop' ) ; } if ( $ n === false ) { $ err = \ error_get_last ( ) ; if ( ! isset ( $ err [ 'message' ] ) || \ stripos ( $ err [ 'message' ] , 'interrupted system call' ) === false ) { $ msg = $ err [ 'message' ] ? \ sprintf ( 'Error waiting for execution loop: %s' , $ err [ 'message' ] ) : 'Error waiting for execution loop' ; throw new \ RuntimeException ( $ msg ) ; } } } while ( $ n < 1 ) ; $ content = \ stream_get_contents ( $ down ) ; \ fclose ( $ down ) ; if ( $ content ) { $ shell -> setScopeVariables ( @ \ unserialize ( $ content ) ) ; } throw new BreakException ( 'Exiting main thread' ) ; } if ( \ function_exists ( 'setproctitle' ) ) { setproctitle ( 'psysh (loop)' ) ; } \ fclose ( $ down ) ; $ this -> up = $ up ; }
Forks into a master and a loop process .
13,043
public function afterLoop ( Shell $ shell ) { if ( isset ( $ this -> savegame ) ) { \ posix_kill ( $ this -> savegame , SIGKILL ) ; \ pcntl_signal_dispatch ( ) ; } }
Clean up old savegames at the end of each loop iteration .
13,044
private function createSavegame ( ) { $ this -> savegame = \ posix_getpid ( ) ; $ pid = \ pcntl_fork ( ) ; if ( $ pid < 0 ) { throw new \ RuntimeException ( 'Unable to create savegame fork' ) ; } elseif ( $ pid > 0 ) { \ pcntl_waitpid ( $ pid , $ status ) ; if ( ! \ pcntl_wexitstatus ( $ status ) ) { \ posix_kill ( \ posix_getpid ( ) , SIGKILL ) ; } $ this -> createSavegame ( ) ; } }
Create a savegame fork .
13,045
private function serializeReturn ( array $ return ) { $ serializable = [ ] ; foreach ( $ return as $ key => $ value ) { if ( Context :: isSpecialVariableName ( $ key ) ) { continue ; } if ( \ is_resource ( $ value ) || $ value instanceof \ Closure ) { continue ; } try { @ \ serialize ( $ value ) ; $ serializable [ $ key ] = $ value ; } catch ( \ Throwable $ e ) { } catch ( \ Exception $ e ) { } } return @ \ serialize ( $ serializable ) ; }
Serialize all serializable return values .
13,046
private function argumentsAsText ( ) { $ max = $ this -> getMaxWidth ( ) ; $ messages = [ ] ; $ arguments = $ this -> getArguments ( ) ; if ( ! empty ( $ arguments ) ) { $ messages [ ] = '<comment>Arguments:</comment>' ; foreach ( $ arguments as $ argument ) { if ( null !== $ argument -> getDefault ( ) && ( ! \ is_array ( $ argument -> getDefault ( ) ) || \ count ( $ argument -> getDefault ( ) ) ) ) { $ default = \ sprintf ( '<comment> (default: %s)</comment>' , $ this -> formatDefaultValue ( $ argument -> getDefault ( ) ) ) ; } else { $ default = '' ; } $ description = \ str_replace ( "\n" , "\n" . \ str_pad ( '' , $ max + 2 , ' ' ) , $ argument -> getDescription ( ) ) ; $ messages [ ] = \ sprintf ( " <info>%-${max}s</info> %s%s" , $ argument -> getName ( ) , $ description , $ default ) ; } $ messages [ ] = '' ; } return \ implode ( PHP_EOL , $ messages ) ; }
Format command arguments as text .
13,047
private function optionsAsText ( ) { $ max = $ this -> getMaxWidth ( ) ; $ messages = [ ] ; $ options = $ this -> getOptions ( ) ; if ( $ options ) { $ messages [ ] = '<comment>Options:</comment>' ; foreach ( $ options as $ option ) { if ( $ option -> acceptValue ( ) && null !== $ option -> getDefault ( ) && ( ! \ is_array ( $ option -> getDefault ( ) ) || \ count ( $ option -> getDefault ( ) ) ) ) { $ default = \ sprintf ( '<comment> (default: %s)</comment>' , $ this -> formatDefaultValue ( $ option -> getDefault ( ) ) ) ; } else { $ default = '' ; } $ multiple = $ option -> isArray ( ) ? '<comment> (multiple values allowed)</comment>' : '' ; $ description = \ str_replace ( "\n" , "\n" . \ str_pad ( '' , $ max + 2 , ' ' ) , $ option -> getDescription ( ) ) ; $ optionMax = $ max - \ strlen ( $ option -> getName ( ) ) - 2 ; $ messages [ ] = \ sprintf ( " <info>%s</info> %-${optionMax}s%s%s%s" , '--' . $ option -> getName ( ) , $ option -> getShortcut ( ) ? \ sprintf ( '(-%s) ' , $ option -> getShortcut ( ) ) : '' , $ description , $ default , $ multiple ) ; } $ messages [ ] = '' ; } return \ implode ( PHP_EOL , $ messages ) ; }
Format options as text .
13,048
private function getMaxWidth ( ) { $ max = 0 ; foreach ( $ this -> getOptions ( ) as $ option ) { $ nameLength = \ strlen ( $ option -> getName ( ) ) + 2 ; if ( $ option -> getShortcut ( ) ) { $ nameLength += \ strlen ( $ option -> getShortcut ( ) ) + 3 ; } $ max = \ max ( $ max , $ nameLength ) ; } foreach ( $ this -> getArguments ( ) as $ argument ) { $ max = \ max ( $ max , \ strlen ( $ argument -> getName ( ) ) ) ; } return ++ $ max ; }
Calculate the maximum padding width for a set of lines .
13,049
protected function getTable ( OutputInterface $ output ) { if ( ! \ class_exists ( 'Symfony\Component\Console\Helper\Table' ) ) { return $ this -> getTableHelper ( ) ; } $ style = new TableStyle ( ) ; $ style -> setVerticalBorderChar ( ' ' ) -> setHorizontalBorderChar ( '' ) -> setCrossingChar ( '' ) ; $ table = new Table ( $ output ) ; return $ table -> setRows ( [ ] ) -> setStyle ( $ style ) ; }
Get a Table instance .
13,050
protected function getTableHelper ( ) { $ table = $ this -> getApplication ( ) -> getHelperSet ( ) -> get ( 'table' ) ; return $ table -> setRows ( [ ] ) -> setLayout ( TableHelper :: LAYOUT_BORDERLESS ) -> setHorizontalBorderChar ( '' ) -> setCrossingChar ( '' ) ; }
Legacy fallback for getTable .
13,051
public static function getOptions ( ) { return [ new InputOption ( 'grep' , 'G' , InputOption :: VALUE_REQUIRED , 'Limit to items matching the given pattern (string or regex).' ) , new InputOption ( 'insensitive' , 'i' , InputOption :: VALUE_NONE , 'Case-insensitive search (requires --grep).' ) , new InputOption ( 'invert' , 'v' , InputOption :: VALUE_NONE , 'Inverted search (requires --grep).' ) , ] ; }
Get input option definitions for filtering .
13,052
public function bind ( InputInterface $ input ) { $ this -> validateInput ( $ input ) ; if ( ! $ pattern = $ input -> getOption ( 'grep' ) ) { $ this -> filter = false ; return ; } if ( ! $ this -> stringIsRegex ( $ pattern ) ) { $ pattern = '/' . \ preg_quote ( $ pattern , '/' ) . '/' ; } if ( $ insensitive = $ input -> getOption ( 'insensitive' ) ) { $ pattern .= 'i' ; } $ this -> validateRegex ( $ pattern ) ; $ this -> filter = true ; $ this -> pattern = $ pattern ; $ this -> insensitive = $ insensitive ; $ this -> invert = $ input -> getOption ( 'invert' ) ; }
Bind input and prepare filter .
13,053
public function match ( $ string , array & $ matches = null ) { return $ this -> filter === false || ( \ preg_match ( $ this -> pattern , $ string , $ matches ) xor $ this -> invert ) ; }
Check whether a string matches the current filter options .
13,054
private function validateInput ( InputInterface $ input ) { if ( ! $ input -> getOption ( 'grep' ) ) { foreach ( [ 'invert' , 'insensitive' ] as $ option ) { if ( $ input -> getOption ( $ option ) ) { throw new RuntimeException ( '--' . $ option . ' does not make sense without --grep' ) ; } } } }
Validate that grep invert and insensitive input options are consistent .
13,055
public function close ( ) { if ( isset ( $ this -> pipe ) ) { \ fclose ( $ this -> pipe ) ; } if ( isset ( $ this -> proc ) ) { $ exit = \ proc_close ( $ this -> proc ) ; if ( $ exit !== 0 ) { throw new \ RuntimeException ( 'Error closing output stream' ) ; } } unset ( $ this -> pipe , $ this -> proc ) ; }
Close the current pager process .
13,056
private function getPipe ( ) { if ( ! isset ( $ this -> pipe ) || ! isset ( $ this -> proc ) ) { $ desc = [ [ 'pipe' , 'r' ] , $ this -> stream , \ fopen ( 'php://stderr' , 'w' ) ] ; $ this -> proc = \ proc_open ( $ this -> cmd , $ desc , $ pipes ) ; if ( ! \ is_resource ( $ this -> proc ) ) { throw new \ RuntimeException ( 'Error opening output stream' ) ; } $ this -> pipe = $ pipes [ 0 ] ; } return $ this -> pipe ; }
Get a pipe for paging output .
13,057
private static function isNonExpressionStmt ( Node $ node ) { return $ node instanceof Stmt && ! $ node instanceof Expression && ! $ node instanceof Return_ && ! $ node instanceof Namespace_ ; }
Check whether a given node is a non - expression statement .
13,058
protected function getMethods ( $ showAll , \ Reflector $ reflector , $ noInherit = false ) { $ className = $ reflector -> getName ( ) ; $ methods = [ ] ; foreach ( $ reflector -> getMethods ( ) as $ name => $ method ) { if ( $ noInherit && $ method -> getDeclaringClass ( ) -> getName ( ) !== $ className ) { continue ; } if ( $ showAll || $ method -> isPublic ( ) ) { $ methods [ $ method -> getName ( ) ] = $ method ; } } \ ksort ( $ methods , SORT_NATURAL | SORT_FLAG_CASE ) ; return $ methods ; }
Get defined methods for the given class or object Reflector .
13,059
protected function prepareMethods ( array $ methods ) { $ ret = [ ] ; foreach ( $ methods as $ name => $ method ) { if ( $ this -> showItem ( $ name ) ) { $ ret [ $ name ] = [ 'name' => $ name , 'style' => $ this -> getVisibilityStyle ( $ method ) , 'value' => $ this -> presentSignature ( $ method ) , ] ; } } return $ ret ; }
Prepare formatted method array .
13,060
private function getVisibilityStyle ( \ ReflectionMethod $ method ) { if ( $ method -> isPublic ( ) ) { return self :: IS_PUBLIC ; } elseif ( $ method -> isProtected ( ) ) { return self :: IS_PROTECTED ; } else { return self :: IS_PRIVATE ; } }
Get output style for the given method s visibility .
13,061
protected function setClosure ( Shell $ shell , \ Closure $ closure ) { if ( self :: shouldBindClosure ( ) ) { $ that = $ shell -> getBoundObject ( ) ; if ( \ is_object ( $ that ) ) { $ closure = $ closure -> bindTo ( $ that , \ get_class ( $ that ) ) ; } else { $ closure = $ closure -> bindTo ( null , $ shell -> getBoundClass ( ) ) ; } } $ this -> closure = $ closure ; }
Set the closure instance .
13,062
public function enterNode ( Node $ node ) { if ( ! $ node instanceof FuncCall && ! $ node instanceof MethodCall && ! $ node instanceof StaticCall ) { return ; } foreach ( $ node -> args as $ arg ) { if ( $ arg -> byRef ) { throw new FatalErrorException ( self :: EXCEPTION_MESSAGE , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } } }
Validate of use call - time pass - by - reference .
13,063
protected function trace ( ) { foreach ( \ array_reverse ( $ this -> backtrace ) as $ stackFrame ) { if ( $ this -> isDebugCall ( $ stackFrame ) ) { return $ stackFrame ; } } return \ end ( $ this -> backtrace ) ; }
Obtains the correct stack frame in the full backtrace .
13,064
protected function fileInfo ( ) { $ stackFrame = $ this -> trace ( ) ; if ( \ preg_match ( '/eval\(/' , $ stackFrame [ 'file' ] ) ) { \ preg_match_all ( '/([^\(]+)\((\d+)/' , $ stackFrame [ 'file' ] , $ matches ) ; $ file = $ matches [ 1 ] [ 0 ] ; $ line = ( int ) $ matches [ 2 ] [ 0 ] ; } else { $ file = $ stackFrame [ 'file' ] ; $ line = $ stackFrame [ 'line' ] ; } return \ compact ( 'file' , 'line' ) ; }
Determine the file and line based on the specific backtrace .
13,065
protected function getProperties ( $ showAll , \ Reflector $ reflector , $ noInherit = false ) { $ className = $ reflector -> getName ( ) ; $ properties = [ ] ; foreach ( $ reflector -> getProperties ( ) as $ property ) { if ( $ noInherit && $ property -> getDeclaringClass ( ) -> getName ( ) !== $ className ) { continue ; } if ( $ showAll || $ property -> isPublic ( ) ) { $ properties [ $ property -> getName ( ) ] = $ property ; } } \ ksort ( $ properties , SORT_NATURAL | SORT_FLAG_CASE ) ; return $ properties ; }
Get defined properties for the given class or object Reflector .
13,066
protected function prepareProperties ( array $ properties , $ target = null ) { $ ret = [ ] ; foreach ( $ properties as $ name => $ property ) { if ( $ this -> showItem ( $ name ) ) { $ fname = '$' . $ name ; $ ret [ $ fname ] = [ 'name' => $ fname , 'style' => $ this -> getVisibilityStyle ( $ property ) , 'value' => $ this -> presentValue ( $ property , $ target ) , ] ; } } return $ ret ; }
Prepare formatted property array .
13,067
private function getVisibilityStyle ( \ ReflectionProperty $ property ) { if ( $ property -> isPublic ( ) ) { return self :: IS_PUBLIC ; } elseif ( $ property -> isProtected ( ) ) { return self :: IS_PROTECTED ; } else { return self :: IS_PRIVATE ; } }
Get output style for the given property s visibility .
13,068
protected function getFunctions ( $ type = null ) { $ funcs = \ get_defined_functions ( ) ; if ( $ type ) { return $ funcs [ $ type ] ; } else { return \ array_merge ( $ funcs [ 'internal' ] , $ funcs [ 'user' ] ) ; } }
Get defined functions .
13,069
protected function prepareFunctions ( array $ functions ) { \ natcasesort ( $ functions ) ; $ ret = [ ] ; foreach ( $ functions as $ name ) { if ( $ this -> showItem ( $ name ) ) { $ ret [ $ name ] = [ 'name' => $ name , 'style' => self :: IS_FUNCTION , 'value' => $ this -> presentSignature ( $ name ) , ] ; } } return $ ret ; }
Prepare formatted function array .
13,070
private function tokenize ( $ input ) { $ tokens = [ ] ; $ length = \ strlen ( $ input ) ; $ cursor = 0 ; while ( $ cursor < $ length ) { if ( \ preg_match ( '/\s+/A' , $ input , $ match , null , $ cursor ) ) { } elseif ( \ preg_match ( '/([^="\'\s]+?)(=?)(' . StringInput :: REGEX_QUOTED_STRING . '+)/A' , $ input , $ match , null , $ cursor ) ) { $ tokens [ ] = [ $ match [ 1 ] . $ match [ 2 ] . \ stripcslashes ( \ str_replace ( [ '"\'' , '\'"' , '\'\'' , '""' ] , '' , \ substr ( $ match [ 3 ] , 1 , \ strlen ( $ match [ 3 ] ) - 2 ) ) ) , \ stripcslashes ( \ substr ( $ input , $ cursor ) ) , ] ; } elseif ( \ preg_match ( '/' . StringInput :: REGEX_QUOTED_STRING . '/A' , $ input , $ match , null , $ cursor ) ) { $ tokens [ ] = [ \ stripcslashes ( \ substr ( $ match [ 0 ] , 1 , \ strlen ( $ match [ 0 ] ) - 2 ) ) , \ stripcslashes ( \ substr ( $ input , $ cursor ) ) , ] ; } elseif ( \ preg_match ( '/' . StringInput :: REGEX_STRING . '/A' , $ input , $ match , null , $ cursor ) ) { $ tokens [ ] = [ \ stripcslashes ( $ match [ 1 ] ) , \ stripcslashes ( \ substr ( $ input , $ cursor ) ) , ] ; } else { throw new \ InvalidArgumentException ( \ sprintf ( 'Unable to parse input near "... %s ..."' , \ substr ( $ input , $ cursor , 10 ) ) ) ; } $ cursor += \ strlen ( $ match [ 0 ] ) ; } return $ tokens ; }
Tokenizes a string .
13,071
protected function parse ( ) { $ parseOptions = true ; $ this -> parsed = $ this -> tokenPairs ; while ( null !== $ tokenPair = \ array_shift ( $ this -> parsed ) ) { list ( $ token , $ rest ) = $ tokenPair ; if ( $ parseOptions && '' === $ token ) { $ this -> parseShellArgument ( $ token , $ rest ) ; } elseif ( $ parseOptions && '--' === $ token ) { $ parseOptions = false ; } elseif ( $ parseOptions && 0 === \ strpos ( $ token , '--' ) ) { $ this -> parseLongOption ( $ token ) ; } elseif ( $ parseOptions && '-' === $ token [ 0 ] && '-' !== $ token ) { $ this -> parseShortOption ( $ token ) ; } else { $ this -> parseShellArgument ( $ token , $ rest ) ; } } }
Same as parent but with some bonus handling for code arguments .
13,072
private function parseShellArgument ( $ token , $ rest ) { $ c = \ count ( $ this -> arguments ) ; if ( $ this -> definition -> hasArgument ( $ c ) ) { $ arg = $ this -> definition -> getArgument ( $ c ) ; if ( $ arg instanceof CodeArgument ) { $ this -> parsed = [ ] ; $ this -> arguments [ $ arg -> getName ( ) ] = $ rest ; } else { $ this -> arguments [ $ arg -> getName ( ) ] = $ arg -> isArray ( ) ? [ $ token ] : $ token ; } return ; } if ( $ this -> definition -> hasArgument ( $ c - 1 ) && $ this -> definition -> getArgument ( $ c - 1 ) -> isArray ( ) ) { $ arg = $ this -> definition -> getArgument ( $ c - 1 ) ; $ this -> arguments [ $ arg -> getName ( ) ] [ ] = $ token ; return ; } $ all = $ this -> definition -> getArguments ( ) ; if ( \ count ( $ all ) ) { throw new \ RuntimeException ( \ sprintf ( 'Too many arguments, expected arguments "%s".' , \ implode ( '" "' , \ array_keys ( $ all ) ) ) ) ; } throw new \ RuntimeException ( \ sprintf ( 'No arguments expected, got "%s".' , $ token ) ) ; }
Parses an argument with bonus handling for code arguments .
13,073
public function enterNode ( Node $ node ) { if ( ! $ node instanceof Instanceof_ ) { return ; } if ( ( $ node -> expr instanceof Scalar && ! $ node -> expr instanceof Encapsed ) || $ node -> expr instanceof ConstFetch ) { throw new FatalErrorException ( self :: EXCEPTION_MSG , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } }
Validate that the instanceof statement does not receive a scalar value or a non - class constant .
13,074
public static function markEnd ( $ ret = null ) { self :: $ times [ ] = \ microtime ( true ) - self :: $ start ; self :: $ start = null ; return $ ret ; }
Internal method for marking the end of timeit execution .
13,075
private function instrumentCode ( $ code ) { return $ this -> printer -> prettyPrint ( $ this -> traverser -> traverse ( $ this -> parse ( $ code ) ) ) ; }
Instrument code for timeit execution .
13,076
protected function getInput ( array $ tokens ) { $ var = '' ; $ firstToken = \ array_pop ( $ tokens ) ; if ( self :: tokenIs ( $ firstToken , self :: T_STRING ) ) { $ var = $ firstToken [ 1 ] ; } return $ var ; }
Get current readline input word .
13,077
public function getParameters ( ) { $ params = [ ] ; foreach ( self :: $ languageConstructs [ $ this -> keyword ] as $ parameter => $ opts ) { \ array_push ( $ params , new ReflectionLanguageConstructParameter ( $ this -> keyword , $ parameter , $ opts ) ) ; } return $ params ; }
Get language construct params .
13,078
public function present ( $ value , $ depth = null , $ options = 0 ) { $ data = $ this -> cloner -> cloneVar ( $ value , ! ( $ options & self :: VERBOSE ) ? Caster :: EXCLUDE_VERBOSE : 0 ) ; if ( null !== $ depth ) { $ data = $ data -> withMaxDepth ( $ depth ) ; } $ oldLocale = \ setlocale ( LC_NUMERIC , 0 ) ; \ setlocale ( LC_NUMERIC , 'C' ) ; $ output = '' ; $ this -> dumper -> dump ( $ data , function ( $ line , $ depth ) use ( & $ output ) { if ( $ depth >= 0 ) { if ( '' !== $ output ) { $ output .= PHP_EOL ; } $ output .= \ str_repeat ( ' ' , $ depth ) . $ line ; } } ) ; \ setlocale ( LC_NUMERIC , $ oldLocale ) ; return OutputFormatter :: escape ( $ output ) ; }
Present a full representation of the value .
13,079
protected function filterClasses ( $ key , $ classes , $ internal , $ user ) { $ ret = [ ] ; if ( $ internal ) { $ ret [ 'Internal ' . $ key ] = \ array_filter ( $ classes , function ( $ class ) { $ refl = new \ ReflectionClass ( $ class ) ; return $ refl -> isInternal ( ) ; } ) ; } if ( $ user ) { $ ret [ 'User ' . $ key ] = \ array_filter ( $ classes , function ( $ class ) { $ refl = new \ ReflectionClass ( $ class ) ; return ! $ refl -> isInternal ( ) ; } ) ; } if ( ! $ user && ! $ internal ) { $ ret [ $ key ] = $ classes ; } return $ ret ; }
Filter a list of classes interfaces or traits .
13,080
protected function prepareClasses ( array $ classes ) { \ natcasesort ( $ classes ) ; $ ret = [ ] ; foreach ( $ classes as $ name ) { if ( $ this -> showItem ( $ name ) ) { $ ret [ $ name ] = [ 'name' => $ name , 'style' => self :: IS_CLASS , 'value' => $ this -> presentSignature ( $ name ) , ] ; } } return $ ret ; }
Prepare formatted class array .
13,081
public function processCallback ( $ input , $ index , $ info = [ ] ) { $ line = $ info [ 'line_buffer' ] ; if ( isset ( $ info [ 'end' ] ) ) { $ line = \ substr ( $ line , 0 , $ info [ 'end' ] ) ; } if ( $ line === '' && $ input !== '' ) { $ line = $ input ; } $ tokens = \ token_get_all ( '<?php ' . $ line ) ; $ tokens = \ array_filter ( $ tokens , function ( $ token ) { return ! AbstractMatcher :: tokenIs ( $ token , AbstractMatcher :: T_WHITESPACE ) ; } ) ; $ matches = [ ] ; foreach ( $ this -> matchers as $ matcher ) { if ( $ matcher -> hasMatched ( $ tokens ) ) { $ matches = \ array_merge ( $ matcher -> getMatches ( $ tokens ) , $ matches ) ; } } $ matches = \ array_unique ( $ matches ) ; return ! empty ( $ matches ) ? $ matches : [ '' ] ; }
Handle readline completion .
13,082
private function validateArrayMultisort ( Node $ node ) { $ nonPassable = 2 ; foreach ( $ node -> args as $ arg ) { if ( $ this -> isPassableByReference ( $ arg ) ) { $ nonPassable = 0 ; } elseif ( ++ $ nonPassable > 2 ) { throw new FatalErrorException ( self :: EXCEPTION_MESSAGE , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } } }
Because array_multisort has a problematic signature ...
13,083
public function page ( $ messages , $ type = 0 ) { if ( \ is_string ( $ messages ) ) { $ messages = ( array ) $ messages ; } if ( ! \ is_array ( $ messages ) && ! \ is_callable ( $ messages ) ) { throw new \ InvalidArgumentException ( 'Paged output requires a string, array or callback' ) ; } $ this -> startPaging ( ) ; if ( \ is_callable ( $ messages ) ) { $ messages ( $ this ) ; } else { $ this -> write ( $ messages , true , $ type ) ; } $ this -> stopPaging ( ) ; }
Page multiple lines of output .
13,084
private function initFormatters ( ) { $ formatter = $ this -> getFormatter ( ) ; $ formatter -> setStyle ( 'warning' , new OutputFormatterStyle ( 'black' , 'yellow' ) ) ; $ formatter -> setStyle ( 'error' , new OutputFormatterStyle ( 'black' , 'red' , [ 'bold' ] ) ) ; $ formatter -> setStyle ( 'aside' , new OutputFormatterStyle ( 'blue' ) ) ; $ formatter -> setStyle ( 'strong' , new OutputFormatterStyle ( null , null , [ 'bold' ] ) ) ; $ formatter -> setStyle ( 'return' , new OutputFormatterStyle ( 'cyan' ) ) ; $ formatter -> setStyle ( 'urgent' , new OutputFormatterStyle ( 'red' ) ) ; $ formatter -> setStyle ( 'hidden' , new OutputFormatterStyle ( 'black' ) ) ; $ formatter -> setStyle ( 'public' , new OutputFormatterStyle ( null , null , [ 'bold' ] ) ) ; $ formatter -> setStyle ( 'protected' , new OutputFormatterStyle ( 'yellow' ) ) ; $ formatter -> setStyle ( 'private' , new OutputFormatterStyle ( 'red' ) ) ; $ formatter -> setStyle ( 'global' , new OutputFormatterStyle ( 'cyan' , null , [ 'bold' ] ) ) ; $ formatter -> setStyle ( 'const' , new OutputFormatterStyle ( 'cyan' ) ) ; $ formatter -> setStyle ( 'class' , new OutputFormatterStyle ( 'blue' , null , [ 'underscore' ] ) ) ; $ formatter -> setStyle ( 'function' , new OutputFormatterStyle ( null ) ) ; $ formatter -> setStyle ( 'default' , new OutputFormatterStyle ( null ) ) ; $ formatter -> setStyle ( 'number' , new OutputFormatterStyle ( 'magenta' ) ) ; $ formatter -> setStyle ( 'string' , new OutputFormatterStyle ( 'green' ) ) ; $ formatter -> setStyle ( 'bool' , new OutputFormatterStyle ( 'cyan' ) ) ; $ formatter -> setStyle ( 'keyword' , new OutputFormatterStyle ( 'yellow' ) ) ; $ formatter -> setStyle ( 'comment' , new OutputFormatterStyle ( 'blue' ) ) ; $ formatter -> setStyle ( 'object' , new OutputFormatterStyle ( 'blue' ) ) ; $ formatter -> setStyle ( 'resource' , new OutputFormatterStyle ( 'yellow' ) ) ; }
Initialize output formatter styles .
13,085
private function getDefaultPasses ( ) { $ useStatementPass = new UseStatementPass ( ) ; $ namespacePass = new NamespacePass ( $ this ) ; $ this -> addImplicitDebugContext ( [ $ useStatementPass , $ namespacePass ] ) ; return [ new AbstractClassPass ( ) , new AssignThisVariablePass ( ) , new CalledClassPass ( ) , new CallTimePassByReferencePass ( ) , new FinalClassPass ( ) , new FunctionContextPass ( ) , new FunctionReturnInWriteContextPass ( ) , new InstanceOfPass ( ) , new LeavePsyshAlonePass ( ) , new LegacyEmptyPass ( ) , new ListPass ( ) , new LoopContextPass ( ) , new PassableByReferencePass ( ) , new ValidConstructorPass ( ) , $ useStatementPass , new ExitPass ( ) , new ImplicitReturnPass ( ) , new MagicConstantsPass ( ) , $ namespacePass , new RequirePass ( ) , new StrictTypesPass ( ) , new ValidClassNamePass ( ) , new ValidConstantPass ( ) , new ValidFunctionNamePass ( ) , ] ; }
Get default CodeCleaner passes .
13,086
private function addImplicitDebugContext ( array $ passes ) { $ file = $ this -> getDebugFile ( ) ; if ( $ file === null ) { return ; } try { $ code = @ \ file_get_contents ( $ file ) ; if ( ! $ code ) { return ; } $ stmts = $ this -> parse ( $ code , true ) ; if ( $ stmts === false ) { return ; } $ traverser = new NodeTraverser ( ) ; foreach ( $ passes as $ pass ) { $ traverser -> addVisitor ( $ pass ) ; } $ traverser -> traverse ( $ stmts ) ; } catch ( \ Throwable $ e ) { } catch ( \ Exception $ e ) { } }
Warm up code cleaner passes when we re coming from a debug call .
13,087
private static function getDebugFile ( ) { $ trace = \ debug_backtrace ( DEBUG_BACKTRACE_IGNORE_ARGS ) ; foreach ( \ array_reverse ( $ trace ) as $ stackFrame ) { if ( ! self :: isDebugCall ( $ stackFrame ) ) { continue ; } if ( \ preg_match ( '/eval\(/' , $ stackFrame [ 'file' ] ) ) { \ preg_match_all ( '/([^\(]+)\((\d+)/' , $ stackFrame [ 'file' ] , $ matches ) ; return $ matches [ 1 ] [ 0 ] ; } return $ stackFrame [ 'file' ] ; } }
Search the stack trace for a file in which the user called Psy \ debug .
13,088
public function clean ( array $ codeLines , $ requireSemicolons = false ) { $ stmts = $ this -> parse ( '<?php ' . \ implode ( PHP_EOL , $ codeLines ) . PHP_EOL , $ requireSemicolons ) ; if ( $ stmts === false ) { return false ; } $ stmts = $ this -> traverser -> traverse ( $ stmts ) ; $ oldLocale = \ setlocale ( LC_NUMERIC , 0 ) ; \ setlocale ( LC_NUMERIC , 'C' ) ; $ code = $ this -> printer -> prettyPrint ( $ stmts ) ; \ setlocale ( LC_NUMERIC , $ oldLocale ) ; return $ code ; }
Clean the given array of code .
13,089
protected function parse ( $ code , $ requireSemicolons = false ) { try { return $ this -> parser -> parse ( $ code ) ; } catch ( \ PhpParser \ Error $ e ) { if ( $ this -> parseErrorIsUnclosedString ( $ e , $ code ) ) { return false ; } if ( $ this -> parseErrorIsUnterminatedComment ( $ e , $ code ) ) { return false ; } if ( $ this -> parseErrorIsTrailingComma ( $ e , $ code ) ) { return false ; } if ( ! $ this -> parseErrorIsEOF ( $ e ) ) { throw ParseErrorException :: fromParseError ( $ e ) ; } if ( $ requireSemicolons ) { return false ; } try { return $ this -> parser -> parse ( $ code . ';' ) ; } catch ( \ PhpParser \ Error $ e ) { return false ; } } }
Lex and parse a block of code .
13,090
private function parseErrorIsUnclosedString ( \ PhpParser \ Error $ e , $ code ) { if ( $ e -> getRawMessage ( ) !== 'Syntax error, unexpected T_ENCAPSED_AND_WHITESPACE' ) { return false ; } try { $ this -> parser -> parse ( $ code . "';" ) ; } catch ( \ Exception $ e ) { return false ; } return true ; }
A special test for unclosed single - quoted strings .
13,091
public function enterNode ( Node $ node ) { parent :: enterNode ( $ node ) ; if ( self :: isConditional ( $ node ) ) { $ this -> conditionalScopes ++ ; } elseif ( $ node instanceof Function_ ) { $ name = $ this -> getFullyQualifiedName ( $ node -> name ) ; if ( $ this -> conditionalScopes === 0 ) { if ( \ function_exists ( $ name ) || isset ( $ this -> currentScope [ \ strtolower ( $ name ) ] ) ) { $ msg = \ sprintf ( 'Cannot redeclare %s()' , $ name ) ; throw new FatalErrorException ( $ msg , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } } $ this -> currentScope [ \ strtolower ( $ name ) ] = true ; } }
Store newly defined function names on the way in to allow recursion .
13,092
public function leaveNode ( Node $ node ) { if ( self :: isConditional ( $ node ) ) { $ this -> conditionalScopes -- ; } elseif ( $ node instanceof FuncCall ) { $ name = $ node -> name ; if ( ! $ name instanceof Expr && ! $ name instanceof Variable ) { $ shortName = \ implode ( '\\' , $ name -> parts ) ; $ fullName = $ this -> getFullyQualifiedName ( $ name ) ; $ inScope = isset ( $ this -> currentScope [ \ strtolower ( $ fullName ) ] ) ; if ( ! $ inScope && ! \ function_exists ( $ shortName ) && ! \ function_exists ( $ fullName ) ) { $ message = \ sprintf ( 'Call to undefined function %s()' , $ name ) ; throw new FatalErrorException ( $ message , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } } } }
Validate that function calls will succeed .
13,093
public function leaveNode ( Node $ node ) { if ( $ node instanceof ConstFetch && \ count ( $ node -> name -> parts ) > 1 ) { $ name = $ this -> getFullyQualifiedName ( $ node -> name ) ; if ( ! \ defined ( $ name ) ) { $ msg = \ sprintf ( 'Undefined constant %s' , $ name ) ; throw new FatalErrorException ( $ msg , 0 , E_ERROR , null , $ node -> getLine ( ) ) ; } } elseif ( $ node instanceof ClassConstFetch ) { $ this -> validateClassConstFetchExpression ( $ node ) ; } }
Validate that namespaced constant references will succeed .
13,094
protected function validateClassConstFetchExpression ( ClassConstFetch $ stmt ) { $ constName = $ stmt -> name instanceof Identifier ? $ stmt -> name -> toString ( ) : $ stmt -> name ; if ( $ constName === 'class' ) { return ; } if ( ! $ stmt -> class instanceof Expr ) { $ className = $ this -> getFullyQualifiedName ( $ stmt -> class ) ; if ( \ class_exists ( $ className ) || \ interface_exists ( $ className ) ) { $ refl = new \ ReflectionClass ( $ className ) ; if ( ! $ refl -> hasConstant ( $ constName ) ) { $ constType = \ class_exists ( $ className ) ? 'Class' : 'Interface' ; $ msg = \ sprintf ( '%s constant \'%s::%s\' not found' , $ constType , $ className , $ constName ) ; throw new FatalErrorException ( $ msg , 0 , E_ERROR , null , $ stmt -> getLine ( ) ) ; } } } }
Validate a class constant fetch expression .
13,095
public static function getCurrentConfigDir ( ) { $ configDirs = self :: getHomeConfigDirs ( ) ; foreach ( $ configDirs as $ configDir ) { if ( @ \ is_dir ( $ configDir ) ) { return $ configDir ; } } return $ configDirs [ 0 ] ; }
Get the current home config directory .
13,096
public static function getConfigFiles ( array $ names , $ configDir = null ) { $ dirs = ( $ configDir === null ) ? self :: getConfigDirs ( ) : [ $ configDir ] ; return self :: getRealFiles ( $ dirs , $ names ) ; }
Find real config files in config directories .
13,097
public static function getDataFiles ( array $ names , $ dataDir = null ) { $ dirs = ( $ dataDir === null ) ? self :: getDataDirs ( ) : [ $ dataDir ] ; return self :: getRealFiles ( $ dirs , $ names ) ; }
Find real data files in config directories .
13,098
public static function getRuntimeDir ( ) { $ xdg = new Xdg ( ) ; \ set_error_handler ( [ 'Psy\Exception\ErrorException' , 'throwException' ] ) ; try { $ runtimeDir = $ xdg -> getRuntimeDir ( false ) ; } catch ( \ Exception $ e ) { $ runtimeDir = \ sys_get_temp_dir ( ) ; } \ restore_error_handler ( ) ; return \ strtr ( $ runtimeDir , '\\' , '/' ) . '/psysh' ; }
Get a runtime directory .
13,099
protected function prepareTraits ( array $ traits ) { \ natcasesort ( $ traits ) ; $ ret = [ ] ; foreach ( $ traits as $ name ) { if ( $ this -> showItem ( $ name ) ) { $ ret [ $ name ] = [ 'name' => $ name , 'style' => self :: IS_CLASS , 'value' => $ this -> presentSignature ( $ name ) , ] ; } } return $ ret ; }
Prepare formatted trait array .