Beispiel #1
0
 public function getConsoleBanner(ConsoleAdapterInterface $console)
 {
     $console->writeLine();
     $console->writeLine(str_pad('', $console->getWidth() - 1, '=', STR_PAD_RIGHT), Color::GREEN);
     $console->write('=', Color::GREEN);
     $console->write(str_pad('' . Module::NAME, $console->getWidth() - 3, ' ', STR_PAD_BOTH));
     $console->writeLine('=', Color::GREEN);
     $console->writeLine(str_pad('', $console->getWidth() - 1, '=', STR_PAD_RIGHT), Color::GREEN);
     $console->writeLine();
     return 'Usage:';
 }
Beispiel #2
0
 public function __invoke(Route $route, Console $console) : int
 {
     $basePath = $route->getMatchedParam('path');
     $path = realpath($basePath) . '/data/blog';
     $cache = realpath($basePath) . '/data/cache/posts';
     $baseUri = new Uri('https://mwop.net');
     $middleware = $this->blogMiddleware;
     $console->writeLine('Generating static cache for blog posts', Color::GREEN);
     // Prepare final handler for middleware
     $failed = false;
     $done = function ($req, $res, $err = null) use(&$failed) {
         $failed = $err ? true : false;
     };
     $parser = new Parser(null, new CommonMarkParser());
     foreach (new MarkdownFileFilter($path) as $fileInfo) {
         $document = $parser->parse(file_get_contents($fileInfo->getPathname()));
         $metadata = $document->getYAML();
         $message = '    ' . $metadata['id'];
         $length = strlen($message);
         $width = $console->getWidth();
         $console->write($message, Color::BLUE);
         $canonical = $baseUri->withPath(sprintf('/blog/%s.html', $metadata['id']));
         $request = (new Request(new PsrRequest([], [], $canonical, 'GET')))->withUri($canonical)->withAttribute('id', $metadata['id']);
         $failed = false;
         $response = $middleware($request, new Response(), $done);
         if (!$failed) {
             $this->cacheResponse($metadata['id'], $cache, $response->getBody());
         }
         $this->reportComplete($console, $width, $length, !$failed);
     }
     $console->writeLine('ALL DONE', Color::GREEN);
     return 0;
 }
 public function getConsoleBanner(Console $console)
 {
     $version = `git describe`;
     $name = 'YAWIK ' . trim($version);
     $width = $console->getWidth();
     return sprintf("==%1\$s==\n%2\$s%3\$s\n**%1\$s**\n", str_repeat('-', $width - 4), str_repeat(' ', floor(($width - strlen($name)) / 2)), $name);
 }
 public function __invoke(Route $route, Console $console) : int
 {
     $basePath = $route->getMatchedParam('path');
     $postsPath = $route->getMatchedParam('postsPath');
     $authorsPath = $route->getMatchedParam('authorsPath');
     $dbPath = $route->getMatchedParam('dbPath');
     $message = 'Generating blog post database';
     $length = strlen($message);
     $width = $console->getWidth();
     $console->write($message, Color::BLUE);
     $pdo = $this->createDatabase($dbPath, $console);
     $path = sprintf('%s/%s', realpath($basePath), ltrim($postsPath));
     $trim = strlen(realpath($basePath)) + 1;
     $parser = new Parser(null, new CommonMarkParser());
     $statements = [];
     foreach (new MarkdownFileFilter($path) as $fileInfo) {
         $path = $fileInfo->getPathname();
         $document = $parser->parse(file_get_contents($path));
         $metadata = $document->getYAML();
         $html = $document->getContent();
         $parts = explode($this->postDelimiter, $html, 2);
         $body = $parts[0];
         $extended = isset($parts[1]) ? $parts[1] : '';
         $author = $this->getAuthor($metadata['author'], $authorsPath);
         $template = empty($statements) ? $this->initial : $this->item;
         $statements[] = sprintf($template, $pdo->quote($metadata['id']), $pdo->quote(substr($path, $trim)), (new DateTime($metadata['created']))->getTimestamp(), (new DateTime($metadata['updated']))->getTimestamp(), $pdo->quote($metadata['title']), $pdo->quote($author['id']), $metadata['draft'] ? 1 : 0, $metadata['public'] ? 1 : 0, $pdo->quote($body), $pdo->quote(sprintf('|%s|', implode('|', $metadata['tags']))));
     }
     $pdo->exec(implode("\n", $statements));
     return $this->reportSuccess($console, $width, $length);
 }
