4 * This file is part of Psy Shell.
6 * (c) 2012-2017 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
14 use Psy\Exception\DeprecatedException;
15 use Psy\Exception\RuntimeException;
16 use Psy\ExecutionLoop\ForkingLoop;
17 use Psy\ExecutionLoop\Loop;
18 use Psy\Output\OutputPager;
19 use Psy\Output\ShellOutput;
20 use Psy\Readline\GNUReadline;
21 use Psy\Readline\HoaConsole;
22 use Psy\Readline\Libedit;
23 use Psy\Readline\Readline;
24 use Psy\Readline\Transient;
25 use Psy\TabCompletion\AutoCompleter;
26 use Psy\VarDumper\Presenter;
27 use Psy\VersionUpdater\Checker;
28 use Psy\VersionUpdater\GitHubChecker;
29 use Psy\VersionUpdater\IntervalChecker;
30 use Psy\VersionUpdater\NoopChecker;
34 * The Psy Shell configuration.
38 const COLOR_MODE_AUTO = 'auto';
39 const COLOR_MODE_FORCED = 'forced';
40 const COLOR_MODE_DISABLED = 'disabled';
42 private static $AVAILABLE_OPTIONS = array(
43 'defaultIncludes', 'useReadline', 'usePcntl', 'codeCleaner', 'pager',
44 'loop', 'configDir', 'dataDir', 'runtimeDir', 'manualDbFile',
45 'requireSemicolons', 'useUnicode', 'historySize', 'eraseDuplicates',
46 'tabCompletion', 'errorLoggingLevel', 'warnOnMultipleConfigs',
47 'colorMode', 'updateCheck', 'startupMessage',
50 private $defaultIncludes;
55 /** @var string|false */
58 private $eraseDuplicates;
59 private $manualDbFile;
64 private $newCommands = array();
65 private $requireSemicolons = false;
67 private $tabCompletion;
68 private $tabCompletionMatchers = array();
69 private $errorLoggingLevel = E_ALL;
70 private $warnOnMultipleConfigs = false;
73 private $startupMessage;
88 * Construct a Configuration instance.
90 * Optionally, supply an array of configuration values to load.
92 * @param array $config Optional array of configuration values
94 public function __construct(array $config = array())
96 $this->setColorMode(self::COLOR_MODE_AUTO);
98 // explicit configFile option
99 if (isset($config['configFile'])) {
100 $this->configFile = $config['configFile'];
101 } elseif ($configFile = getenv('PSYSH_CONFIG')) {
102 $this->configFile = $configFile;
105 // legacy baseDir option
106 if (isset($config['baseDir'])) {
107 $msg = "The 'baseDir' configuration option is deprecated. " .
108 "Please specify 'configDir' and 'dataDir' options instead.";
109 throw new DeprecatedException($msg);
112 unset($config['configFile'], $config['baseDir']);
114 // go go gadget, config!
115 $this->loadConfig($config);
120 * Initialize the configuration.
122 * This checks for the presence of Readline and Pcntl extensions.
124 * If a config file is available, it will be loaded and merged with the current config.
126 * If no custom config file was specified and a local project config file
127 * is available, it will be loaded and merged with the current config.
129 public function init()
132 $this->hasReadline = function_exists('readline');
133 $this->hasPcntl = function_exists('pcntl_signal') && function_exists('posix_getpid');
135 if ($configFile = $this->getConfigFile()) {
136 $this->loadConfigFile($configFile);
139 if (!$this->configFile && $localConfig = $this->getLocalConfigFile()) {
140 $this->loadConfigFile($localConfig);
145 * Get the current PsySH config file.
147 * If a `configFile` option was passed to the Configuration constructor,
148 * this file will be returned. If not, all possible config directories will
149 * be searched, and the first `config.php` or `rc.php` file which exists
152 * If you're trying to decide where to put your config file, pick
154 * ~/.config/psysh/config.php
158 public function getConfigFile()
160 if (isset($this->configFile)) {
161 return $this->configFile;
164 $files = ConfigPaths::getConfigFiles(array('config.php', 'rc.php'), $this->configDir);
166 if (!empty($files)) {
167 if ($this->warnOnMultipleConfigs && count($files) > 1) {
168 $msg = sprintf('Multiple configuration files found: %s. Using %s', implode($files, ', '), $files[0]);
169 trigger_error($msg, E_USER_NOTICE);
177 * Get the local PsySH config file.
179 * Searches for a project specific config file `.psysh.php` in the current
184 public function getLocalConfigFile()
186 $localConfig = getenv('PWD') . '/.psysh.php';
188 if (@is_file($localConfig)) {
194 * Load configuration values from an array of options.
196 * @param array $options
198 public function loadConfig(array $options)
200 foreach (self::$AVAILABLE_OPTIONS as $option) {
201 if (isset($options[$option])) {
202 $method = 'set' . ucfirst($option);
203 $this->$method($options[$option]);
207 foreach (array('commands', 'tabCompletionMatchers', 'casters') as $option) {
208 if (isset($options[$option])) {
209 $method = 'add' . ucfirst($option);
210 $this->$method($options[$option]);
216 * Load a configuration file (default: `$HOME/.config/psysh/config.php`).
218 * This configuration instance will be available to the config file as $config.
219 * The config file may directly manipulate the configuration, or may return
220 * an array of options which will be merged with the current configuration.
222 * @throws \InvalidArgumentException if the config file returns a non-array result
224 * @param string $file
226 public function loadConfigFile($file)
228 $__psysh_config_file__ = $file;
229 $load = function ($config) use ($__psysh_config_file__) {
230 $result = require $__psysh_config_file__;
235 $result = $load($this);
237 if (!empty($result)) {
238 if (is_array($result)) {
239 $this->loadConfig($result);
241 throw new \InvalidArgumentException('Psy Shell configuration must return an array of options');
247 * Set files to be included by default at the start of each shell session.
249 * @param array $includes
251 public function setDefaultIncludes(array $includes = array())
253 $this->defaultIncludes = $includes;
257 * Get files to be included by default at the start of each shell session.
261 public function getDefaultIncludes()
263 return $this->defaultIncludes ?: array();
267 * Set the shell's config directory location.
271 public function setConfigDir($dir)
273 $this->configDir = (string) $dir;
277 * Get the current configuration directory, if any is explicitly set.
281 public function getConfigDir()
283 return $this->configDir;
287 * Set the shell's data directory location.
291 public function setDataDir($dir)
293 $this->dataDir = (string) $dir;
297 * Get the current data directory, if any is explicitly set.
301 public function getDataDir()
303 return $this->dataDir;
307 * Set the shell's temporary directory location.
311 public function setRuntimeDir($dir)
313 $this->runtimeDir = (string) $dir;
317 * Get the shell's temporary directory location.
319 * Defaults to `/psysh` inside the system's temp dir unless explicitly
324 public function getRuntimeDir()
326 if (!isset($this->runtimeDir)) {
327 $this->runtimeDir = ConfigPaths::getRuntimeDir();
330 if (!is_dir($this->runtimeDir)) {
331 mkdir($this->runtimeDir, 0700, true);
334 return $this->runtimeDir;
338 * Set the readline history file path.
340 * @param string $file
342 public function setHistoryFile($file)
344 $this->historyFile = ConfigPaths::touchFileWithMkdir($file);
348 * Get the readline history file path.
350 * Defaults to `/history` inside the shell's base config dir unless
351 * explicitly overridden.
355 public function getHistoryFile()
357 if (isset($this->historyFile)) {
358 return $this->historyFile;
361 // Deprecation warning for incorrect psysh_history path.
362 // @todo remove this before v0.9.0
364 $oldHistory = $xdg->getHomeConfigDir() . '/psysh_history';
365 if (@is_file($oldHistory)) {
366 $dir = $this->configDir ?: ConfigPaths::getCurrentConfigDir();
367 $newHistory = $dir . '/psysh_history';
370 "PsySH history file found at '%s'. Please delete it or move it to '%s'.",
371 strtr($oldHistory, '\\', '/'),
374 @trigger_error($msg, E_USER_DEPRECATED);
375 $this->setHistoryFile($oldHistory);
377 return $this->historyFile;
380 $files = ConfigPaths::getConfigFiles(array('psysh_history', 'history'), $this->configDir);
382 if (!empty($files)) {
383 if ($this->warnOnMultipleConfigs && count($files) > 1) {
384 $msg = sprintf('Multiple history files found: %s. Using %s', implode($files, ', '), $files[0]);
385 trigger_error($msg, E_USER_NOTICE);
388 $this->setHistoryFile($files[0]);
390 // fallback: create our own history file
391 $dir = $this->configDir ?: ConfigPaths::getCurrentConfigDir();
392 $this->setHistoryFile($dir . '/psysh_history');
395 return $this->historyFile;
399 * Set the readline max history size.
403 public function setHistorySize($value)
405 $this->historySize = (int) $value;
409 * Get the readline max history size.
413 public function getHistorySize()
415 return $this->historySize;
419 * Sets whether readline erases old duplicate history entries.
423 public function setEraseDuplicates($value)
425 $this->eraseDuplicates = (bool) $value;
429 * Get whether readline erases old duplicate history entries.
433 public function getEraseDuplicates()
435 return $this->eraseDuplicates;
439 * Get a temporary file of type $type for process $pid.
441 * The file will be created inside the current temporary directory.
443 * @see self::getRuntimeDir
445 * @param string $type
448 * @return string Temporary file name
450 public function getTempFile($type, $pid)
452 return tempnam($this->getRuntimeDir(), $type . '_' . $pid . '_');
456 * Get a filename suitable for a FIFO pipe of $type for process $pid.
458 * The pipe will be created inside the current temporary directory.
460 * @param string $type
463 * @return string Pipe name
465 public function getPipe($type, $pid)
467 return sprintf('%s/%s_%s', $this->getRuntimeDir(), $type, $pid);
471 * Check whether this PHP instance has Readline available.
473 * @return bool True if Readline is available
475 public function hasReadline()
477 return $this->hasReadline;
481 * Enable or disable Readline usage.
483 * @param bool $useReadline
485 public function setUseReadline($useReadline)
487 $this->useReadline = (bool) $useReadline;
491 * Check whether to use Readline.
493 * If `setUseReadline` as been set to true, but Readline is not actually
494 * available, this will return false.
496 * @return bool True if the current Shell should use Readline
498 public function useReadline()
500 return isset($this->useReadline) ? ($this->hasReadline && $this->useReadline) : $this->hasReadline;
504 * Set the Psy Shell readline service.
506 * @param Readline $readline
508 public function setReadline(Readline $readline)
510 $this->readline = $readline;
514 * Get the Psy Shell readline service.
516 * By default, this service uses (in order of preference):
520 * * A transient array-based readline emulation.
524 public function getReadline()
526 if (!isset($this->readline)) {
527 $className = $this->getReadlineClass();
528 $this->readline = new $className(
529 $this->getHistoryFile(),
530 $this->getHistorySize(),
531 $this->getEraseDuplicates()
535 return $this->readline;
539 * Get the appropriate Readline implementation class name.
541 * @see self::getReadline
545 private function getReadlineClass()
547 if ($this->useReadline()) {
548 if (GNUReadline::isSupported()) {
549 return 'Psy\Readline\GNUReadline';
550 } elseif (Libedit::isSupported()) {
551 return 'Psy\Readline\Libedit';
552 } elseif (HoaConsole::isSupported()) {
553 return 'Psy\Readline\HoaConsole';
557 return 'Psy\Readline\Transient';
561 * Check whether this PHP instance has Pcntl available.
563 * @return bool True if Pcntl is available
565 public function hasPcntl()
567 return $this->hasPcntl;
571 * Enable or disable Pcntl usage.
573 * @param bool $usePcntl
575 public function setUsePcntl($usePcntl)
577 $this->usePcntl = (bool) $usePcntl;
581 * Check whether to use Pcntl.
583 * If `setUsePcntl` has been set to true, but Pcntl is not actually
584 * available, this will return false.
586 * @return bool True if the current Shell should use Pcntl
588 public function usePcntl()
590 return isset($this->usePcntl) ? ($this->hasPcntl && $this->usePcntl) : $this->hasPcntl;
594 * Enable or disable strict requirement of semicolons.
596 * @see self::requireSemicolons()
598 * @param bool $requireSemicolons
600 public function setRequireSemicolons($requireSemicolons)
602 $this->requireSemicolons = (bool) $requireSemicolons;
606 * Check whether to require semicolons on all statements.
608 * By default, PsySH will automatically insert semicolons at the end of
609 * statements if they're missing. To strictly require semicolons, set
610 * `requireSemicolons` to true.
614 public function requireSemicolons()
616 return $this->requireSemicolons;
620 * Enable or disable Unicode in PsySH specific output.
622 * Note that this does not disable Unicode output in general, it just makes
623 * it so PsySH won't output any itself.
625 * @param bool $useUnicode
627 public function setUseUnicode($useUnicode)
629 $this->useUnicode = (bool) $useUnicode;
633 * Check whether to use Unicode in PsySH specific output.
635 * Note that this does not disable Unicode output in general, it just makes
636 * it so PsySH won't output any itself.
640 public function useUnicode()
642 if (isset($this->useUnicode)) {
643 return $this->useUnicode;
646 // @todo detect `chsh` != 65001 on Windows and return false
651 * Set the error logging level.
653 * @see self::errorLoggingLevel
655 * @param bool $errorLoggingLevel
657 public function setErrorLoggingLevel($errorLoggingLevel)
659 $this->errorLoggingLevel = (E_ALL | E_STRICT) & $errorLoggingLevel;
663 * Get the current error logging level.
665 * By default, PsySH will automatically log all errors, regardless of the
666 * current `error_reporting` level. Additionally, if the `error_reporting`
667 * level warrants, an ErrorException will be thrown.
669 * Set `errorLoggingLevel` to 0 to prevent logging non-thrown errors. Set it
670 * to any valid error_reporting value to log only errors which match that
673 * http://php.net/manual/en/function.error-reporting.php
677 public function errorLoggingLevel()
679 return $this->errorLoggingLevel;
683 * Set a CodeCleaner service instance.
685 * @param CodeCleaner $cleaner
687 public function setCodeCleaner(CodeCleaner $cleaner)
689 $this->cleaner = $cleaner;
693 * Get a CodeCleaner service instance.
695 * If none has been explicitly defined, this will create a new instance.
697 * @return CodeCleaner
699 public function getCodeCleaner()
701 if (!isset($this->cleaner)) {
702 $this->cleaner = new CodeCleaner();
705 return $this->cleaner;
709 * Enable or disable tab completion.
711 * @param bool $tabCompletion
713 public function setTabCompletion($tabCompletion)
715 $this->tabCompletion = (bool) $tabCompletion;
719 * Check whether to use tab completion.
721 * If `setTabCompletion` has been set to true, but readline is not actually
722 * available, this will return false.
724 * @return bool True if the current Shell should use tab completion
726 public function getTabCompletion()
728 return isset($this->tabCompletion) ? ($this->hasReadline && $this->tabCompletion) : $this->hasReadline;
732 * Set the Shell Output service.
734 * @param ShellOutput $output
736 public function setOutput(ShellOutput $output)
738 $this->output = $output;
742 * Get a Shell Output service instance.
744 * If none has been explicitly provided, this will create a new instance
745 * with VERBOSITY_NORMAL and the output page supplied by self::getPager
747 * @see self::getPager
749 * @return ShellOutput
751 public function getOutput()
753 if (!isset($this->output)) {
754 $this->output = new ShellOutput(
755 ShellOutput::VERBOSITY_NORMAL,
756 $this->getOutputDecorated(),
762 return $this->output;
766 * Get the decoration (i.e. color) setting for the Shell Output service.
768 * @return null|bool 3-state boolean corresponding to the current color mode
770 public function getOutputDecorated()
772 if ($this->colorMode() === self::COLOR_MODE_AUTO) {
774 } elseif ($this->colorMode() === self::COLOR_MODE_FORCED) {
776 } elseif ($this->colorMode() === self::COLOR_MODE_DISABLED) {
782 * Set the OutputPager service.
784 * If a string is supplied, a ProcOutputPager will be used which shells out
785 * to the specified command.
787 * @throws \InvalidArgumentException if $pager is not a string or OutputPager instance
789 * @param string|OutputPager $pager
791 public function setPager($pager)
793 if ($pager && !is_string($pager) && !$pager instanceof OutputPager) {
794 throw new \InvalidArgumentException('Unexpected pager instance.');
797 $this->pager = $pager;
801 * Get an OutputPager instance or a command for an external Proc pager.
803 * If no Pager has been explicitly provided, and Pcntl is available, this
804 * will default to `cli.pager` ini value, falling back to `which less`.
806 * @return string|OutputPager
808 public function getPager()
810 if (!isset($this->pager) && $this->usePcntl()) {
811 if ($pager = ini_get('cli.pager')) {
812 // use the default pager (5.4+)
813 $this->pager = $pager;
814 } elseif ($less = exec('which less 2>/dev/null')) {
815 // check for the presence of less...
816 $this->pager = $less . ' -R -S -F -X';
824 * Set the Shell evaluation Loop service.
828 public function setLoop(Loop $loop)
834 * Get a Shell evaluation Loop service instance.
836 * If none has been explicitly defined, this will create a new instance.
837 * If Pcntl is available and enabled, the new instance will be a ForkingLoop.
841 public function getLoop()
843 if (!isset($this->loop)) {
844 if ($this->usePcntl()) {
845 $this->loop = new ForkingLoop($this);
847 $this->loop = new Loop($this);
855 * Set the Shell autocompleter service.
857 * @param AutoCompleter $completer
859 public function setAutoCompleter(AutoCompleter $completer)
861 $this->completer = $completer;
865 * Get an AutoCompleter service instance.
867 * @return AutoCompleter
869 public function getAutoCompleter()
871 if (!isset($this->completer)) {
872 $this->completer = new AutoCompleter();
875 return $this->completer;
879 * Get user specified tab completion matchers for the AutoCompleter.
883 public function getTabCompletionMatchers()
885 return $this->tabCompletionMatchers;
889 * Add additional tab completion matchers to the AutoCompleter.
891 * @param array $matchers
893 public function addTabCompletionMatchers(array $matchers)
895 $this->tabCompletionMatchers = array_merge($this->tabCompletionMatchers, $matchers);
896 if (isset($this->shell)) {
897 $this->shell->addTabCompletionMatchers($this->tabCompletionMatchers);
902 * Add commands to the Shell.
904 * This will buffer new commands in the event that the Shell has not yet
905 * been instantiated. This allows the user to specify commands in their
906 * config rc file, despite the fact that their file is needed in the Shell
909 * @param array $commands
911 public function addCommands(array $commands)
913 $this->newCommands = array_merge($this->newCommands, $commands);
914 if (isset($this->shell)) {
915 $this->doAddCommands();
920 * Internal method for adding commands. This will set any new commands once
921 * a Shell is available.
923 private function doAddCommands()
925 if (!empty($this->newCommands)) {
926 $this->shell->addCommands($this->newCommands);
927 $this->newCommands = array();
932 * Set the Shell backreference and add any new commands to the Shell.
934 * @param Shell $shell
936 public function setShell(Shell $shell)
938 $this->shell = $shell;
939 $this->doAddCommands();
943 * Set the PHP manual database file.
945 * This file should be an SQLite database generated from the phpdoc source
946 * with the `bin/build_manual` script.
948 * @param string $filename
950 public function setManualDbFile($filename)
952 $this->manualDbFile = (string) $filename;
956 * Get the current PHP manual database file.
958 * @return string Default: '~/.local/share/psysh/php_manual.sqlite'
960 public function getManualDbFile()
962 if (isset($this->manualDbFile)) {
963 return $this->manualDbFile;
966 $files = ConfigPaths::getDataFiles(array('php_manual.sqlite'), $this->dataDir);
967 if (!empty($files)) {
968 if ($this->warnOnMultipleConfigs && count($files) > 1) {
969 $msg = sprintf('Multiple manual database files found: %s. Using %s', implode($files, ', '), $files[0]);
970 trigger_error($msg, E_USER_NOTICE);
973 return $this->manualDbFile = $files[0];
978 * Get a PHP manual database connection.
982 public function getManualDb()
984 if (!isset($this->manualDb)) {
985 $dbFile = $this->getManualDbFile();
986 if (is_file($dbFile)) {
988 $this->manualDb = new \PDO('sqlite:' . $dbFile);
989 } catch (\PDOException $e) {
990 if ($e->getMessage() === 'could not find driver') {
991 throw new RuntimeException('SQLite PDO driver not found', 0, $e);
999 return $this->manualDb;
1003 * Add an array of casters definitions.
1005 * @param array $casters
1007 public function addCasters(array $casters)
1009 $this->getPresenter()->addCasters($casters);
1013 * Get the Presenter service.
1017 public function getPresenter()
1019 if (!isset($this->presenter)) {
1020 $this->presenter = new Presenter($this->getOutput()->getFormatter());
1023 return $this->presenter;
1027 * Enable or disable warnings on multiple configuration or data files.
1029 * @see self::warnOnMultipleConfigs()
1031 * @param bool $warnOnMultipleConfigs
1033 public function setWarnOnMultipleConfigs($warnOnMultipleConfigs)
1035 $this->warnOnMultipleConfigs = (bool) $warnOnMultipleConfigs;
1039 * Check whether to warn on multiple configuration or data files.
1041 * By default, PsySH will use the file with highest precedence, and will
1042 * silently ignore all others. With this enabled, a warning will be emitted
1043 * (but not an exception thrown) if multiple configuration or data files
1046 * This will default to true in a future release, but is false for now.
1050 public function warnOnMultipleConfigs()
1052 return $this->warnOnMultipleConfigs;
1056 * Set the current color mode.
1058 * @param string $colorMode
1060 public function setColorMode($colorMode)
1062 $validColorModes = array(
1063 self::COLOR_MODE_AUTO,
1064 self::COLOR_MODE_FORCED,
1065 self::COLOR_MODE_DISABLED,
1068 if (in_array($colorMode, $validColorModes)) {
1069 $this->colorMode = $colorMode;
1071 throw new \InvalidArgumentException('invalid color mode: ' . $colorMode);
1076 * Get the current color mode.
1080 public function colorMode()
1082 return $this->colorMode;
1086 * Set an update checker service instance.
1088 * @param Checker $checker
1090 public function setChecker(Checker $checker)
1092 $this->checker = $checker;
1096 * Get an update checker service instance.
1098 * If none has been explicitly defined, this will create a new instance.
1102 public function getChecker()
1104 if (!isset($this->checker)) {
1105 $interval = $this->getUpdateCheck();
1106 switch ($interval) {
1107 case Checker::ALWAYS:
1108 $this->checker = new GitHubChecker();
1111 case Checker::DAILY:
1112 case Checker::WEEKLY:
1113 case Checker::MONTHLY:
1114 $checkFile = $this->getUpdateCheckCacheFile();
1115 if ($checkFile === false) {
1116 $this->checker = new NoopChecker();
1118 $this->checker = new IntervalChecker($checkFile, $interval);
1122 case Checker::NEVER:
1123 $this->checker = new NoopChecker();
1128 return $this->checker;
1132 * Get the current update check interval.
1134 * One of 'always', 'daily', 'weekly', 'monthly' or 'never'. If none is
1135 * explicitly set, default to 'weekly'.
1139 public function getUpdateCheck()
1141 return isset($this->updateCheck) ? $this->updateCheck : Checker::WEEKLY;
1145 * Set the update check interval.
1147 * @throws \InvalidArgumentDescription if the update check interval is unknown
1149 * @param string $interval
1151 public function setUpdateCheck($interval)
1153 $validIntervals = array(
1161 if (!in_array($interval, $validIntervals)) {
1162 throw new \InvalidArgumentException('invalid update check interval: ' . $interval);
1165 $this->updateCheck = $interval;
1169 * Get a cache file path for the update checker.
1171 * @return string|false Return false if config file/directory is not writable
1173 public function getUpdateCheckCacheFile()
1175 $dir = $this->configDir ?: ConfigPaths::getCurrentConfigDir();
1177 return ConfigPaths::touchFileWithMkdir($dir . '/update_check.json');
1181 * Set the startup message.
1183 * @param string $message
1185 public function setStartupMessage($message)
1187 $this->startupMessage = $message;
1191 * Get the startup message.
1193 * @return string|null
1195 public function getStartupMessage()
1197 return $this->startupMessage;