code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
private final function getToken() { return $this->hash($this->passwordHash . $this->getPublicKey()); }
Get expected valid client authorization token @return string
getToken
php
barbushin/php-console
src/PhpConsole/Auth.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Auth.php
MIT
public static function setPostponeStorage(Storage $storage) { if(self::$instance) { throw new \Exception(__METHOD__ . ' can be called only before ' . __CLASS__ . '::getInstance()'); } self::$postponeStorage = $storage; }
Set storage for postponed response data. Storage\Session is used by default, but if you have problems with overridden session handler you should use another one. IMPORTANT: This method cannot be called after Connector::getInstance() @param Storage $storage @throws \Exception
setPostponeStorage
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
protected function isCliMode() { return PHP_SAPI == 'cli'; }
Detect script is running in command-line mode @return int
isCliMode
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
private function initConnection() { if($this->isCliMode()) { return; } $this->initServerCookie(); $this->client = $this->initClient(); if($this->client) { ob_start(); $this->isActiveClient = true; $this->registerFlushOnShutDown(); $this->setHeadersLimit(isset($_SERVER['SERVER_SOFTWARE']) && stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false ? 4096 // default headers limit for Nginx : 8192 // default headers limit for all other web-servers ); $this->listenGetPostponedResponse(); $this->postponeResponseId = $this->setPostponeHeader(); } }
Notify clients that there is active PHP Console on server & check if there is request from client with active PHP Console @throws \Exception
initConnection
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
private function initClient() { if(isset($_COOKIE[self::CLIENT_INFO_COOKIE])) { $clientData = @json_decode(base64_decode($_COOKIE[self::CLIENT_INFO_COOKIE], true), true); if(!$clientData) { throw new \Exception('Wrong format of response cookie data: ' . $_COOKIE[self::CLIENT_INFO_COOKIE]); } $client = new Client($clientData); if(isset($clientData['auth'])) { $client->auth = new ClientAuth($clientData['auth']); } return $client; } }
Get connected client data( @return Client|null @throws \Exception
initClient
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
private function initServerCookie() { if(!isset($_COOKIE[self::SERVER_COOKIE]) || $_COOKIE[self::SERVER_COOKIE] != self::SERVER_PROTOCOL) { $isSuccess = setcookie(self::SERVER_COOKIE, self::SERVER_PROTOCOL, null, '/'); if(!$isSuccess) { throw new \Exception('Unable to set PHP Console server cookie'); } } }
Notify clients that there is active PHP Console on server @throws \Exception
initServerCookie
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function isActiveClient() { return $this->isActiveClient; }
Check if there is client is installed PHP Console extension @return bool
isActiveClient
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function disable() { $this->isActiveClient = false; }
Set client connection as not active
disable
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function isAuthorized() { return $this->isAuthorized; }
Check if client with valid auth credentials is connected @return bool
isAuthorized
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setAllowedIpMasks(array $ipMasks) { if($this->isActiveClient()) { if(isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; foreach($ipMasks as $ipMask) { if(preg_match('~^' . str_replace(array('.', '*'), array('\.', '\w+'), $ipMask) . '$~i', $ip)) { return; } } } $this->disable(); } }
Set IP masks of clients that will be allowed to connect to PHP Console @param array $ipMasks Use *(star character) for "any numbers" placeholder array('192.168.*.*', '10.2.12*.*', '127.0.0.1', '2001:0:5ef5:79fb:*:*:*:*')
setAllowedIpMasks
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setErrorsDispatcher(Dispatcher\Errors $dispatcher) { $this->errorsDispatcher = $dispatcher; }
Override default errors dispatcher @param Dispatcher\Errors $dispatcher
setErrorsDispatcher
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function getErrorsDispatcher() { if(!$this->errorsDispatcher) { $this->errorsDispatcher = new Dispatcher\Errors($this, $this->getDumper()); } return $this->errorsDispatcher; }
Get dispatcher responsible for sending errors/exceptions messages @return Dispatcher\Errors
getErrorsDispatcher
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setDebugDispatcher(Dispatcher\Debug $dispatcher) { $this->debugDispatcher = $dispatcher; }
Override default debug dispatcher @param Dispatcher\Debug $dispatcher
setDebugDispatcher
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function getDebugDispatcher() { if(!$this->debugDispatcher) { $this->debugDispatcher = new Dispatcher\Debug($this, $this->getDumper()); } return $this->debugDispatcher; }
Get dispatcher responsible for sending debug messages @return Dispatcher\Debug
getDebugDispatcher
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setEvalDispatcher(Dispatcher\Evaluate $dispatcher) { $this->evalDispatcher = $dispatcher; }
Override default eval requests dispatcher @param Dispatcher\Evaluate $dispatcher
setEvalDispatcher
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function getEvalDispatcher() { if(!$this->evalDispatcher) { $this->evalDispatcher = new Dispatcher\Evaluate($this, new EvalProvider(), $this->getDumper()); } return $this->evalDispatcher; }
Get dispatcher responsible for handling eval requests @return Dispatcher\Evaluate
getEvalDispatcher
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function startEvalRequestsListener($exitOnEval = true, $flushDebugMessages = true) { if(!$this->auth) { throw new \Exception('Eval dispatcher is allowed only in password protected mode. See PhpConsole\Connector::getInstance()->setPassword(...)'); } if($this->isEvalListenerStarted) { throw new \Exception('Eval requests listener already started'); } $this->isEvalListenerStarted = true; if($this->isActiveClient() && $this->isAuthorized() && isset($_POST[Connector::POST_VAR_NAME]['eval'])) { $request = $_POST[Connector::POST_VAR_NAME]['eval']; if(!isset($request['data']) || !isset($request['signature'])) { throw new \Exception('Wrong PHP Console eval request'); } if($this->auth->getSignature($request['data']) !== $request['signature']) { throw new \Exception('Wrong PHP Console eval request signature'); } if($flushDebugMessages) { foreach($this->messages as $i => $message) { if($message instanceof DebugMessage) { unset($this->messages[$i]); } } } $this->convertEncoding($request['data'], $this->serverEncoding, self::CLIENT_ENCODING); $this->getEvalDispatcher()->dispatchCode($request['data']); if($exitOnEval) { exit; } } }
Enable eval request to be handled by eval dispatcher. Must be called after all Connector configurations. Connector::getInstance()->setPassword() is required to be called before this method Use Connector::getInstance()->setAllowedIpMasks() for additional access protection Check Connector::getInstance()->getEvalDispatcher()->getEvalProvider() to customize eval accessibility & security options @param bool $exitOnEval @param bool $flushDebugMessages Clear debug messages handled before this method is called @throws \Exception
startEvalRequestsListener
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setSourcesBasePath($sourcesBasePath) { $sourcesBasePath = realpath($sourcesBasePath); if(!$sourcesBasePath) { throw new \Exception('Path "' . $sourcesBasePath . '" not found'); } $this->sourcesBasePath = $sourcesBasePath; }
Set bath to base dir of project source code(so it will be stripped in paths displaying on client) @param $sourcesBasePath @throws \Exception
setSourcesBasePath
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setPassword($password, $publicKeyByIp = true) { if($this->auth) { throw new \Exception('Password already defined'); } $this->convertEncoding($password, self::CLIENT_ENCODING, $this->serverEncoding); $this->auth = new Auth($password, $publicKeyByIp); if($this->client) { $this->isAuthorized = $this->client->auth && $this->auth->isValidAuth($this->client->auth); } }
Protect PHP Console connection by password Use Connector::getInstance()->setAllowedIpMasks() for additional secure @param string $password @param bool $publicKeyByIp Set authorization token depending on client IP @throws \Exception
setPassword
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
protected function jsonEncode($var) { return json_encode($var, defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : null); }
Encode var to JSON with errors & encoding handling @param $var @return string @throws \Exception
jsonEncode
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
protected function convertArrayEncoding(&$data, $toEncoding, $fromEncoding) { array_walk_recursive($data, array($this, 'convertWalkRecursiveItemEncoding'), array($toEncoding, $fromEncoding)); }
Recursive var data encoding conversion @param $data @param $fromEncoding @param $toEncoding
convertArrayEncoding
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
protected function convertWalkRecursiveItemEncoding(&$string, $key = null, array $args) { $this->convertEncoding($string, $args[0], $args[1]); }
Encoding conversion callback for array_walk_recursive() @param string $string @param null $key @param array $args
convertWalkRecursiveItemEncoding
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
protected function convertEncoding(&$string, $toEncoding, $fromEncoding) { if($string && is_string($string) && $toEncoding != $fromEncoding) { static $isMbString; if($isMbString === null) { $isMbString = extension_loaded('mbstring'); } if($isMbString) { $string = @mb_convert_encoding($string, $toEncoding, $fromEncoding) ? : $string; } else { $string = @iconv($fromEncoding, $toEncoding . '//IGNORE', $string) ? : $string; } if(!$string && $toEncoding == 'UTF-8') { $string = utf8_encode($string); } } }
Convert string encoding @param string $string @param string $toEncoding @param string|null $fromEncoding @throws \Exception
convertEncoding
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function setServerEncoding($encoding) { if($encoding == 'utf8' || $encoding == 'utf-8') { $encoding = 'UTF-8'; // otherwise mb_convert_encoding() sometime fails with error(thanks to @alexborisov) } $this->serverEncoding = $encoding; }
Set your server PHP internal encoding, if it's different from "mbstring.internal_encoding" or UTF-8 @param $encoding
setServerEncoding
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function sendMessage(Message $message) { if($this->isActiveClient()) { $this->messages[] = $message; } }
Send data message to PHP Console client(if it's connected) @param Message $message
sendMessage
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function registerFlushOnShutDown() { $this->registeredShutDowns++; register_shutdown_function(array($this, 'onShutDown')); }
Register shut down callback handler. Must be called after all errors handlers register_shutdown_function()
registerFlushOnShutDown
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function onShutDown() { $this->registeredShutDowns--; if(!$this->registeredShutDowns) { $this->proceedResponsePackage(); } }
This method must be called only by register_shutdown_function(). Never call it manually!
onShutDown
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function enableSslOnlyMode() { $this->isSslOnlyMode = true; }
Force connection by SSL for clients with PHP Console installed
enableSslOnlyMode
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
protected function isSsl() { return (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || (isset($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT']) == 443); }
Check if client is connected by SSL @return bool
isSsl
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
private function proceedResponsePackage() { if($this->isActiveClient()) { $response = new Response(); $response->isSslOnlyMode = $this->isSslOnlyMode; if(isset($_POST[self::POST_VAR_NAME]['getBackData'])) { $response->getBackData = $_POST[self::POST_VAR_NAME]['getBackData']; } if(!$this->isSslOnlyMode || $this->isSsl()) { if($this->auth) { $response->auth = $this->auth->getServerAuthStatus($this->client->auth); } if(!$this->auth || $this->isAuthorized()) { $response->isLocal = isset($_SERVER['REMOTE_ADDR']) && ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1'); $response->docRoot = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : null; $response->sourcesBasePath = $this->sourcesBasePath; $response->isEvalEnabled = $this->isEvalListenerStarted; $response->messages = $this->messages; } } $responseData = $this->serializeResponse($response); if(strlen($responseData) > $this->headersLimit || !$this->setHeaderData($responseData, self::HEADER_NAME, false)) { $this->getPostponeStorage()->push($this->postponeResponseId, $responseData); } } }
Send response data to client @throws \Exception
proceedResponsePackage
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
private function listenGetPostponedResponse() { if(isset($_POST[self::POST_VAR_NAME]['getPostponedResponse'])) { header('Content-Type: application/json; charset=' . self::CLIENT_ENCODING); echo $this->getPostponeStorage()->pop($_POST[self::POST_VAR_NAME]['getPostponedResponse']); $this->disable(); exit; } }
Check if there is postponed response request and dispatch it
listenGetPostponedResponse
php
barbushin/php-console
src/PhpConsole/Connector.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Connector.php
MIT
public function __construct(Connector $connector, Dumper $dumper) { $this->connector = $connector; $this->setDumper($dumper); }
@param Connector $connector @param Dumper $dumper
__construct
php
barbushin/php-console
src/PhpConsole/Dispatcher.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher.php
MIT
public function setDumper(Dumper $dumper) { $this->dumper = $dumper; }
Override default dumper @param Dumper $dumper
setDumper
php
barbushin/php-console
src/PhpConsole/Dispatcher.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher.php
MIT
public function isActive() { return $this->connector->isActiveClient(); }
Check if dispatcher is active to send messages @return bool
isActive
php
barbushin/php-console
src/PhpConsole/Dispatcher.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher.php
MIT
protected function fetchTrace(array $trace, &$file = null, &$line = null, $ignoreTraceCalls = 0) { $ignoreByNumber = is_numeric($ignoreTraceCalls) ? $ignoreTraceCalls : 0; $ignoreByClassPrefixes = is_array($ignoreTraceCalls) ? array_merge($ignoreTraceCalls, array(__NAMESPACE__)) : null; foreach($trace as $i => $call) { if(!$file && $i == $ignoreTraceCalls && isset($call['file'])) { $file = $call['file']; $line = $call['line']; } if($ignoreByClassPrefixes && isset($call['class'])) { foreach($ignoreByClassPrefixes as $classPrefix) { if(strpos($call['class'], $classPrefix) !== false) { unset($trace[$i]); continue; } } } if($i < $ignoreByNumber || (isset($call['file']) && $call['file'] == $file && $call['line'] == $line)) { unset($trace[$i]); } } $traceCalls = array(); foreach(array_reverse($trace) as $call) { $args = array(); if(isset($call['args'])) { foreach($call['args'] as $arg) { if(is_object($arg)) { $args[] = get_class($arg); } elseif(is_array($arg)) { $args[] = 'Array[' . count($arg) . ']'; } else { $arg = var_export($arg, 1); $args[] = strlen($arg) > 15 ? substr($arg, 0, 15) . '...\'' : $arg; } } } if(strpos($call['function'], '{closure}')) { $call['function'] = '{closure}'; } $traceCall = new TraceCall(); $traceCall->call = (isset($call['class']) ? $call['class'] . $call['type'] : '') . $call['function'] . '(' . implode(', ', $args) . ')'; if(isset($call['file'])) { $traceCall->file = $call['file']; } if(isset($call['line'])) { $traceCall->line = $call['line']; } $traceCalls[] = $traceCall; } return $traceCalls; }
Convert backtrace to array of TraceCall with source file & line detection @param array $trace Standard PHP backtrace array @param null|string $file Reference to var that will contain source file path @param null|string $line Reference to var that will contain source line number @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore @return TraceCall[]
fetchTrace
php
barbushin/php-console
src/PhpConsole/Dispatcher.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher.php
MIT
public function evaluate($code) { $code = $this->applyHandlersToCode($code); $code = $this->adaptCodeToEval($code); $this->backupGlobals(); $this->applyOpenBaseDirSetting(); $startTime = microtime(true); static::executeCode('', $this->sharedVars); $selfTime = microtime(true) - $startTime; ob_start(); $result = new EvalResult(); $startTime = microtime(true); try { $result->return = static::executeCode($code, $this->sharedVars); } catch(\Throwable $exception) { $result->exception = $exception; } catch(\Exception $exception) { $result->exception = $exception; } $result->time = abs(microtime(true) - $startTime - $selfTime); $result->output = ob_get_clean(); $this->restoreGlobals(); return $result; }
Execute PHP code handling execution time, output & exception @param string $code @return EvalResult
evaluate
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
public function addCodeHandler($callback) { if(!is_callable($callback)) { throw new \Exception('Argument is not callable'); } $this->codeCallbackHandlers[] = $callback; }
Add callback that will be called with &$code var reference before code execution @param $callback @throws \Exception
addCodeHandler
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function applyHandlersToCode($code) { foreach($this->codeCallbackHandlers as $callback) { call_user_func_array($callback, array(&$code)); } return $code; }
Call added code handlers @param $code @return mixed
applyHandlersToCode
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function backupGlobals() { $this->globalsBackup = array(); foreach($GLOBALS as $key => $value) { if($key != 'GLOBALS') { $this->globalsBackup[$key] = $value; } } }
Store global vars data in backup var
backupGlobals
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function restoreGlobals() { foreach($this->globalsBackup as $key => $value) { $GLOBALS[$key] = $value; } foreach(array_diff(array_keys($GLOBALS), array_keys($this->globalsBackup)) as $newKey) { if($newKey != 'GLOBALS') { unset($GLOBALS[$newKey]); } } }
Restore global vars data from backup var
restoreGlobals
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected static function executeCode($_code, array $_sharedVars) { foreach($_sharedVars as $var => $value) { if(isset($GLOBALS[$var]) && $var[0] == '_') { // extract($this->sharedVars, EXTR_OVERWRITE) and $$var = $value do not overwrites global vars $GLOBALS[$var] = $value; } elseif(!isset($$var)) { $$var = $value; } } return eval($_code); }
Execute code with shared vars @param $_code @param array $_sharedVars @return mixed
executeCode
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function trimPhpTags($code) { $replace = array( '~^(\s*)<\?=~s' => '\1echo ', '~^(\s*)<\?(php)?~is' => '\1', '~\?>\s*$~s' => '', '~<\?(php)?[\s;]*$~is' => '', ); return preg_replace(array_keys($replace), $replace, $code); }
Prepare code PHP tags be correctly passed to eval() function @param string $code @return string
trimPhpTags
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function forceEndingSemicolon($code) { $code = rtrim($code, "; \r\n"); return $code[strlen($code) - 1] != '}' ? $code . ';' : $code; }
Add semicolon to the end of code if it's required @param string $code @return string
forceEndingSemicolon
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function adaptCodeToEval($code) { $code = $this->trimPhpTags($code); $code = $this->forceEndingSemicolon($code); return $code; }
Apply some default code handlers @param string $code @return string
adaptCodeToEval
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
public function setOpenBaseDirs(array $openBaseDirs) { $this->openBaseDirs = $openBaseDirs; }
Protect response code access only to specified directories using http://www.php.net/manual/en/ini.core.php#ini.open-basedir IMPORTANT: classes autoload methods will work only for specified directories @param array $openBaseDirs @codeCoverageIgnore
setOpenBaseDirs
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function forcePhpConsoleClassesAutoLoad() { foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__), \RecursiveIteratorIterator::LEAVES_ONLY) as $path) { /** @var $path \SplFileInfo */ if($path->isFile() && $path->getExtension() == 'php' && $path->getFilename() !== 'PsrLogger.php') { require_once($path->getPathname()); } } }
Autoload all PHP Console classes @codeCoverageIgnore
forcePhpConsoleClassesAutoLoad
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
protected function applyOpenBaseDirSetting() { if($this->openBaseDirs) { $value = implode(PATH_SEPARATOR, $this->openBaseDirs); if(ini_get('open_basedir') != $value) { $this->forcePhpConsoleClassesAutoLoad(); if(ini_set('open_basedir', $value) === false) { throw new \Exception('Unable to set "open_basedir" php.ini setting'); } } } }
Set actual "open_basedir" PHP ini option @throws \Exception @codeCoverageIgnore
applyOpenBaseDirSetting
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
public function disableFileAccessByOpenBaseDir() { $this->setOpenBaseDirs(array(__DIR__ . '/not_existed_dir' . mt_rand())); }
Protect response code from reading/writing/including any files using http://www.php.net/manual/en/ini.core.php#ini.open-basedir IMPORTANT: It does not protects from system(), exec(), passthru(), popen() & etc OS commands execution functions IMPORTANT: Classes autoload methods will not work, so all required classes must be loaded before code evaluation @codeCoverageIgnore
disableFileAccessByOpenBaseDir
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
public function addSharedVar($name, $var) { $this->addSharedVarReference($name, $var); }
Add var that will be implemented in PHP code executed from PHP Console debug panel (will be implemented in PHP Console > v3.0) @param $name @param $var @throws \Exception
addSharedVar
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
public function addSharedVarReference($name, &$var) { if(isset($this->sharedVars[$name])) { throw new \Exception('Var with name "' . $name . '" already added'); } $this->sharedVars[$name] =& $var; }
Add var that will be implemented in PHP code executed from PHP Console debug panel (will be implemented in PHP Console > v3.0) @param $name @param $var @throws \Exception
addSharedVarReference
php
barbushin/php-console
src/PhpConsole/EvalProvider.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/EvalProvider.php
MIT
public function start() { if($this->isStarted) { throw new \Exception(get_called_class() . ' is already started, use ' . get_called_class() . '::getInstance()->isStarted() to check it.'); } $this->isStarted = true; if($this->handleErrors) { $this->initErrorsHandler(); } if($this->handleExceptions) { $this->initExceptionsHandler(); } }
Start errors & exceptions handlers @throws \Exception
start
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
protected function checkIsCalledBeforeStart() { if($this->isStarted) { throw new \Exception('This method can be called only before ' . get_class($this) . '::start()'); } }
Validate that method is called before start. Required for handlers configuration methods. @throws \Exception
checkIsCalledBeforeStart
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function setHandleErrors($isEnabled) { $this->checkIsCalledBeforeStart(); $this->handleErrors = $isEnabled; // @codeCoverageIgnore }
Enable or disable errors handler @param bool $isEnabled
setHandleErrors
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function setHandleExceptions($isEnabled) { $this->checkIsCalledBeforeStart(); $this->handleExceptions = $isEnabled; // @codeCoverageIgnore }
Enable or disable exceptions handler @param bool $isEnabled
setHandleExceptions
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function setCallOldHandlers($isEnabled) { $this->callOldHandlers = $isEnabled; }
Enable or disable calling overridden errors & exceptions @param bool $isEnabled
setCallOldHandlers
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function isStarted() { return $this->isStarted; }
Check if PHP Console handler is started @return bool
isStarted
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
protected function initExceptionsHandler() { $this->oldExceptionsHandler = set_exception_handler(array($this, 'handleException')); }
Override PHP exceptions handler to PHP Console handler
initExceptionsHandler
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function setErrorsHandlerLevel($level) { $this->checkIsCalledBeforeStart(); $this->errorsHandlerLevel = $level; }
Set custom errors handler level like E_ALL ^ E_STRICT But, anyway, it's strongly recommended to configure ignore some errors type in PHP Console extension options IMPORTANT: previously old error handler will be called only with new errors level @param int $level see http://us1.php.net/manual/ru/function.error-reporting.php
setErrorsHandlerLevel
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
protected function initErrorsHandler() { ini_set('display_errors', false); error_reporting($this->errorsHandlerLevel ? : E_ALL | E_STRICT); $this->oldErrorsHandler = set_error_handler(array($this, 'handleError')); register_shutdown_function(array($this, 'checkFatalErrorOnShutDown')); $this->connector->registerFlushOnShutDown(); }
Override PHP errors handler to PHP Console handler
initErrorsHandler
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function checkFatalErrorOnShutDown() { $error = error_get_last(); if($error) { ini_set('memory_limit', memory_get_usage(true) + 1000000); // if memory limit exceeded $this->callOldHandlers = false; $this->handleError($error['type'], $error['message'], $error['file'], $error['line'], null, 1); } }
Method is called by register_shutdown_function(), it's required to handle fatal PHP errors. Never call it manually. @codeCoverageIgnore
checkFatalErrorOnShutDown
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function handleError($code = null, $text = null, $file = null, $line = null, $context = null, $ignoreTraceCalls = 0) { if(!$this->isStarted || error_reporting() === 0 || $this->isHandlingDisabled() || ($this->errorsHandlerLevel && !($code & $this->errorsHandlerLevel))) { return; } $this->onHandlingStart(); $this->connector->getErrorsDispatcher()->dispatchError($code, $text, $file, $line, is_numeric($ignoreTraceCalls) ? $ignoreTraceCalls + 1 : $ignoreTraceCalls); if($this->oldErrorsHandler && $this->callOldHandlers) { call_user_func_array($this->oldErrorsHandler, array($code, $text, $file, $line, $context)); } $this->onHandlingComplete(); }
Handle error data @param int|null $code @param string|null $text @param string|null $file @param int|null $line @param null $context @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore
handleError
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
protected function isHandlingDisabled() { return $this->recursiveHandlingLevel >= static::ERRORS_RECURSION_LIMIT; }
Check if errors/exception handling is disabled @return bool
isHandlingDisabled
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function handleException($exception) { if(!$this->isStarted || $this->isHandlingDisabled()) { return; } try { $this->onHandlingStart(); $this->connector->getErrorsDispatcher()->dispatchException($exception); if($this->oldExceptionsHandler && $this->callOldHandlers) { call_user_func($this->oldExceptionsHandler, $exception); } } catch(\Throwable $internalException) { $this->handleException($internalException); } catch(\Exception $internalException) { $this->handleException($internalException); } $this->onHandlingComplete(); }
Handle exception object @param \Exception|\Throwable $exception
handleException
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public function debug($data, $tags = null, $ignoreTraceCalls = 0) { if($this->connector->isActiveClient()) { $this->connector->getDebugDispatcher()->dispatchDebug($data, $tags, is_numeric($ignoreTraceCalls) ? $ignoreTraceCalls + 1 : $ignoreTraceCalls); } }
Handle debug data @param mixed $data @param string|null $tags Tags separated by dot, e.g. "low.db.billing" @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore
debug
php
barbushin/php-console
src/PhpConsole/Handler.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Handler.php
MIT
public static function register(Connector $connector = null, Handler $handler = null) { if(static::$connector) { throw new \Exception('Helper already registered'); } self::$handler = $handler; self::$connector = $connector ? : Connector::getInstance(); self::$isActive = self::$connector->isActiveClient(); return self::$connector; }
This method must be called to make class "PC" available @param Connector|null $connector @param Handler|null $handler @throws \Exception @return Connector
register
php
barbushin/php-console
src/PhpConsole/Helper.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Helper.php
MIT
public static function isRegistered() { return isset(self::$connector); }
Check if method Helper::register() was called before @return bool
isRegistered
php
barbushin/php-console
src/PhpConsole/Helper.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Helper.php
MIT
public static function getConnector() { if(!self::$connector) { throw new \Exception('Helper is not registered. Call ' . get_called_class() . '::register()'); } return self::$connector; }
Get actual helper connector instance @return Connector @throws \Exception
getConnector
php
barbushin/php-console
src/PhpConsole/Helper.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Helper.php
MIT
public static function getHandler() { if(!self::$connector) { throw new \Exception('Helper is not registered. Call ' . get_called_class() . '::register()'); } if(!self::$handler) { self::$handler = Handler::getInstance(); } return self::$handler; }
Get actual handler instance @return Handler @throws \Exception
getHandler
php
barbushin/php-console
src/PhpConsole/Helper.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Helper.php
MIT
public static function debug($data, $tags = null, $ignoreTraceCalls = 0) { if(self::$isActive) { self::$connector->getDebugDispatcher()->dispatchDebug($data, $tags, is_numeric($ignoreTraceCalls) ? $ignoreTraceCalls + 1 : $ignoreTraceCalls); } }
Analog of Handler::getInstance()->debug(...) method @param mixed $data @param string|null $tags Tags separated by dot, e.g. "low.db.billing" @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore
debug
php
barbushin/php-console
src/PhpConsole/Helper.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Helper.php
MIT
public static function __callStatic($tags, $args) { if(isset($args[1])) { $tags .= '.' . $args[1]; } static::debug(isset($args[0]) ? $args[0] : null, $tags, 1); }
Short access to analog of Handler::getInstance()->debug(...) method You can access it like PC::tagName($debugData, $additionalTags = null) @param string $tags @param $args
__callStatic
php
barbushin/php-console
src/PhpConsole/Helper.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Helper.php
MIT
public static function start($handleErrors = true, $handleExceptions = true, $sourceBasePath = null) { if(self::$instance) { die('PhpConsole already started'); } self::$instance = new static(); $handler = Handler::getInstance(); $handler->setHandleErrors($handleErrors); $handler->setHandleExceptions($handleExceptions); $handler->setCallOldHandlers(self::$callOldErrorHandler || self::$callOldExceptionsHandler); $handler->start(); $connector = $handler->getConnector(); $connector->setSourcesBasePath($sourceBasePath); }
Start PhpConsole v1 handler @param bool $handleErrors @param bool $handleExceptions @param null|string $sourceBasePath
start
php
barbushin/php-console
src/PhpConsole/OldVersionAdapter.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/OldVersionAdapter.php
MIT
public function __construct(Connector $connector = null, Dumper $contextDumper = null, $ignoreTraceCalls = 1) { $this->connector = $connector ?: Connector::getInstance(); $this->contextDumper = $contextDumper ?: $this->connector->getDumper(); $this->ignoreTraceCalls = $ignoreTraceCalls; }
@param Connector|null $connector @param Dumper|null $contextDumper @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore
__construct
php
barbushin/php-console
src/PhpConsole/PsrLogger.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/PsrLogger.php
MIT
public function setKeyLifetime($seconds) { $this->keyLifetime = $seconds; }
Set maximum key lifetime in seconds @param int $seconds
setKeyLifetime
php
barbushin/php-console
src/PhpConsole/Storage.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage.php
MIT
public function dispatchDebug($data, $tags = null, $ignoreTraceCalls = 0) { if($this->isActive()) { $message = new DebugMessage(); $message->data = $this->dumper->dump($data); if($tags) { $message->tags = explode('.', $tags); } if($this->detectTraceAndSource && $ignoreTraceCalls !== null) { $message->trace = $this->fetchTrace(debug_backtrace(), $message->file, $message->line, $ignoreTraceCalls); } $this->sendMessage($message); } }
Send debug data message to client @param mixed $data @param null|string $tags Tags separated by dot, e.g. "low.db.billing" @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore
dispatchDebug
php
barbushin/php-console
src/PhpConsole/Dispatcher/Debug.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Debug.php
MIT
public function dispatchError($code = null, $text = null, $file = null, $line = null, $ignoreTraceCalls = 0) { if($this->isActive()) { $message = new ErrorMessage(); $message->code = $code; $message->class = $this->getErrorTypeByCode($code); $message->data = $this->dumper->dump($text); $message->file = $file; $message->line = $line; if($ignoreTraceCalls !== null) { $message->trace = $this->fetchTrace(debug_backtrace(), $file, $line, is_array($ignoreTraceCalls) ? $ignoreTraceCalls : $ignoreTraceCalls + 1); } $this->sendMessage($message); } }
Send error message to client @param null|integer $code @param null|string $text @param null|string $file @param null|integer $line @param int|array $ignoreTraceCalls Ignore tracing classes by name prefix `array('PhpConsole')` or fixed number of calls to ignore
dispatchError
php
barbushin/php-console
src/PhpConsole/Dispatcher/Errors.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Errors.php
MIT
public function dispatchException($exception) { if($this->isActive()) { if($this->dispatchPreviousExceptions && $exception->getPrevious()) { $this->dispatchException($exception->getPrevious()); } $message = new ErrorMessage(); $message->code = $exception->getCode(); $message->class = get_class($exception); $message->data = $this->dumper->dump($exception->getMessage()); $message->file = $exception->getFile(); $message->line = $exception->getLine(); $message->trace = self::fetchTrace($exception->getTrace(), $message->file, $message->line); $this->sendMessage($message); } }
Send exception message to client @param \Exception|\Throwable $exception
dispatchException
php
barbushin/php-console
src/PhpConsole/Dispatcher/Errors.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Errors.php
MIT
protected function sendMessage(Message $message) { if(!$this->isIgnored($message)) { parent::sendMessage($message); $this->sentMessages[] = $message; } }
Send message to PHP Console connector @param Message $message
sendMessage
php
barbushin/php-console
src/PhpConsole/Dispatcher/Errors.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Errors.php
MIT
protected function getErrorTypeByCode($code) { if(!static::$errorsConstantsValues) { foreach(static::$errorsConstantsNames as $constantName) { if(defined($constantName)) { static::$errorsConstantsValues[constant($constantName)] = $constantName; } } } if(isset(static::$errorsConstantsValues[$code])) { return static::$errorsConstantsValues[$code]; } return (string)$code; }
Get PHP error constant name by value @param int $code @return string
getErrorTypeByCode
php
barbushin/php-console
src/PhpConsole/Dispatcher/Errors.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Errors.php
MIT
protected function isIgnored(ErrorMessage $message) { if($this->ignoreRepeatedSource && $message->file) { foreach($this->sentMessages as $sentMessage) { if($message->file == $sentMessage->file && $message->line == $sentMessage->line && $message->class == $sentMessage->class) { return true; } } } return false; }
Return true if message with same file, line & class was already sent @param ErrorMessage $message @return bool
isIgnored
php
barbushin/php-console
src/PhpConsole/Dispatcher/Errors.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Errors.php
MIT
public function __construct(Connector $connector, EvalProvider $evalProvider, Dumper $dumper) { $this->evalProvider = $evalProvider; parent::__construct($connector, $dumper); }
@param Connector $connector @param EvalProvider $evalProvider @param Dumper $dumper
__construct
php
barbushin/php-console
src/PhpConsole/Dispatcher/Evaluate.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Evaluate.php
MIT
public function setEvalProvider(EvalProvider $evalProvider) { $this->evalProvider = $evalProvider; }
Override eval provider @param EvalProvider $evalProvider
setEvalProvider
php
barbushin/php-console
src/PhpConsole/Dispatcher/Evaluate.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Evaluate.php
MIT
public function dispatchCode($code) { if($this->isActive()) { $previousLastError = error_get_last(); $oldDisplayErrors = ini_set('display_errors', false); $result = $this->evalProvider->evaluate($code); ini_set('display_errors', $oldDisplayErrors); $message = new EvalResultMessage(); $message->return = $this->dumper->dump($result->return); $message->output = $this->dumper->dump($result->output); $message->time = round($result->time, 6); $newLastError = error_get_last(); if($newLastError && $newLastError != $previousLastError) { $this->connector->getErrorsDispatcher()->dispatchError($newLastError ['type'], $newLastError ['message'], $newLastError ['file'], $newLastError ['line'], 999); } if($result->exception) { $this->connector->getErrorsDispatcher()->dispatchException($result->exception); } $this->sendMessage($message); } }
Execute PHP code and send result message in connector @param $code
dispatchCode
php
barbushin/php-console
src/PhpConsole/Dispatcher/Evaluate.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Dispatcher/Evaluate.php
MIT
public function pop($key) { $keysData = $this->getKeysData(); if(isset($keysData[$key])) { $keyData = $keysData[$key]['data']; unset($keysData[$key]); $this->saveKeysData($keysData); return $keyData; } }
Get postponed data from storage and delete @param string $key @return string
pop
php
barbushin/php-console
src/PhpConsole/Storage/AllKeysList.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/AllKeysList.php
MIT
public function push($key, $data) { $keysData = $this->getKeysData(); $this->clearExpiredKeys($keysData); $keysData[$key] = array( 'time' => time(), 'data' => $data ); $this->saveKeysData($keysData); }
Save postponed data to storage @param string $key @param string $data
push
php
barbushin/php-console
src/PhpConsole/Storage/AllKeysList.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/AllKeysList.php
MIT
public function pop($key) { $data = $this->get($key); if($data) { $this->delete($key); } return $data; }
Get postponed data from storage and delete @param string $key @return string
pop
php
barbushin/php-console
src/PhpConsole/Storage/ExpiringKeyValue.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/ExpiringKeyValue.php
MIT
public function push($key, $data) { $this->set($key, $data, $this->keyLifetime); }
Save postponed data to storage @param string $key @param string $data
push
php
barbushin/php-console
src/PhpConsole/Storage/ExpiringKeyValue.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/ExpiringKeyValue.php
MIT
public function __construct($filePath, $validatePathNotUnderDocRoot = true) { if(!file_exists($filePath)) { if(file_put_contents($filePath, '') === false) { throw new \Exception('Unable to write file ' . $filePath); } } $this->filePath = realpath($filePath); if($validatePathNotUnderDocRoot && $this->isPathUnderDocRoot()) { throw new \Exception('Path ' . $this->filePath . ' is under DOCUMENT_ROOT. It\'s insecure!'); } }
@param string $filePath Writable path for postponed data storage (should not be under DOCUMENT_ROOT) @param bool $validatePathNotUnderDocRoot Throw \Exception if $filePath is not under DOCUMENT_ROOT @throws \Exception
__construct
php
barbushin/php-console
src/PhpConsole/Storage/File.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/File.php
MIT
protected function set($key, $data, $expire) { $this->memcache->set($key, $data, null, $expire); }
Save data by auto-expire key @param $key @param string $data @param int $expire
set
php
barbushin/php-console
src/PhpConsole/Storage/Memcache.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/Memcache.php
MIT
protected function get($key) { return $this->memcache->get($key); }
Get data by key if not expired @param $key @return string
get
php
barbushin/php-console
src/PhpConsole/Storage/Memcache.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/Memcache.php
MIT
protected function set($key, $data, $expire) { $this->mongoCollection->update(array( 'key' => $key ), array( 'key' => $key, 'data' => $data, 'expireAt' => new \MongoDate(time() + $expire) ), array( 'upsert' => true )); }
Save data by auto-expire key @param $key @param string $data @param int $expire
set
php
barbushin/php-console
src/PhpConsole/Storage/MongoDB.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/MongoDB.php
MIT
protected function get($key) { $record = $this->mongoCollection->findOne(array('key' => $key)); if($record && is_array($record) && array_key_exists('data', $record)) { return $record['data']; } }
Get data by key if not expired @param $key @return string
get
php
barbushin/php-console
src/PhpConsole/Storage/MongoDB.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/MongoDB.php
MIT
protected function delete($key) { return $this->mongoCollection->remove(array('key' => $key)); }
Remove key in store @param $key @return mixed
delete
php
barbushin/php-console
src/PhpConsole/Storage/MongoDB.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/MongoDB.php
MIT
public function __construct($sessionKey = '__PHP_Console_postponed', $autoStart = true) { if($autoStart && (defined('PHP_SESSION_ACTIVE') ? session_status() != PHP_SESSION_ACTIVE : !session_id()) && !headers_sent()) { session_start(); } register_shutdown_function('session_write_close'); // force saving session data if session handler is overridden $this->sessionKey = $sessionKey; }
@param string $sessionKey Key name in $_SESSION variable @param bool $autoStart Start session if it's not started
__construct
php
barbushin/php-console
src/PhpConsole/Storage/Session.php
https://github.com/barbushin/php-console/blob/master/src/PhpConsole/Storage/Session.php
MIT
public function sendRequest(Request $request, $postponedResponseId = null, $postponedOutput = null) { if(!$this->serverWrapperUrl) { throw new \Exception('Unable to send request because server wrapper URL is not specified'); } $clientData = $request->getClientData(); if($clientData) { $request->cookies[\PhpConsole\Connector::CLIENT_INFO_COOKIE] = base64_encode(json_encode($clientData)); } if($postponedResponseId) { $request->postData[\PhpConsole\Connector::POST_VAR_NAME] = array( 'getPostponedResponse' => $postponedResponseId ); } $request->postData[static::POST_VAR_NAME] = array( 'scripts' => $request->getScripts(), ); $postData = $request->postData; array_walk_recursive($postData, function (&$item) { if(!is_object($item)) { $item = base64_encode($item); } }); $rawPostData = serialize($postData); $url = $request->isSsl ? str_replace('http://', 'https://', $this->serverWrapperUrl) : $this->serverWrapperUrl; $curlOptions = array( CURLOPT_URL => $url . '?signature=' . $this->getPostDataSignature($rawPostData), CURLOPT_CONNECTTIMEOUT => 2, CURLOPT_TIMEOUT => 5, CURLOPT_HEADER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $rawPostData, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, ); if($request->cookies) { $cookiesData = array(); foreach($request->cookies as $name => $value) { $cookiesData[] = rawurlencode($name) . '=' . rawurlencode($value); } $curlOptions[CURLOPT_COOKIE] = implode('; ', $cookiesData); } $curlHandle = curl_init(); curl_setopt_array($curlHandle, $curlOptions); $responseData = curl_exec($curlHandle); $code = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE); $error = curl_error($curlHandle); $responseHeaders = substr($responseData, 0, curl_getinfo($curlHandle, CURLINFO_HEADER_SIZE)); if(substr($responseHeaders, -1) !== "\n") { // because curl_getinfo($curlHandle, CURLINFO_HEADER_SIZE) is bugged on some PHP versions $responseHeaders = substr($responseData, 0, strpos($responseData, PHP_EOL . PHP_EOL)); } $responseOutput = substr($responseData, strlen($responseHeaders)); curl_close($curlHandle); $response = new Response(); $response->code = $code; $response->output = (string)($postponedResponseId ? $postponedOutput : $responseOutput); $response->headerData = $this->parseHeaderData($responseHeaders); $response->cookies = $this->parseCookies($responseHeaders); try { if($error || ($code != 200 && $code != 204 && $code != 500)) { throw new \Exception('Connection to "' . $this->serverWrapperUrl . '" failed with code "' . $code . '" and error: ' . $error . '" and response: "' . $responseOutput, $code); } $packageEncodedData = $postponedResponseId ? $responseOutput : $response->headerData; if($packageEncodedData) { $packageData = $this->jsonDecode($packageEncodedData); if(!empty($packageData['isPostponed'])) { $request->cookies = $response->cookies; $response = $this->sendRequest($request, $packageData['id'], $responseOutput); $response->isPostponed = true; return $response; } $response->package = $this->initResponsePackage($packageData); } } catch(\Exception $exception) { throw new RequestFailed($exception, $request, $response); } return $response; }
@param Request $request @param bool $postponedResponseId @param null $postponedOutput @return Response @throws RequestFailed @throws \Exception
sendRequest
php
barbushin/php-console
test/ClientEmulator/Connector.php
https://github.com/barbushin/php-console/blob/master/test/ClientEmulator/Connector.php
MIT
protected function initResponsePackage(array $packageData) { $package = new \PhpConsole\Response($packageData); if($package->auth) { $package->auth = new ServerAuthStatus($package->auth); } return $package; }
@param array $packageData @throws \Exception @return Response|null
initResponsePackage
php
barbushin/php-console
test/ClientEmulator/Connector.php
https://github.com/barbushin/php-console/blob/master/test/ClientEmulator/Connector.php
MIT
function getLogs() { $messagesData = array(); foreach($this->sentMessages as $message) { if($message instanceof ErrorMessage) { $messagesData[] = array_search($message->class, \PhpConsole\PsrLogger::$errorsLevels) . ' ' . $message->data; } elseif($message instanceof DebugMessage) { $messagesData[] = array_search($message->tags[0], \PhpConsole\PsrLogger::$debugLevels) . ' ' . $message->data; } } return $messagesData; }
This must return the log messages in order with a simple formatting: "<LOG LEVEL> <MESSAGE>" Example ->error('Foo') would yield "error Foo" @return string[]
getLogs
php
barbushin/php-console
test/Test/PsrLoggerTest.php
https://github.com/barbushin/php-console/blob/master/test/Test/PsrLoggerTest.php
MIT
public function testSetAllowedIpMasks($allowedIpMask, $clientIp, $expectIsAllowed) { $this->request->addScript('set_connector_allowed_ip', array( 'clientIp' => $clientIp, 'ipMasks' => is_array($allowedIpMask) ? $allowedIpMask : array($allowedIpMask) )); $this->sendRequest(); $this->assertRandomMessageInResponse($expectIsAllowed); }
@dataProvider provideSetAllowedIpMasksArgs @param $clientIp @param $allowedIpMask @param $expectIsAllowed
testSetAllowedIpMasks
php
barbushin/php-console
test/Test/Remote/ConnectorTest.php
https://github.com/barbushin/php-console/blob/master/test/Test/Remote/ConnectorTest.php
MIT
public function testFatalErrorsHandling($scriptAlias, array $expectedMessages) { $this->randomOutputMustPresentInResponse = false; $this->request->addScript($scriptAlias); $this->sendRequest(); $this->assertRandomMessageInResponse(true); foreach($expectedMessages as $expectedMessage) { $message = $this->findMessageInResponse(isset($expectedMessage['code']) ? array('code' => $expectedMessage['code']) : array('type' => 'error') ); $this->assertContains($expectedMessage['data'], $message['data']); unset($expectedMessage['data']); $expectedMessage['file'] = $this->clientEmulator->getScriptPath($scriptAlias); $this->assertContainsRecursive($expectedMessage, $message); } }
@dataProvider provideFatalScriptsError @param $scriptAlias @param array $expectedMessages
testFatalErrorsHandling
php
barbushin/php-console
test/Test/Remote/HandlerTest.php
https://github.com/barbushin/php-console/blob/master/test/Test/Remote/HandlerTest.php
MIT
public function findMessageInResponse(array $propertiesValues) { $messages = $this->findMessagesInResponse($propertiesValues); if($messages) { if(count($messages) > 1) { throw new \Exception('There is more than one matched messages'); } return reset($messages); } }
@param array $propertiesValues @return null|\PhpConsole\ErrorMessage|\PhpConsole\DebugMessage|\PhpConsole\EvalResultMessage @throws \Exception
findMessageInResponse
php
barbushin/php-console
test/Test/Remote/Test.php
https://github.com/barbushin/php-console/blob/master/test/Test/Remote/Test.php
MIT
protected function initStorage($validatePathUnderDocRoot = false) { $this->filePath = realpath(\PhpConsole\Test\TMP_DIR) . '/file_storage_test.data'; if(file_exists($this->filePath)) { unlink($this->filePath); } return new File($this->filePath, $validatePathUnderDocRoot); }
@param bool $validatePathUnderDocRoot @return \PhpConsole\Storage
initStorage
php
barbushin/php-console
test/Test/Storage/FileTest.php
https://github.com/barbushin/php-console/blob/master/test/Test/Storage/FileTest.php
MIT