Beispiel #5
0
 /**
  * Get configuration by key
  */
 public function getAction()
 {
     // check for help mode
     if ($this->requestOptions->getFlagHelp()) {
         return $this->getHelp();
     }
     // output header
     $this->consoleHeader('Fetching requested configuration');
     // get needed options to shorten code
     $path = realpath($this->requestOptions->getPath());
     $configName = $this->requestOptions->getConfigName();
     $flagLocal = $this->requestOptions->getFlagLocal();
     // check for config name
     if (!$configName) {
         return $this->sendError('config get <configName> was not provided');
     }
     // check for local file
     if ($flagLocal) {
         $configFile = $path . '/config/autoload/local.php';
         // check if local config file exists
         if (!file_exists($configFile)) {
             return $this->sendError('Local config file ' . $configFile . ' does not exist.');
         }
     } else {
         $configFile = $path . '/config/application.config.php';
     }
     // fetch config data
     $configData = (include $configFile);
     // check if local config file exists
     if (empty($configData)) {
         return $this->sendError('Config file ' . $configFile . ' is empty.');
     }
     // start output
     $this->console->write('       => Reading configuration file ');
     $this->console->writeLine($configFile, Color::GREEN);
     $this->console->writeLine();
     // find value in array
     $configValue = ModuleConfig::findValueInArray($configName, $configData);
     // start output
     $this->console->write(' Done ', Color::NORMAL, Color::CYAN);
     $this->console->write(' ');
     $this->console->write('Configuration data for key ');
     $this->console->writeLine($configName, Color::GREEN);
     $this->console->writeLine();
     // check config value
     if (is_array($configValue)) {
         $iniWriter = new IniWriter();
         $this->console->writeLine(str_pad('', $this->console->getWidth() - 1, '=', STR_PAD_RIGHT));
         $this->console->writeLine(trim($iniWriter->toString($configValue)));
         $this->console->writeLine(str_pad('', $this->console->getWidth() - 1, '=', STR_PAD_RIGHT));
     } elseif (is_null($configValue)) {
         $this->console->writeLine('       => NULL');
     } else {
         $this->console->writeLine('       => ' . $configValue);
     }
     // output footer
     $this->consoleFooter('requested configuration was successfully displayed');
 }
Beispiel #6
0
 public function listAction()
 {
     $module = $this->request->getParam('module');
     if ($module) {
         $this->console->writeLine('Only for module "' . $module . '":');
     }
     $includeModules = $this->request->getParam('includemodules');
     //Display mini-help
     $this->console->writeLine(str_pad('', $this->console->getWidth(), '-'));
     $this->console->writeLine('L - Already loaded', Color::GREEN);
     $this->console->writeLine('R - Ready for load', Color::YELLOW);
     $this->console->writeLine('LN - Loaded, not exists', Color::RED);
     $this->console->writeLine('C - Conflict, not loaded', null, Color::RED);
     $this->console->writeLine(str_pad('', $this->console->getWidth(), '-'));
     //Display legend
     $this->console->writeLine("|state\t|migration\t\t|module", Color::GRAY);
     try {
         $manager = $this->getManager();
         $migrations = $this->manager->listMigrations($module, $includeModules);
         foreach ($migrations as $migration) {
             $color = null;
             $bgColor = null;
             $prefix = '';
             switch ($migration['type']) {
                 case $manager::MIGRATION_TYPE_CONFLICT:
                     $bgColor = Color::RED;
                     $prefix = '[C]';
                     break;
                 case $manager::MIGRATION_TYPE_READY:
                     $color = Color::YELLOW;
                     $prefix = '[R]';
                     break;
                 case $manager::MIGRATION_TYPE_NOT_EXIST:
                     $color = Color::RED;
                     $prefix = '[LN]';
                     break;
                 case $manager::MIGRATION_TYPE_LOADED:
                     $color = Color::GREEN;
                     $prefix = '[L]';
                     break;
             }
             //Display all migrations
             $this->console->writeLine("{$prefix}\t{$migration['name']}\t{$migration['module']}", $color, $bgColor);
         }
         $this->console->writeLine(str_pad('', $this->console->getWidth(), '-'));
     } catch (ZFCToolException $e) {
         $this->console->writeLine($e->getMessage(), Color::RED);
     } catch (\Exception $e) {
         $this->console->writeLine($e->getMessage(), Color::RED);
     }
 }
