Example: Writing to standard output
uses('util.cmd.Console');
Console::writeLine('Hello ', 'a', 'b', 1); // Hello ab1
Console::writeLinef('Hello %s', 'World'); // Hello World
Console::$out->write('.');
Example: Writing to standard error
uses('util.cmd.Console');
Console::$err->writeLine('*** An error occured: ', $e->toString());
public function processGames() { if ($this->site->lookupgames == 1) { $console = new Console($this->echooutput); $console->processConsoleReleases(); } }
/** * Bootstrap a server from command line options * * @param \Aerys\Logger $logger * @param \Aerys\Console $console * @return \Aerys\Server */ public function boot(Logger $logger, Console $console) : Server { $configFile = $this->selectConfigFile((string) $console->getArg("config")); $logger->info("Using config file found at {$configFile}"); if (!(include $configFile)) { throw new \DomainException("Config file inclusion failure: {$configFile}"); } elseif (!defined("AERYS_OPTIONS")) { $options = []; } elseif (is_array(AERYS_OPTIONS)) { $options = AERYS_OPTIONS; } else { throw new \DomainException("Invalid AERYS_OPTIONS constant: array expected, got " . gettype(AERYS_OPTIONS)); } if ($console->isArgDefined("debug")) { $options["debug"] = true; } $options = $this->generateOptionsObjFromArray($options); $vhosts = new VhostContainer(); $ticker = new Ticker($logger); $server = new Server($options, $vhosts, $logger, $ticker); $bootLoader = function (Bootable $bootable) use($server, $logger) { return $bootable->boot($server, $logger); }; $hosts = \call_user_func($this->hostAggregator) ?: [new Host()]; foreach ($hosts as $host) { $vhost = $this->buildVhost($host, $bootLoader); $vhosts->use($vhost); } return $server; }
protected function doStart(Console $console) : \Generator { if ($console->isArgDefined("restart")) { $this->logger->critical("You cannot restart a debug aerys instance via command"); exit(1); } $server = (yield from $this->bootstrapper->boot($this->logger, $console)); (yield $server->start()); $this->server = $server; }
public function __construct(Console $console, $ipcSock) { if ($console->isArgDefined("color")) { $this->setAnsify($console->getArg("color")); } $level = $console->getArg("log"); $level = isset(self::LEVELS[$level]) ? self::LEVELS[$level] : $level; $this->setOutputLevel($level); $onWritable = $this->makePrivateCallable("onWritable"); $this->ipcSock = $ipcSock; $this->writeWatcherId = \Amp\onWritable($ipcSock, $onWritable, ["enable" => false]); }
public function __construct(Console $console) { $this->console = $console; if ($console->isArgDefined("color")) { $value = $console->getArg("color"); $this->setAnsiColorOption($value); } if ($console->isArgDefined("log")) { $level = $console->getArg("log"); $level = isset(self::LEVELS[$level]) ? self::LEVELS[$level] : $level; $this->setOutputLevel($level); } }
public function run(Console $console, Db $db) { $this->db = $db; if (!$console->hasParams()) { $this->showHelp(); } else { foreach ($console->getParams() as $command => $value) { if (method_exists($this, $command)) { $this->{$command}($value); } } } }
public function Display(Console $con, $resIps, $errorsOnly) { foreach ($this->GetChangedLines() as $line) { $con->WritePart('[' . $con->Colorize('ERROR', Console::C_RED) . '] '); $con->WritePart($con->Colorize($resIps ? substr(str_pad($this->ResolveIP($line->ip), 48), 0, 48) : str_pad($line->ip, 16), Console::C_YELLOW) . ' '); $con->WritePart($con->Colorize(str_pad($line->domain, 32), Console::C_BROWN) . ' '); $long_mesg = $con->Colorize($line->message, Console::C_RED); $con->WriteLine($long_mesg); } }
protected function doStart(Console $console) : \Generator { if ($console->isArgDefined("restart")) { $this->logger->critical("You cannot restart a debug aerys instance via command"); exit(1); } if (ini_get("zend.assertions") === "-1") { $this->logger->warning("Running aerys in debug mode with assertions disabled is not recommended; " . "enable assertions in php.ini (zend.assertions = 1) " . "or disable debug mode (-d) to hide this warning."); } else { ini_set("zend.assertions", 1); } $server = (yield from $this->bootstrapper->boot($this->logger, $console)); (yield $server->start()); $this->server = $server; }
public function __construct($workingDir = '.', $info, $commandsSeq = array()) { parent::__construct($workingDir, $info, $commandsSeq); Console::initCore(); $this->root_dir = Config::get('ROOT_DIR'); $this->models_dir = Config::get('models_dir'); }
function call($arguments = null) { Console::debugEx(LOG_DEBUG1, __CLASS__, "Delegate invocation"); foreach ($this->callable as $classes) { @call_user_func_array($classes, (array) $arguments); } }
/** * Comando de consola para crear un modelo * * @param array $params parametros nombrados de la consola * @param string $model modelo * @throw KumbiaException */ public function create($params, $model) { // nombre de archivo $file = APP_PATH . 'models'; // obtiene el path $path = explode('/', trim($model, '/')); // obtiene el nombre de modelo $model_name = array_pop($path); if (count($path)) { $dir = implode('/', $path); $file .= "/{$dir}"; if (!is_dir($file) && !FileUtil::mkdir($file)) { throw new KumbiaException("No se ha logrado crear el directorio \"{$file}\""); } } $file .= "/{$model_name}.php"; // si no existe o se sobreescribe if (!is_file($file) || Console::input("El modelo existe, �desea sobrescribirlo? (s/n): ", array('s', 'n')) == 's') { // nombre de clase $class = Util::camelcase($model_name); // codigo de modelo ob_start(); include CORE_PATH . 'console/generators/model.php'; $code = '<?php' . PHP_EOL . ob_get_clean(); // genera el archivo if (file_put_contents($file, $code)) { echo "-> Creado modelo {$model_name} en: {$file}" . PHP_EOL; } else { throw new KumbiaException("No se ha logrado crear el archivo \"{$file}\""); } } }
private function renderRecursive($nod) { $ret = ''; for ($n = 0; $n < $nod->childNodes->length; $n++) { $cn = $nod->childNodes->item($n); if ($cn->namespaceURI == self::NS_LITEMARKUP) { $t = explode(':', $cn->nodeName); switch ($t[1]) { case 'debug': $ret .= "THIS IS THE DEBUGGING INFO"; break; default: Console::warn("Unknown LiteMarkup tag: %s", $cn->nodeName); } } else { switch ($cn->nodeName) { case '#text': $ret .= $cn->nodeValue; break; default: $ret .= '<' . $cn->nodeName . '>' . $this->renderRecursive($cn) . '</' . $cn->nodeName . '>'; break; } } } return $ret; }
/** * Returns stdin file pointer * * @return resource STDIN file pointer */ private static function GetStdin() { if (!self::$stdin) { self::$stdin = fopen('php://stdin', 'r'); } return self::$stdin; }
/** * * @return Console */ public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; }
function exception(Exception $e) { logger::emerg("Unhandled exception: (%s) %s in %s:%d", get_class($e), $e->getMessage(), str_replace(BASE_PATH, '', $e->getFile()), $e->getLine()); Console::debugEx(0, get_class($e), "Unhandled exception: (%s) %s in %s:%d", get_class($e), $e->getMessage(), str_replace(BASE_PATH, '', $e->getFile()), $e->getLine()); $f = file($e->getFile()); foreach ($f as $i => $line) { $mark = $i + 1 == $e->getLine() ? '=> ' : ' '; $f[$i] = sprintf(' %05d. %s', $i + 1, $mark) . $f[$i]; $f[$i] = str_replace("\n", "", $f[$i]); } $first = $e->getLine() - 4; if ($first < 0) { $first = 0; } $last = $e->getLine() + 3; if ($last >= count($f)) { $last = count($f) - 1; } $source = join("\n", array_slice($f, $first, $last - $first)); Console::debugEx(0, get_class($e), Console::backtrace(0, $e->getTrace(), true)); Console::debugEx(LOG_LOG, "Exception", "Source dump of %s:\n%s", str_replace(BASE_PATH, '', $e->getFile()), $source); $rv = 1; logger::emerg("Exiting with return code %d after exception.", $rv); Console::debugEx(LOG_BASIC, __CLASS__, "Exiting with return code %d after exception.", $rv); }
function process() { Console::initCore(); if ($r = ArgsHolder::get()->getOption('count')) { $this->count = $r; } if (($c = ArgsHolder::get()->shiftCommand()) == 'help') { return $this->cmdHelp(); } try { IO::out(""); $sql = 'SELECT * FROM ' . self::TABLE . ' where not isnull(finished_at) and not isnull(locked_at) and isnull(failed_at) ORDER BY run_at DESC'; if ($this->count) { $list = DB::query($sql . ' LIMIT ' . $this->count); } else { $list = DB::query($sql); } if (!count($list)) { IO::out("No finished work!", IO::MESSAGE_FAIL); return; } io::out(sprintf("%-10s %-7s %-3s %-20s %-20s %-19s %-4s %-5s", "~CYAN~id", "queue", "pr", "run_at", "locked_at", "finished_at", "att", "call_to~~~")); foreach ($list as $l) { $handler = unserialize($l["handler"]); io::out(sprintf("%-4s %-7s %-3s %-20s %-20s %-20s %-3s %-5s", $l["id"], $l["queue"], $l["priority"], $l["run_at"], $l["locked_at"], $l["finished_at"], $l["attempts"], $handler["class"] . "::" . $handler["method"] . "(...)")); } } catch (Exception $e) { io::out($e->getMessage(), IO::MESSAGE_FAIL); return; } IO::out(""); }
/** * Start server * * @param string[] args */ public static function main(array $args) { $stor = new TestingStorage(); $stor->add(new TestingCollection('/', $stor)); $stor->add(new TestingCollection('/.trash', $stor)); $stor->add(new TestingElement('/.trash/do-not-remove.txt', $stor)); $stor->add(new TestingCollection('/htdocs', $stor)); $stor->add(new TestingElement('/htdocs/file with whitespaces.html', $stor)); $stor->add(new TestingElement('/htdocs/index.html', $stor, "<html/>\n")); $stor->add(new TestingCollection('/outer', $stor)); $stor->add(new TestingCollection('/outer/inner', $stor)); $stor->add(new TestingElement('/outer/inner/index.html', $stor)); $auth = newinstance('lang.Object', array(), '{ public function authenticate($user, $password) { return ("testtest" == $user.$password); } }'); $protocol = newinstance('peer.ftp.server.FtpProtocol', array($stor, $auth), '{ public function onShutdown($socket, $params) { $this->answer($socket, 200, "Shutting down"); $this->server->terminate= TRUE; } }'); isset($args[0]) && $protocol->setTrace(Logger::getInstance()->getCategory()->withAppender(new FileAppender($args[0]))); $s = new Server('127.0.0.1', 0); try { $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
public function actionIndex($isForced = false, $isDebug = false) { $console = Console::getInstance($isForced, $isDebug); $console->debugStart('Entered'); // if (mail('*****@*****.**', 'test', 'test message')) { // $console->writeLine('OK'); // } else { // $console->writeLine('Failure'); // } $newExecutors = Site::getNewExecutors('2015-11-19 12:20:00'); $report = ''; foreach ($newExecutors as $e) { $sites = Site::model()->findAllByAttributes(array('executor_id' => $e)); if (count($sites) < 1) { continue; } $report .= String::build('Positions for "{keyword}" ({date_from} - {date_to})', array('keyword' => $sites[0]->keyword->name, 'date_from' => Time::toPretty($sites[0]->updated_at), 'date_to' => Time::toPretty($sites[count($sites) - 1]->updated_at))) . PHP_EOL; foreach ($sites as $s) { $report .= String::build('{position}: {site}', array('position' => $s->position, 'site' => String::rebuildUrl($s->link, false, false, true, false))) . PHP_EOL; } } $console->writeLine($report); $console->debugEnd(); return; }
function gravalog($numero, $texto, $pagina = null, $linha = null, $contexto = null) { $ddf = fopen(DIR_LOGS . "/" . date('Y.M.d') . ".log", 'a'); if ($ddf) { $datalog = date('d.m.Y H:i:s'); $txt = "::[" . $datalog . "]--|" . ip() . "|----------------------\n"; $txt .= "(" . $numero . ") " . $texto . "\n"; if (!is_null($pagina)) { $txt .= "Pagina: " . $pagina . "\n"; } if (!is_null($linha)) { $txt .= "Linha: " . $linha . "\n"; } $txt .= "\n"; if (PROFILER) { if (class_exists("Console")) { $e = new ErrorException($texto, 0, $numero, $pagina, $linha); Console::logError($e, $texto); } } if (fwrite($ddf, $txt)) { return true; if (DEBUG) { alert('Arquivo gravado com sucesso', false); } } } else { if (DEBUG) { alert('Erro ao gravar arquivo', false); } } fclose($ddf); }
public static function input($prompt, $color = null) { Console::write($prompt, $color); $finput = fopen("php://stdin", "r"); $input = fgets($finput); return str_replace("\n", "", $input); }
function logger($level, $msg, $method = null) { static $labels = array(100 => 'DEBUG', 200 => 'INFO', 250 => 'NOTICE', 300 => 'WARNING', 400 => 'ERROR', 500 => 'CRITICAL', 550 => 'ALERT', 600 => 'EMERGENCY', 700 => 'ALL'); // make sure $level has the correct value if (is_int($level) and !isset($labels[$level]) or is_string($level) and !array_search(strtoupper($level), $labels)) { throw new \FuelException('Invalid level "' . $level . '" passed to logger()'); } if (is_string($level)) { $level = array_search(strtoupper($level), $labels); } // get the levels defined to be logged $loglabels = \Config::get('log_threshold'); // bail out if we don't need logging at all if ($loglabels == \Fuel::L_NONE) { return false; } // if profiling is active log the message to the profile if (\Config::get('profiling')) { \Console::log($method . ' - ' . $msg); } // if it's not an array, assume it's an "up to" level if (!is_array($loglabels)) { $a = array(); foreach ($labels as $l => $label) { $l >= $loglabels and $a[] = $l; } $loglabels = $a; } // do we need to log the message with this level? if (!in_array($level, $loglabels)) { return false; } return \Log::instance()->log($level, (empty($method) ? '' : $method . ' - ') . $msg); }
public function __construct() { parent::__construct(); $this->setName('Logger'); $this->addTest(Logger::suite()); $this->addTest(Console::suite()); }
function process() { Console::initCore(); if (($c = ArgsHolder::get()->shiftCommand()) == 'help') { return $this->cmdHelp(); } try { $format = "%-25s %s"; IO::out(""); $s = DB::query('SELECT * FROM ' . self::TABLE . ' where id="' . $c . '"'); if (!count($s)) { io::out("Work with id={$c} is not exists", IO::MESSAGE_FAIL); return; } io::out(sprintf($format, "~CYAN~id~~~", $c)); io::out(sprintf($format, "~CYAN~queue~~~", $this->emp($s[0]['queue']))); io::out(sprintf($format, "~CYAN~priority~~~", $this->emp($s[0]['priority']))); io::out(sprintf($format, "~CYAN~run at~~~", $this->emp($s[0]['run_at']))); io::out(sprintf($format, "~CYAN~locked at~~~", $this->emp($s[0]['locked_at']))); io::out(sprintf($format, "~CYAN~finished at~~~", $this->emp($s[0]['finished_at']))); io::out(sprintf($format, "~CYAN~failed at~~~", $this->emp($s[0]['failed_at']))); io::out(sprintf($format, "~CYAN~attemts~~~", $this->emp($s[0]['attempts']))); $handler = unserialize($s[0]["handler"]); io::out(sprintf($format, "~CYAN~call~~~", $handler["class"] . "::" . $handler["method"]) . "(...)"); if (isset($handler["param"])) { io::out(sprintf($format, "~CYAN~params~~~", trim(self::walker($handler['param']), ','))); } } catch (Exception $e) { io::out($e->getMessage(), IO::MESSAGE_FAIL); return; } IO::out(""); }
/** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { $arg = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0); Console::log($arg); $this->output->enable_profiler(true); $this->load->view('welcome_message'); }
public static function getInstance($isForced = false, $isDebug = false) { if (!self::$console) { self::$console = new Console($isForced, $isDebug); } return self::$console; }
/** * Displays a variable. * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as Yii controllers. * @param mixed $var variable to be dumped * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10. * @param boolean $highlight whether the result should be syntax-highlighted */ public static function dump($var, $depth = 10, $highlight = true) { if (Console::isCli()) { $highlight = false; } echo static::dumpAsString($var, $depth, $highlight); }
public function __construct($args) { $this->args = $args; Console::$have_readline = function_exists("readline"); for ($x = 1; $x < count($args); $x++) { switch ($args[$x]) { case "-h": case "--help": $this->usage(); break; default: if (substr($args[$x], 0, 1) == "-") { $this->usage(); } elseif (defined("HALFMOON_ENV")) { $this->usage(); } else { define("HALFMOON_ENV", $args[$x]); } } } require_once __DIR__ . "/../halfmoon.php"; error_reporting(E_ALL | E_STRICT); ini_set("error_log", NULL); ini_set("log_errors", 1); ini_set("html_errors", 0); ini_set("display_errors", 0); while (ob_get_level()) { ob_end_clean(); } ob_implicit_flush(true); /* TODO: forcibly load models so they're in the tab-completion cache */ print "Loaded " . HALFMOON_ENV . " environment (halfmoon)\n"; $this->loop(); }
/** * @return array */ protected function getConsoleMessages() { $messages = array(); foreach ($this->console->getLogs() as $log) { switch ($log['type']) { case 'log': $message = array('message' => print_r($log['data'], true), 'type' => 'log'); break; case 'memory': $message = array('message' => (!empty($log['data_type']) ? "{$log['data_type']}: " : '') . $log['name'], 'data' => $this->getReadableMemory($log['data']), 'type' => 'memory'); break; case 'error': $message = array('message' => "Line {$log['line']}: {$log['data']} in {$this->getFilePath($log['file'])}", 'type' => 'error'); break; case 'speed': $elapsedTime = $log['data'] - $this->startTime; $message = array('message' => $log['name'], 'data' => $this->getReadableTime($elapsedTime), 'type' => 'speed'); break; default: $message = array('message' => "Unrecognized console log type: {$log['type']}", 'type' => 'error'); break; } array_push($messages, $message); } return $messages; }
public function getPosition($from = 1, $count = 1) { $console = Console::getInstance(); $console->operationStart('Collecting search results'); $this->pageNumber = ceil($from / $this->positionsPerPage); if ($count < 1 || $count > 10) { $console->operationEnd(); $console - error('Count must be in 1-10. ' . $count . ' is setted'); return false; } $sites = array(); $position = 1; do { $console->operationStep(); $pageResults = $this->getPageResults(); foreach ($pageResults as $pr) { $sitesCount = count($sites); $domain = ($domain = String::rebuildUrl($pr->url, false, false, true, false)) ? $domain : $pr->url; if (IgnoreList::isInList($domain) || $sitesCount && $sites[$sitesCount - 1]->domain == $domain) { continue; } $site = new Site(); $site->name = strip_tags($pr->title); $site->position = $position++; $site->link = $pr->url; $site->domain = $domain; $sites[] = $site; } $this->pageNumber++; } while ($sitesCount < $count); //$this->pageNumber++ * $this->positionsPerPage < $count // old $console->operationEnd(); return array_slice($sites, 0, $count); }
/** * Preps the application for running, then runs it. If this function is called more than once, an E_USER_ERROR is triggered. * * @param string $root_dir The path to the root of the installation. * @return void */ function StartCurator() { static $did_start = false; // set up the exit status. $exit_status = 0; // make sure this is only run once. if ($did_start === false) { $autoload = Autoload::singleton(); // configure the autoloader. try { $autoload->setBaseDir(CURATOR_APP_DIR); $autoload->register(); } catch (\Exception $e) { Console::stderr('** Could not register the autoloader:'); Console::stderr(' ' . $e->getMessage()); die; } // once the autoloader is in place, we are started up. $did_start = true; try { $app = new Application(); $exit_status = $app->run(); } catch (\Exception $e) { Console::stderr('** Could not run the application:'); Console::stderr(' ' . $e->getMessage()); die; } } else { // if we are called again, bail. trigger_error('StartCurator called after already being called.', E_USER_ERROR); } // send the status back. return $exit_status; }