### Install PsySH from Repository Source: https://github.com/bobthecow/psysh/wiki/Installation Clone the PsySH repository, install its dependencies with Composer, and then run the executable. ```bash git clone https://github.com/bobthecow/psysh.git cd psysh composer install ./bin/psysh ``` -------------------------------- ### Start PsySH REPL Source: https://github.com/bobthecow/psysh/wiki/Usage Run the PsySH executable from your terminal to start an interactive PHP REPL session. ```bash ~ $ ./psysh Psy Shell v0.12.x (PHP 8.x.x — cli) by Justin Hileman >>> ``` -------------------------------- ### Update PHP Manual Source: https://github.com/bobthecow/psysh/wiki/CLI-options Download and install the latest PHP manual, optionally specifying a language. ```bash psysh --update-manual ``` ```bash psysh --update-manual=fr # Switch language ``` -------------------------------- ### Install PsySH via Composer Source: https://github.com/bobthecow/psysh/wiki/Installation Install PsySH as a project dependency using Composer. You can then run it using the vendor binary. ```bash composer require psy/psysh:@stable ./vendor/bin/psysh ``` -------------------------------- ### Get help for a specific PsySH command Source: https://github.com/bobthecow/psysh/wiki/Commands Provide a command name as an argument to `help` to view detailed usage information, including arguments, options, and examples for that specific command. ```shell >>> help dump Usage: dump [--depth DEPTH] [-a|--all] [--] Arguments: target A target object or primitive to dump. Options: --depth Depth to parse (default: 10) --all (-a) Include private and protected methods and properties. Help: Dump an object or primitive. This is like var_dump but way awesomer. e.g. >>> dump $_ >>> dump $someVar >>> ``` -------------------------------- ### Install PHP Dependencies in Babun Source: https://github.com/bobthecow/psysh/wiki/Windows Utilize the 'pact' package manager to install PHP and its required extensions for PsySH within the Babun environment. Babun is based on Cygwin. ```bash $ pact install php php_mbstring php_json php_tokenizer php_posix ``` -------------------------------- ### Install/Update PHP Manual Source: https://github.com/bobthecow/psysh/wiki/PHP-manual Use this command to install or update the PHP manual to the latest version. You can also specify a language code to download a manual in a specific language. ```bash psysh --update-manual ``` ```bash psysh --update-manual=fr ``` -------------------------------- ### Install PHP Dependencies in Cygwin Source: https://github.com/bobthecow/psysh/wiki/Windows Use apt-cyg to install necessary PHP extensions for PsySH in a Cygwin environment. Ensure you are using the correct PHP binary for Cygwin. ```bash $ apt-cyg install php_mbstring php_json php_tokenizer php_posix ``` -------------------------------- ### Install PsySH via Homebrew Source: https://github.com/bobthecow/psysh/wiki/Installation For macOS users, PsySH can be conveniently installed using the Homebrew package manager. ```bash brew install psysh ``` -------------------------------- ### Set Alternate Working Directory Source: https://github.com/bobthecow/psysh/wiki/CLI-options Start PsySH in a specified directory and enable local configuration file detection. ```bash psysh --cwd /path/to/project ``` -------------------------------- ### Configure Default Includes for PsySH Source: https://github.com/bobthecow/psysh/wiki/Sample-config Specify files to be included at the start of every PsySH session. This is ideal for loading autoloaders or setting up common variables. ```php $defaultIncludes = []; $bootstrapPath = __DIR__ . '/include/bootstrap.php'; if (file_exists($bootstrapPath)) { $defaultIncludes[] = $bootstrapPath; } return [ 'defaultIncludes' => $defaultIncludes, ]; ``` -------------------------------- ### Custom Tab Completion Matchers Source: https://github.com/bobthecow/psysh/wiki/Config-options Implement custom tab completion matchers by providing an array of matcher instances. This example shows matchers for MongoDB database and collection names. ```php [ new \Psy\TabCompletion\Matcher\MongoClientMatcher, new \Psy\TabCompletion\Matcher\MongoDatabaseMatcher, ] ``` -------------------------------- ### Inspect and update PsySH configuration Source: https://github.com/bobthecow/psysh/wiki/Commands Use the `config` command to view available settings with `list`, retrieve a specific setting's value with `get`, or change a setting for the current session with `set`. ```shell >>> config list >>> config get pager >>> config set pager off >>> config set semicolonsSuppressReturn double ``` -------------------------------- ### Debug with Custom Context Source: https://github.com/bobthecow/psysh/wiki/Usage Use `Psy\debug` to start a debugging session with a custom context, such as an application object. ```php $result = \Psy\debug(['app' => $myApp]); ``` -------------------------------- ### Configure Tab Completion Matchers Source: https://github.com/bobthecow/psysh/wiki/Sample-config Extend PsySH's tab completion by adding custom matchers for specific classes or types. This example shows how to enable completion for MongoDB database and collection names. ```php 'matchers' => [ new \Psy\TabCompletion\Matcher\MongoClientMatcher, new \Psy\TabCompletion\Matcher\MongoDatabaseMatcher, ], ``` -------------------------------- ### Migrating Formatter Styles to Theme - PsySH Source: https://github.com/bobthecow/psysh/wiki/Config-options Deprecated `formatterStyles` can be migrated to custom `theme` styles. This example shows the conversion from the old format to the new `theme` structure for defining styles. ```php 'formatterStyles' => [ // name => [foreground, background, [options]], 'error' => ['black', 'red', ['bold']], ], ``` ```php 'theme' => [ 'styles' => [ // name => [foreground, background, [options]], 'error' => ['black', 'red', ['bold']], ], ], ``` -------------------------------- ### Force Non-Interactive Mode Source: https://github.com/bobthecow/psysh/wiki/CLI-options Execute input from stdin without starting an interactive shell. This requires input to be provided via stdin. ```bash echo '>> my_helper() Warning: Skipped conditional: if (...) { function my_helper() ... } ``` -------------------------------- ### Display all PsySH commands Source: https://github.com/bobthecow/psysh/wiki/Commands Use the `help` command without arguments to list all available commands and their brief descriptions. This is useful for discovering available functionality. ```shell >>> help help Show a list of commands. Type `help [foo]` for information about [foo]. Aliases: ? ls List local, instance or class variables, methods and constants. Aliases: list, dir dump Dump an object or primitive. doc Read the documentation for an object, class, constant, method or property. Aliases: rtfm, man show Show the code for an object, class, constant, method or property. ... >>> ``` -------------------------------- ### Use Custom Config and Enable Autoload Warming Source: https://github.com/bobthecow/psysh/wiki/CLI-options Specify a custom configuration file with `--config` and enable autoload warming with `--warm-autoload`. ```bash psysh --config /path/to/config.php --warm-autoload ``` -------------------------------- ### Configure Logging with Callbacks or PSR-3 Loggers Source: https://github.com/bobthecow/psysh/wiki/Config-options Set up logging for user input, commands, and executed code. Supports simple callbacks or PSR-3 compatible loggers with optional granular control over log levels for different event types. ```php // Simple callback 'logging' => function ($kind, $data) { file_put_contents('/tmp/psysh.log', "[$kind] $data\n", FILE_APPEND); }, ``` ```php // PSR-3 logger with defaults (input=info, command=info, execute=debug) 'logging' => $psrLogger, ``` ```php // Set a single log level for everything 'logging' => [ 'logger' => $psrLogger, 'level' => 'info', ], ``` ```php // Granular control per event type 'logging' => [ 'logger' => $psrLogger, 'level' => [ 'input' => 'info', // User code input 'command' => false, // Disable command logging 'execute' => 'debug', // Cleaned code before execution ], ], ``` -------------------------------- ### Configure PsySH Settings Source: https://github.com/bobthecow/psysh/wiki/Configuration Add this to `~/.config/psysh/config.php` to customize PsySH behavior, such as adding commands or setting a custom startup message. ```php [ new \Psy\Command\ParseCommand, ], 'defaultIncludes' => [ __DIR__ . '/include/bootstrap.php', ], 'startupMessage' => sprintf('%s', shell_exec('uptime')), ]; ``` -------------------------------- ### Use Compact Output Source: https://github.com/bobthecow/psysh/wiki/CLI-options Run PsySH with reduced whitespace for a more compact display, similar to the 'compact' theme. ```bash psysh --compact ``` -------------------------------- ### Trust Project with PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Use `--trust-project` to skip the Restricted Mode prompt and load local configurations, binaries, and Composer autoloads. ```bash psysh --trust-project ``` -------------------------------- ### Migrate Custom Prompt to Theme Configuration Source: https://github.com/bobthecow/psysh/wiki/Config-options Transition from the deprecated `prompt` configuration to the `theme` configuration for custom prompts. This ensures compatibility with the new theming system. ```php 'prompt' => '$> ', ``` ```php 'theme' => [ 'prompt' => '$> ', ], ``` -------------------------------- ### Display Startup Message Source: https://github.com/bobthecow/psysh/wiki/Sample-config Configure an additional startup message for PsySH. Supports Symfony Console tags for styling and coloring. ```php 'startupMessage' => sprintf('%s', shell_exec('uptime')), ``` -------------------------------- ### Download and Run PsySH Phar Source: https://github.com/bobthecow/psysh/wiki/Installation Download the PsySH phar archive, make it executable, and run it. Consider placing it in your system's PATH for easier access. ```bash wget https://psysh.org/psysh chmod +x psysh ./psysh ``` -------------------------------- ### Enable Experimental Readline from Command Line Source: https://github.com/bobthecow/psysh/wiki/Interactive-readline Activate the experimental readline features directly from the command line when launching PsySH using the --experimental-readline flag. ```bash psysh --experimental-readline ``` -------------------------------- ### Set Update Check Frequency Source: https://github.com/bobthecow/psysh/wiki/Sample-config Configure how often PsySH checks for updates when starting an interactive session. Options include 'always', 'daily', 'weekly', 'monthly', or 'never' to disable checks. ```php 'updateCheck' => 'daily', ``` -------------------------------- ### Configure Custom PsySH Theme Prompts Source: https://github.com/bobthecow/psysh/wiki/Themes Define custom prompt strings for standard input, multi-line continuation, history replay, and return values. ```php 'theme' => [ 'prompt' => '⟫ ', 'bufferPrompt' => '⋯ ', 'replayPrompt' => '⤑ ', 'returnValue' => '⇒ ', ] ``` -------------------------------- ### Set Custom XDG Directories for PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Customize configuration and data file locations by exporting `XDG_CONFIG_HOME` and `XDG_DATA_HOME`. ```bash # Custom XDG directories export XDG_CONFIG_HOME=~/my-config export XDG_DATA_HOME=~/my-data # PsySH will look for config at ~/my-config/psysh/config.php # and store history at ~/my-data/psysh/ psysh ``` -------------------------------- ### Enable Experimental Readline Source: https://github.com/bobthecow/psysh/wiki/Sample-config Enable experimental interactive readline features, providing a pure-PHP readline replacement with advanced editing and completion capabilities without requiring ext-readline. ```php 'useExperimentalReadline' => true, ``` -------------------------------- ### Override Configuration with Command Line Option Source: https://github.com/bobthecow/psysh/wiki/CLI-options Command-line options like `--compact` take precedence over settings in `config.php`. ```bash # This will use compact output even if your config.php sets compact to false psysh --compact ``` -------------------------------- ### Enable Raw Output Mode Source: https://github.com/bobthecow/psysh/wiki/Sample-config Configure PsySH to print var_export-style return values. This is typically used with the `--raw-output` flag for non-interactive execution. ```php 'rawOutput' => false, ``` -------------------------------- ### Show History Head and Tail Source: https://github.com/bobthecow/psysh/wiki/History Use `--head N` to show the first N lines or `--tail M` to show the last M lines of your PsySH history. ```shell >>> hist --head 3 0: function z() { throw new RuntimeException; } 1: function y() { z(); } 2: function x() { y(); } >>> ``` ```shell >>> hist --tail 2 3: x() 4: wtf >>> ``` -------------------------------- ### Trust All Projects via Environment Variable Source: https://github.com/bobthecow/psysh/wiki/CLI-options Set `PSYSH_TRUST_PROJECT` to `true` or `1` to trust all projects by default. ```bash # Trust all projects export PSYSH_TRUST_PROJECT=true psysh ``` -------------------------------- ### Retrieving Last File, Line, and Directory Context Source: https://github.com/bobthecow/psysh/wiki/Magic-variables Variables like $__file, $__line, and $__dir provide context about the last command that operated on a file, such as `show` or `doc`. These are useful for understanding the location of code elements. ```php >>> show Psy\sh > 29| function sh() 30| { 31| return 'extract(\Psy\Shell::debug(get_defined_vars(), isset($this) ? $this : null));'; 32| } >>> $__file => "/Projects/psysh/src/Psy/functions.php" >>> $__line => 29 >>> $__dir => "/Projects/psysh/src/Psy" ``` -------------------------------- ### Enable Inline Autosuggestions Source: https://github.com/bobthecow/psysh/wiki/Config-options Enable inline autosuggestions (fish-style ghost text) when using the experimental readline. Suggestions are based on command history, and can be accepted by pressing Right. ```php 'useSuggestions' => true, ``` -------------------------------- ### Force Colors and Compact Output in PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Combine `--color` and `--compact` flags for colored output and a more condensed display. ```bash psysh --color --compact ``` -------------------------------- ### Enable Suggestions in PsySH Config Source: https://github.com/bobthecow/psysh/wiki/Interactive-readline Enable inline autosuggestions, similar to Fish and Zsh, by setting 'useSuggestions' to true in your PsySH configuration. This feature is behind a separate flag and is still considered experimental. ```php 'useSuggestions' => true ``` -------------------------------- ### Enable Warm Autoloading in PsySH Source: https://github.com/bobthecow/psysh/wiki/Config-options Set 'warmAutoload' to true to enable autoloading. This can be a boolean or an array for more granular control. ```php 'warmAutoload' => true, ``` ```php 'warmAutoload' => [ // Include vendor packages 'includeVendor' => true, // Include test classes 'includeTests' => true, // Include only specific namespaces 'includeNamespaces' => ['App\', 'Lib\'], // Exclude specific namespaces 'excludeNamespaces' => ['App\Legacy\'], // Include specific vendor namespaces 'includeVendorNamespaces' => ['Symfony\Component\', 'Doctrine\'], // Exclude specific namespaces 'excludeVendorNamespaces' => ['Symfony\VarDumper\'], // Provide custom warmers 'warmers' => [new MyCustomWarmer()], ], ``` -------------------------------- ### Warn on Multiple Configurations in PsySH Source: https://github.com/bobthecow/psysh/wiki/Config-options Enable 'warnOnMultipleConfigs' to receive warnings when multiple versions of the same configuration or data file exist. Defaults to false. ```php 'warnOnMultipleConfigs' => false, ``` -------------------------------- ### Set Custom Output Theme Source: https://github.com/bobthecow/psysh/wiki/Config-options Configure the output theme for PsySH. Available options include 'modern', 'compact', and 'classic', or a custom theme array. Refer to the Themes documentation for more details. ```php 'theme' => 'modern', ``` -------------------------------- ### Configure Autoload Warming in PsySH Source: https://github.com/bobthecow/psysh/wiki/Sample-config Enable autoload warming to improve command support and tab completion. This pre-loads classes at startup. Configure which namespaces and vendor packages to include or exclude, and specify custom autoloaders. ```php 'warmAutoload' => [ 'includeVendor' => true, // Include vendor packages 'includeTests' => true, // Include test classes // Include (or exclude) specific namespaces 'includeNamespaces' => ['App\', 'Lib\'], 'excludeNamespaces' => ['App\Legacy\'], // Include (or exclude) specific vendor namespaces 'includeVendorNamespaces' => ['Symfony\Component\', 'Doctrine\'], 'excludeVendorNamespaces' => ['Symfony\VarDumper\'], // Custom warmers can be implemented via `AutoloadWarmerInterface` 'warmers' => [new MyCustomWarmer()], ], ``` -------------------------------- ### Run a command in PsySH Source: https://github.com/bobthecow/psysh/wiki/Commands Enter a command name followed by its arguments at the prompt to execute it. To run PHP code instead of a command, prefix the input with a semicolon. ```shell >>> $a = $b = 'c' => "c" >>> ls -al Variables: $a "c" $b "c" $_ "c" >>> ``` ```shell >>> const help = 'HELP ME!' => true >>> help help Show a list of commands. Type `help [foo]` for information about [foo]. Aliases: ? ls List local, instance or class variables, methods and constants. Aliases: list, dir dump Dump an object or primitive. doc Read the documentation for an object, class, constant, method or property. Aliases: rtfm, man show Show the code for an object, class, constant, method or property. ... >>> ;help => "HELP ME!" >>> ``` -------------------------------- ### Enable Autoload Warming in PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Enable autoload warming with `--warm-autoload` to pre-load classes for improved tab completion and command support by scanning the Composer autoloader at startup. ```bash psysh --warm-autoload ``` -------------------------------- ### Enable Experimental Readline in PsySH Config Source: https://github.com/bobthecow/psysh/wiki/Interactive-readline Configure PsySH to use the experimental readline features by setting 'useExperimentalReadline' to true in your PsySH configuration file. Other related experimental features like suggestions and bracketed paste can also be enabled here. ```php // In your PsySH config file 'useExperimentalReadline' => true, // 'useSuggestions' => true, // 'useBracketedPaste' => true, // 'useSyntaxHighlighting' => false, ``` -------------------------------- ### Set Runtime Directory Source: https://github.com/bobthecow/psysh/wiki/Sample-config Specify a custom location for PsySH's temporary files. Defaults to `/psysh` within the system's temporary directory. ```php 'runtimeDir' => __DIR__ . '/tmp', ``` -------------------------------- ### Define Functions Defensively in PsySH Config Source: https://github.com/bobthecow/psysh/wiki/Configuration Use `require_once` and function existence checks to prevent errors if your PsySH configuration file is loaded multiple times within a single PHP session. ```php >> `pwd` => "/Projects/psysh\n" >>> `ls` => """ CONTRIBUTING.md\n LICENSE\n README.md\n bin\n composer.json\n composer.lock\n phpunit.xml.dist\n src\n test\n vendor\n """ >>> ``` -------------------------------- ### Configure Output Theme Source: https://github.com/bobthecow/psysh/wiki/Sample-config Customize PsySH's output appearance, including prompt strings, formatter styles, and colors. Built-in themes like `modern`, `compact`, and `classic` are available. ```php 'theme' => [ // Use compact output. This can also be set by the --compact flag. 'compact' => true, // The standard input prompt. 'prompt' => '> ', // The input prompt used for multi-line input continuation. 'bufferPrompt' => '. ', // Output prefix indicating lines replayed from history. 'replayPrompt' => '- ', // Output prefix indicating the evaluated input's return value. 'returnValue' => '= ', // Override theme formatting colors. // // Available colors: // black, red, green, yellow, blue, magenta, cyan, white and default. // Available options: // bold, underscore, blink, reverse and conceal. // // Note that the exact effect of these colors and options on output // depends on your terminal emulator application and settings. 'styles' => [ // name => [foreground, background, [options]], 'error' => ['black', 'red', ['bold']], ], ], ``` -------------------------------- ### Execute Code from File with PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Execute PHP code from a file by redirecting the file's content to PsySH's standard input using the `<` operator. ```bash psysh < script.php ``` -------------------------------- ### Configure PsySH Input and Output Source: https://github.com/bobthecow/psysh/wiki/Sample-config These settings control how PsySH handles user input and displays output. Enable bracketed paste for better pasting of multi-line code. Disable Unicode if you encounter code page issues on Windows. Adjust verbosity to control the amount of output. ```php 'useBracketedPaste' => true, // Use OSC 52 escape sequences for clipboard copy support. Useful over SSH // when your terminal supports it. 'useOsc52Clipboard' => false, // By default, PsySH will use a 'forking' execution loop if pcntl is // installed. This is by far the best way to use it, but you can override // the default by explicitly disabling this functionality here. 'usePcntl' => true, // PsySH uses readline if you have it installed, because interactive input // is pretty awful without it. But you can explicitly disable it if you hate // yourself or something. // // If readline is disabled (or unavailable) then terminal input is subject // to the line discipline provided for TTYs by the OS, which may impose a // maximum line size (4096 chars in GNU/Linux, for example) with larger // lines being truncated before reaching PsySH. 'useReadline' => true, // You can disable tab completion if you want to. Not sure why you'd // want to. 'useTabCompletion' => true, // PsySH uses a couple of UTF-8 characters in its own output. These can be // disabled, mostly to work around code page issues. Because Windows. // // Note that this does not disable Unicode output in general, it just makes // it so PsySH won't output any itself. 'useUnicode' => true, // Change output verbosity. This is equivalent to the `--verbose`, `-vv`, // `-vvv` and `--quiet` command line flags. Choose from: // // \Psy\Configuration::VERBOSITY_QUIET (this is *really* quiet) // \Psy\Configuration::VERBOSITY_NORMAL // \Psy\Configuration::VERBOSITY_VERBOSE // \Psy\Configuration::VERBOSITY_VERY_VERBOSE // \Psy\Configuration::VERBOSITY_DEBUG 'verbosity' => \Psy\Configuration::VERBOSITY_VERBOSE, ``` ```php // Enable inline autosuggestions (fish-style ghost text) in interactive // readline. Still a bit rough around the edges. // 'useSuggestions' => true, ``` -------------------------------- ### Show All PsySH History Source: https://github.com/bobthecow/psysh/wiki/History Displays all commands in your PsySH history. Output may be paged if the history is extensive. ```shell >>> hist 0: function z() { throw new RuntimeException; } 1: function y() { z(); } 2: function x() { y(); } 3: x() 4: wtf >>> ``` -------------------------------- ### Autoload Composer Dependencies in PsySH Config Source: https://github.com/bobthecow/psysh/wiki/Configuration Include this snippet at the top of your PsySH config file to automatically load Composer dependencies if a `vendor/autoload.php` file exists in the current directory. ```php // Automatically autoload Composer dependencies if (is_file(getcwd() . '/vendor/autoload.php')) { require_once getcwd() . '/vendor/autoload.php'; } ``` -------------------------------- ### Bypass Version and Extension Checks via Environment Variable Source: https://github.com/bobthecow/psysh/wiki/CLI-options Use `PSYSH_IGNORE_ENV=1` to bypass PHP version and extension checks. Use with caution. ```bash # Override version/extension checks (not recommended) export PSYSH_IGNORE_ENV=1 psysh ``` -------------------------------- ### Namespace-aware command usage in PsySH Source: https://github.com/bobthecow/psysh/wiki/Commands Commands like `ls`, `doc`, and `show` correctly resolve class names based on the current namespace and `use` statements, similar to how PHP code execution works. ```php >>> namespace App\Models; >>> use Illuminate\Database\Eloquent\Model as EloquentModel; >>> doc User // Resolves to App\Models\User >>> show EloquentModel // Resolves to Illuminate\Database\Eloquent\Model >>> ls Model // Lists members of Illuminate\Database\Eloquent\Model ``` -------------------------------- ### Set Custom Config File via Environment Variable Source: https://github.com/bobthecow/psysh/wiki/CLI-options Use the `PSYSH_CONFIG` environment variable to specify a custom configuration file path. ```bash # Use custom config file export PSYSH_CONFIG=/path/to/config.php psysh ``` -------------------------------- ### Configure PsySH Logging Source: https://github.com/bobthecow/psysh/wiki/Sample-config Enable logging of user input, commands, and executed code using a PSR-3 compatible logger or callback. Define log levels for different event types. ```php 'logging' => [ 'logger' => $myPsrLogger, 'level' => [ 'input' => 'info', 'command' => 'info', 'execute' => 'debug', ], ], ``` -------------------------------- ### Configure PsySH Safety and Warnings Source: https://github.com/bobthecow/psysh/wiki/Sample-config These settings control PsySH's behavior regarding configuration file conflicts and potentially unsafe operations. Enable warnings for multiple configuration files to be alerted to potential issues. Use 'yolo' with extreme caution, as it disables input validation. ```php // If multiple versions of the same configuration or data file exist, PsySH // will use the file with highest precedence, and will silently ignore all // others. With this enabled, a warning will be emitted (but not an // exception thrown) if multiple configuration or data files are found. // // This will default to true in a future release, but is false for now. 'warnOnMultipleConfigs' => true, // Run PsySH without input validation. You don't want to set this to true. 'yolo' => false, ``` -------------------------------- ### Configure Custom PsySH Theme Styles Source: https://github.com/bobthecow/psysh/wiki/Themes Override output formatting colors and styles for PsySH. Available colors include black, red, green, yellow, blue, magenta, cyan, white, and default. Options include bold, underscore, blink, reverse, and conceal. ```php 'theme' => [ 'styles' => [ // name => [foreground, background, [options]], 'error' => ['black', 'red', ['bold']], ] ] ``` -------------------------------- ### Configure PsySH Implicit Use Statements Source: https://github.com/bobthecow/psysh/wiki/Sample-config Automatically add `use` statements for unqualified class references. Specify namespaces to include and exclude for this feature. ```php 'implicitUse' => [ 'includeNamespaces' => ['App\'], 'excludeNamespaces' => ['App\Legacy\'], ], ``` -------------------------------- ### Quiet Mode with Raw Output in PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Run PsySH in quiet mode with `--quiet` and receive raw output using `--raw-output`. ```bash echo ' 'monthly', ``` -------------------------------- ### Define and Call Function in PsySH Source: https://github.com/bobthecow/psysh/wiki/Usage Define a PHP function interactively within the PsySH REPL and then call it to see the result. ```php >>> function timesFive($x) { ... $result = $x * 5; ... return $result; ... } >>> timesFive(10); => 50 >>> ``` -------------------------------- ### Set Built-in PsySH Theme Source: https://github.com/bobthecow/psysh/wiki/Themes Specify one of the built-in themes ('classic', 'compact', 'modern') for PsySH output. ```php 'theme' => 'classic' ``` -------------------------------- ### Raw Output for Non-Interactive Use Source: https://github.com/bobthecow/psysh/wiki/CLI-options Print `var_export`-style return values instead of pretty-printed output, suitable for piped input. ```bash echo ' true, ``` -------------------------------- ### Force Restricted Mode with PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Use `--no-trust-project` to force Restricted Mode, even if the project has been previously trusted. ```bash psysh --no-trust-project ``` -------------------------------- ### Use Deprecated Multiline String Format Source: https://github.com/bobthecow/psysh/wiki/Sample-config A compatibility flag to retain the old triple-quoted multiline string output format. Leave disabled to use the newer heredoc-style output. ```php 'useDeprecatedMultilineStrings' => false, ``` -------------------------------- ### Set Custom Output Pager Source: https://github.com/bobthecow/psysh/wiki/Sample-config Specify a custom command for paginating output in PsySH. Set to `false` to disable paging, or leave unset to use system defaults like `less`. ```php 'pager' => 'more', ``` -------------------------------- ### Configure PsySH Casters Source: https://github.com/bobthecow/psysh/wiki/Sample-config Customize how PsySH displays specific class instances by defining custom casters. This is useful for integrating with your own classes. ```php return [ 'casters' => [ 'MyFooClass' => 'MyFooClassCaster::castMyFooObject', ], ]; ``` -------------------------------- ### Define Custom Prompt Source: https://github.com/bobthecow/psysh/wiki/Sample-config Set a custom prompt string for the PsySH interactive session. Note: This is deprecated and `theme.prompt` is preferred. ```php 'prompt' => '>>>', ``` -------------------------------- ### Show History Slice Source: https://github.com/bobthecow/psysh/wiki/History Displays a specific range or single line from your PsySH history using the `--show` option. Use `N..M` for a range or `N..` for lines from N to the end. ```shell >>> hist --show 1..3 1: function y() { z(); } 2: function x() { y(); } 3: x() >>> ``` -------------------------------- ### Copy values to the clipboard Source: https://github.com/bobthecow/psysh/wiki/Commands The `copy` command evaluates an expression and copies its exported value to the clipboard. If no expression is provided, it copies the last evaluated result (`$_`). ```shell >>> copy >>> copy User::all()->toArray() >>> copy new Foo() ``` -------------------------------- ### Configure PsySH History Settings Source: https://github.com/bobthecow/psysh/wiki/Sample-config Control PsySH history behavior. `eraseDuplicates` prevents duplicate entries, and `historySize` sets the maximum number of entries (0 for unlimited). ```php 'eraseDuplicates' => false, ``` ```php 'historySize' => 0, ``` -------------------------------- ### Configure PsySH Interactive Mode Source: https://github.com/bobthecow/psysh/wiki/Sample-config Control whether PsySH runs in interactive or non-interactive mode. Use `INTERACTIVE_MODE_FORCED`, `INTERACTIVE_MODE_DISABLED`, or `INTERACTIVE_MODE_AUTO`. ```php 'interactiveMode' => \Psy\Configuration::INTERACTIVE_MODE_FORCED, ``` -------------------------------- ### Accessing Last Namespace, Class, Method, and Function Names Source: https://github.com/bobthecow/psysh/wiki/Magic-variables PsySH sets $__namespace, $__class, $__method, and $__function based on commands like `doc` and `show`. These variables help identify the scope and origin of code elements. ```php >>> show Psy\Shell::debug > 138| public static function debug(array $vars = array(), $boundObject = null) 139| { 140| echo PHP_EOL; 141| 142| $sh = new \Psy\Shell(); 143| $sh->setScopeVariables($vars); 144| 145| if ($boundObject !== null) { 146| $sh->setBoundObject($boundObject); 147| } 148| 149| $sh->run(); 150| 151| return $sh->getScopeVariables(false); 152| } >>> $__namespace => "Psy" >>> $__class => "Psy\Shell" >>> $__method => "Psy\Shell::debug" >>> $__function PHP error: Undefined variable: __function on line 1 >>> ``` -------------------------------- ### Replay History Commands Source: https://github.com/bobthecow/psysh/wiki/History Replays commands from your PsySH history using the `--replay` option. This can be combined with filtering options like `--head`, `--tail`, and `--grep`. ```shell >>> hist --head 3 --replay Replaying 3 lines of history --> function z() { throw new RuntimeException; } --> function y() { z(); } --> function x() { y(); } >>> function_exists('x') => true >>> ``` -------------------------------- ### Include PsySH Debugger Source: https://github.com/bobthecow/psysh/wiki/Usage Include the PsySH Phar file in your PHP project to enable debugging capabilities. ```php require('/path/to/psysh'); ``` -------------------------------- ### Custom Exception Details Callback - PsySH Source: https://github.com/bobthecow/psysh/wiki/Config-options Provide a callback to render extra structured exception details in `wtf`, `show`, and uncaught exception output. The callback receives the thrown exception and may return any dumpable value; returning `null` suppresses extra output. ```php 'exceptionDetails' => static function (\Throwable $e) { return ['class' => $e::class]; }, ``` -------------------------------- ### Control Project Trust Level Source: https://github.com/bobthecow/psysh/wiki/Config-options Define how PsySH should handle project trust, which affects whether local configurations, binaries, and autoloaders are loaded. Options include prompting, always trusting, or never trusting. ```php 'trustProject' => 'prompt', // Ask interactively (default) ``` ```php 'trustProject' => 'always', // Trust all projects ``` ```php 'trustProject' => 'never', // Always run restricted ``` -------------------------------- ### Configure PsySH Array Index Display Source: https://github.com/bobthecow/psysh/wiki/Sample-config Force PsySH to always display array indexes, even for numerically indexed arrays. ```php 'forceArrayIndexes' => true, ``` -------------------------------- ### Configure Project Trust Level Source: https://github.com/bobthecow/psysh/wiki/Sample-config Control whether PsySH trusts the current project, affecting loading of local config, binaries, and Composer autoloads. Options include prompting, always trusting, or always running restricted. ```php 'trustProject' => 'prompt', ``` -------------------------------- ### Increase Output Verbosity Source: https://github.com/bobthecow/psysh/wiki/CLI-options Control the level of output detail, from verbose to debug mode. Use `-v`, `-vv`, or `-vvv` for increasing verbosity. ```bash psysh -vvv # Debug mode ``` -------------------------------- ### Add Custom PsySH Commands Source: https://github.com/bobthecow/psysh/wiki/Sample-config Extend PsySH functionality by adding custom commands. Any Psy command added here will be available in your shell sessions. ```php 'commands' => [ new \Psy\Command\ParseCommand, ], ``` -------------------------------- ### Enable Bracketed Paste in PsySH Config Source: https://github.com/bobthecow/psysh/wiki/Interactive-readline Activate bracketed paste mode in PsySH by setting 'useBracketedPaste' to true in your configuration. This ensures multi-line code is inserted as a single block without interference. ```php 'useBracketedPaste' => true ``` -------------------------------- ### Save PsySH History to File Source: https://github.com/bobthecow/psysh/wiki/History Saves a specified portion of your PsySH history to a local file using the `--save FILENAME` option. Combine with `--head`, `--tail`, or `--grep` to save a subset. ```shell >>> hist --head 3 --save history.txt Saving history in history.txt... History saved. >>> ``` -------------------------------- ### Configure PsySH Color Mode Source: https://github.com/bobthecow/psysh/wiki/Sample-config Control color output in PsySH. Use `COLOR_MODE_FORCED` to always enable colors, `COLOR_MODE_DISABLED` to disable, or `COLOR_MODE_AUTO` to detect terminal support. ```php 'colorMode' => \Psy\Configuration::COLOR_MODE_FORCED, ``` -------------------------------- ### Debug with Bound Object Source: https://github.com/bobthecow/psysh/wiki/Usage When debugging from within a class, pass `$this` as the second argument to `Psy\debug` to gain access to the current object's members, including private and protected ones. ```php \Psy\debug(get_defined_vars(), $this); ``` -------------------------------- ### Configure PsySH Error Logging Level Source: https://github.com/bobthecow/psysh/wiki/Sample-config Set the minimum error reporting level for logging in PsySH. Set to `0` to disable logging of non-thrown errors, or to a specific `error_reporting` value. ```php 'errorLoggingLevel' => E_ALL & ~E_NOTICE, ``` -------------------------------- ### Debug Verbosity with Color in PsySH Source: https://github.com/bobthecow/psysh/wiki/CLI-options Increase debug verbosity using multiple `-v` flags and enable color output with `--color`. ```bash psysh -vvv --color ``` -------------------------------- ### Repeat Last Command with `!!` in PsySH Source: https://github.com/bobthecow/psysh/wiki/Code-reloading The `!!` shortcut in PsySH repeats the last command executed. This is useful for re-running a command, especially after receiving a warning and deciding to use `yolo`. ```text >>> my_helper() Warning: Skipped conditional: if (...) { function my_helper() ... } >>> yolo !! ``` -------------------------------- ### Specify Output Pager Source: https://github.com/bobthecow/psysh/wiki/CLI-options Use a custom pager command for output or disable paging entirely. If no pager is specified, PsySH uses its default resolution. ```bash psysh --pager ``` ```bash psysh --pager='less -R' ``` ```bash --no-pager ``` -------------------------------- ### Run PsySH Non-interactively with Stdin Source: https://github.com/bobthecow/psysh/wiki/CLI-options Pipe code to PsySH using `echo` and the `--no-interactive` flag to execute code non-interactively. ```bash echo '>> echo "wat" wat >>> $__out => "wat" ``` -------------------------------- ### Set PHP Manual Update Check Frequency Source: https://github.com/bobthecow/psysh/wiki/Sample-config Determine the frequency for checking updates to the PHP manual database. Valid options are 'always', 'daily', 'weekly', 'monthly', and 'never'. ```php 'updateManualCheck' => 'weekly', ``` -------------------------------- ### Override php.ini Directives in PsySH Source: https://github.com/bobthecow/psysh/wiki/Configuration Add this snippet to your `config.php` to enable per-project overrides of `php.ini` directives using a `.user.ini` file. Only directives changeable in `PHP_INI_ALL` or `PHP_INI_USER` can be set. ```php // Support per-project `php.ini` directive overrides if (is_file(getcwd() . '/.user.ini')) { $conf = parse_ini_file(getcwd() . '/.user.ini'); foreach ($conf as $key => $val) { ini_set($key, $val); } } ``` -------------------------------- ### Accessing Last Exception with $_e Source: https://github.com/bobthecow/psysh/wiki/Magic-variables The $_e variable stores the last uncaught exception. This is useful for inspecting errors that occurred during the session. Use `wtf` for backtrace or `show --ex` to view the throwing code. ```php >>> throw new Exception('wat') Exception with message 'wat' >>> $_e => Exception {#227 #message: "wat", #file: "phar:///psysh/src/Psy/ExecutionLoop/Loop.php(90) : eval()'d code", #line: 1, } >>> ``` -------------------------------- ### Use Magic Variables with Shell Commands Source: https://github.com/bobthecow/psysh/wiki/Shell-integration Utilize PsySH's magic variables like `$__file` and `$__line` within shell commands for context-aware operations. These variables are updated by commands like `doc`. ```php >>> doc Psy\Shell class Psy\Shell extends Symfony\Component\Console\Application Description: The Psy Shell application. Usage: $shell = new Shell; $shell->run(); Author: Justin Hileman >>> $__file => "/Projects/psysh/src/Psy/Shell.php" >>> `subl $__file:$__line` => null >>> ```