Beispiel #7
0
 public function __invoke(Route $route, Console $console) : int
 {
     $message = 'Creating tag cloud';
     $length = strlen($message);
     $width = $console->getWidth();
     $console->write($message, Color::BLUE);
     if (!$route->matchedParam('output')) {
         return $this->reportError($console, $width, $length, 'Missing output file');
     }
     $output = $route->getMatchedParam('output');
     $cloud = $this->mapper->fetchTagCloud();
     $markup = sprintf("<h4>Tag Cloud</h4>\n<div class=\"cloud\">%s</div>", $cloud->render());
     file_put_contents($output, $markup);
     return $this->reportSuccess($console, $width, $length);
 }
Beispiel #8
0
 public function eloAction()
 {
     $request = $this->getRequest();
     // Make sure that we are running in a console and the user has not tricked our
     // application into running this action from a public web server.
     if (!$request instanceof ConsoleRequest) {
         throw new \RuntimeException('You can only use this action from a console!');
     }
     $matches = $this->matchRepository->getAllOrderedByDate();
     $this->pointLogRepository->reset();
     $this->playerRepository->resetRankings();
     foreach ($matches as $match) {
         foreach ($match->getPlayer() as $player) {
             $this->addPlayerToRanking($player);
         }
         $ranking = new Elo();
         $log = $ranking->calculateMatch($match);
         foreach ($match->getPlayer() as $player) {
             $this->playerRepository->persist($player, false);
         }
         if ($match instanceof SingleMatch) {
             $participant1 = $match->getPlayer1();
             $participant2 = $match->getPlayer2();
         } else {
             if ($match instanceof DoubleMatch) {
                 $participant1 = $match->getTeamOne();
                 $participant2 = $match->getTeamTwo();
             }
         }
         $this->pointLogRepository->persist($log, false);
         $this->console->writeLine(sprintf('%s vs. %s - Chances %s%%/%s%%. Points %d (%+d) / %d (%+d)', $participant1->getName(), $participant2->getName(), $log->getChance1(), $log->getChance2(), $log->getNewPoints1(), $log->getDifference1(), $log->getNewPoints2(), $log->getDifference2()));
     }
     $this->pointLogRepository->flush();
     $this->console->writeLine(str_repeat("-", $this->console->getWidth() / 2));
     usort($this->ranking, array($this, 'compareRanking'));
     $this->console->writeLine("Rankings:");
     $i = 1;
     foreach ($this->ranking as $player) {
         $this->console->writeLine(sprintf("%d: %d - %s (%d matches)", $i++, $player->getPoints(), $player->getName(), $player->getMatchCount()));
     }
 }
Beispiel #9
0
 /**
  * route : get contributors.
  */
 public function getcontributorsAction()
 {
     $width = $this->console->getWidth();
     $this->console->writeLine('Fetching GitHub Contributors', Color::GREEN);
     $response = $this->httpClient->send();
     if (!$response->isSuccess()) {
         // report failure
         $message = $response->getStatusCode() . ': ' . $response->getReasonPhrase();
         $this->reportError($width, 0, $message);
         return;
     }
     $body = $response->getBody();
     $contributors = json_decode($body, true);
     $total = count($contributors);
     $contributors = $this->collectContributorsInfo($contributors, $total, $width);
     $this->console->writeLine(str_repeat('-', $width));
     $message = 'Writing file';
     $this->console->write($message, Color::BLUE);
     $path = $this->config['console']['contributors']['output'];
     file_put_contents($path, serialize($contributors));
     $this->reportSuccess($width, strlen($message));
     $this->console->writeLine(sprintf('File written to %s', $path));
 }
Beispiel #10
0
 /**
  * @param \Zend\Console\Adapter\AdapterInterface $console
  */
 public function setConsole($console)
 {
     $this->console = $console;
     // Update width
     $this->width = $console->getWidth();
 }
 /**
  * Build Console usage information by querying currently loaded modules.
  *
  * @param ConsoleAdapter         $console
  * @param string                 $scriptName
  * @param ModuleManagerInterface $moduleManager
  * @return string
  * @throws RuntimeException
  */
 protected function getConsoleUsage(ConsoleAdapter $console, $scriptName, ModuleManagerInterface $moduleManager = null)
 {
     /*
      * Loop through all loaded modules and collect usage info
      */
     $usageInfo = array();
     if ($moduleManager !== null) {
         foreach ($moduleManager->getLoadedModules(false) as $name => $module) {
             // Strict-type on ConsoleUsageProviderInterface, or duck-type
             // on the method it defines
             if (!$module instanceof ConsoleUsageProviderInterface && !method_exists($module, 'getConsoleUsage')) {
                 continue;
                 // this module does not provide usage info
             }
             // We prepend the usage by the module name (printed in red), so that each module is
             // clearly visible by the user
             $moduleName = sprintf("%s\n%s\n%s\n", str_repeat('-', $console->getWidth()), $name, str_repeat('-', $console->getWidth()));
             $moduleName = $console->colorize($moduleName, ColorInterface::RED);
             $usage = $module->getConsoleUsage($console);
             // Normalize what we got from the module or discard
             if (is_array($usage) && !empty($usage)) {
                 array_unshift($usage, $moduleName);
                 $usageInfo[$name] = $usage;
             } elseif (is_string($usage) && $usage != '') {
                 $usageInfo[$name] = array($moduleName, $usage);
             }
         }
     }
     /*
      * Handle an application with no usage information
      */
     if (!count($usageInfo)) {
         // TODO: implement fetching available console routes from router
         return '';
     }
     /*
      * Transform arrays in usage info into columns, otherwise join everything together
      */
     $result = '';
     $table = false;
     $tableCols = 0;
     $tableType = 0;
     foreach ($usageInfo as $moduleName => $usage) {
         if (!is_string($usage) && !is_array($usage)) {
             throw new RuntimeException(sprintf('Cannot understand usage info for module "%s"', $moduleName));
         }
         if (is_string($usage)) {
             // It's a plain string - output as is
             $result .= $usage . "\n";
             continue;
         }
         // It's an array, analyze it
         foreach ($usage as $a => $b) {
             /*
              * 'invocation method' => 'explanation'
              */
             if (is_string($a) && is_string($b)) {
                 if (($tableCols !== 2 || $tableType != 1) && $table !== false) {
                     // render last table
                     $result .= $this->renderTable($table, $tableCols, $console->getWidth());
                     $table = false;
                     // add extra newline for clarity
                     $result .= "\n";
                 }
                 // Colorize the command
                 $a = $console->colorize($scriptName . ' ' . $a, ColorInterface::GREEN);
                 $tableCols = 2;
                 $tableType = 1;
                 $table[] = array($a, $b);
                 continue;
             }
             /*
              * array('--param', '--explanation')
              */
             if (is_array($b)) {
                 if ((count($b) != $tableCols || $tableType != 2) && $table !== false) {
                     // render last table
                     $result .= $this->renderTable($table, $tableCols, $console->getWidth());
                     $table = false;
                     // add extra newline for clarity
                     $result .= "\n";
                 }
                 $tableCols = count($b);
                 $tableType = 2;
                 $table[] = $b;
                 continue;
             }
             /*
              * 'A single line of text'
              */
             if ($table !== false) {
                 // render last table
                 $result .= $this->renderTable($table, $tableCols, $console->getWidth());
                 $table = false;
                 // add extra newline for clarity
                 $result .= "\n";
             }
             $tableType = 0;
             $result .= $b . "\n";
         }
     }
     // Finish last table
     if ($table !== false) {
         $result .= $this->renderTable($table, $tableCols, $console->getWidth());
     }
     return $result;
 }
Beispiel #12
0
 /**
  * @param AdapterInterface $console
  */
 function __construct(AdapterInterface $console)
 {
     // setup dependencies
     $this->console = $console;
     $this->width = $console->getWidth();
 }
Beispiel #13
0
 /**
  * Determine and return current console width.
  *
  * @return int
  */
 public function getWidth()
 {
     return $this->adapter->getWidth();
 }
Beispiel #14
0
 /**
  * Write application footer
  *
  * @param AdapterInterface $console
  */
 public function writeApplicationFooter(AdapterInterface $console)
 {
     $console->writeLine(str_pad('', $console->getWidth() - 1, '=', STR_PAD_RIGHT), Color::GREEN);
     $console->writeLine();
 }
Beispiel #15
0
 private function reportComplete(Console $console, int $length)
 {
     $width = $console->getWidth();
     if ($length + 8 > $width) {
         $console->writeLine('');
         $length = 0;
     }
     $spaces = $width - $length - 8;
     $spaces = $spaces > 0 ? $spaces : 0;
     $console->writeLine(str_repeat('.', $spaces) . '[ DONE ]', Color::GREEN);
 }
 /**
  * {@inheritdoc}
  */
 public function getConsoleBanner(AdapterInterface $console)
 {
     if (static::$consoleBannerEnabled) {
         $figlet = new Figlet(['font' => __DIR__ . '/assets/font/colossal.flf']);
         $figlet->setOutputWidth($console->getWidth());
         $figlet->setJustification(Figlet::JUSTIFICATION_CENTER);
         return PHP_EOL . $figlet->render('Sphinx Search Tool');
     } else {
         return '';
     }
 }