public function testFormattedEscapedOutput() { $output = new StreamOutput($this->stream, StreamOutput::VERBOSITY_NORMAL, true, null); $output->writeln('<info>' . OutputFormatter::escape('<error>some error</error>') . '</info>'); rewind($output->getStream()); $this->assertSame("[32m<error>some error</error>[39m" . PHP_EOL, stream_get_contents($output->getStream())); }
public function testDoWrite() { $output = new StreamOutput($this->stream); $output->writeln('foo'); rewind($output->getStream()); $this->assertEquals('foo' . PHP_EOL, stream_get_contents($output->getStream()), '->doWrite() writes to the stream'); }
/** * Creates the given process * * @throws \Exception */ private function startProcess(OutputInterface $output) { $arguments = $this->resolveProcessArgs(); $name = sha1(serialize($arguments)); if ($this->background->hasProcess($name)) { throw new \RuntimeException("Service is already running."); } $builder = new ProcessBuilder($arguments); if ($this->hasParameter('cwd')) { $builder->setWorkingDirectory($this->getParameter('cwd')); } $process = $builder->getProcess(); if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) { $output->writeln($process->getCommandLine()); } if ($this->hasParameter('output')) { $append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w'; $stream = fopen($this->getParameter('output'), $append); $output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true); } $process->start(function ($type, $buffer) use($output) { $output->write($buffer); }); $this->background->addProcess($name, $process); if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) { throw new TaskRuntimeException($this->getName(), $process->getErrorOutput()); } }
protected function execute(InputInterface $input, OutputInterface $output) { if (NULL !== ($file = $input->getOption('file'))) { if (is_file($file) && !$input->getOption('overwrite')) { $output->writeln(sprintf('File <info>%s</info> already exists, use option <comment>-o</comment> to overwrite it.', $file)); return; } $backup = $output; $fp = fopen($file, 'wb'); $output = new StreamOutput($fp); } $request = new HttpRequest(new Uri('http://test.me/')); $this->requestScope->enter($request); try { $output->writeln('routes:'); $routes = $this->router->getRoutes($this->context)->getSortedRoutes(); foreach (array_reverse($routes) as $name => $route) { $output->writeln(sprintf(' %s:', $name)); foreach (explode("\n", trim(Yaml::dump($route->toArray($this->context), 100))) as $line) { $output->writeln(sprintf(' %s', $line)); } } } finally { $this->requestScope->leave($request); } if (isset($fp) && is_resource($fp)) { @fclose($fp); $backup->writeln(sprintf('Config dumped to <info>%s</info>', $file)); } }
/** * Executes the application. * * Available options: * * * interactive: Sets the input interactive flag * * decorated: Sets the output decorated flag * * verbosity: Sets the output verbosity flag * * capture_stderr_separately: Make output of stdOut and stdErr separately available * * @param array $input An array of arguments and options * @param array $options An array of options * * @return int The command exit code */ public function run(array $input, $options = array()) { $this->input = new ArrayInput($input); if (isset($options['interactive'])) { $this->input->setInteractive($options['interactive']); } $this->captureStreamsIndependently = array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately']; if (!$this->captureStreamsIndependently) { $this->output = new StreamOutput(fopen('php://memory', 'w', false)); if (isset($options['decorated'])) { $this->output->setDecorated($options['decorated']); } if (isset($options['verbosity'])) { $this->output->setVerbosity($options['verbosity']); } } else { $this->output = new ConsoleOutput(isset($options['verbosity']) ? $options['verbosity'] : ConsoleOutput::VERBOSITY_NORMAL, isset($options['decorated']) ? $options['decorated'] : null); $errorOutput = new StreamOutput(fopen('php://memory', 'w', false)); $errorOutput->setFormatter($this->output->getFormatter()); $errorOutput->setVerbosity($this->output->getVerbosity()); $errorOutput->setDecorated($this->output->isDecorated()); $reflectedOutput = new \ReflectionObject($this->output); $strErrProperty = $reflectedOutput->getProperty('stderr'); $strErrProperty->setAccessible(true); $strErrProperty->setValue($this->output, $errorOutput); $reflectedParent = $reflectedOutput->getParentClass(); $streamProperty = $reflectedParent->getProperty('stream'); $streamProperty->setAccessible(true); $streamProperty->setValue($this->output, fopen('php://memory', 'w', false)); } return $this->statusCode = $this->application->run($this->input, $this->output); }
/** * @param boolean * * @return string */ public function getDisplay($normalize = false) { rewind($this->output->getStream()); $display = stream_get_contents($this->output->getStream()); if ($normalize) { $display = str_replace(PHP_EOL, "\n", $display); } return $display; }
/** * Returns the contents of the output stream. * * @param StreamOutput $output The output manager. * * @return string The contents of the stream. */ public function readOutput(StreamOutput $output) { $contents = ''; $stream = $output->getStream(); rewind($stream); do { $contents .= fgets($stream); } while (!feof($stream)); return $contents; }
/** * helper method to get output as string out of a StreamOutput * * @param $output * * @return string all output */ protected function getOutputBuffer(StreamOutput $output) { $handle = $output->getStream(); rewind($handle); $display = stream_get_contents($handle); // Symfony2's StreamOutput has a hidden dependency on PHP_EOL which needs to be removed by // normalizing it to the standard newline for text here. $display = strtr($display, array(PHP_EOL => "\n")); return $display; }
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadConfig($input); $ignore_locked = false; $from_date = $this->getHarvestFromDate("Ymd", "3 days ago"); $to_date = $this->getHarvestToDate("Ymd", "today"); $chartType = $this->getChartType(null); $chartPeriod = $this->getChartPeriod(null); if (!($outputFilename = $input->getOption("output-file"))) { $outputFilename = 'FetchUserActivity-' . $from_date . '-' . $to_date . '.json'; } $output->writeln('FetchUserActivity executed: ' . date('Ymd H:i:s')); $output->writeln('Verifying projects in Harvest'); $output->writeln('Output filename: ' . $outputFilename); if ($this->getHarvestExcludeContractors()) { $output->writeln('NOTE: Contractors are excluded from the dataset!'); } $ticketEntries = $this->getEntriesByUsers($from_date, $to_date); $output->writeln(sprintf('Collected %d ticket entries', sizeof($ticketEntries))); if (sizeof($ticketEntries) == 0) { //We have no entries containing ticket ids so bail return; } // GET THE LATEST ENTRY FOR EACH USER IN PERIOD REGARDLESS OF PROJECT $sortedEntries = null; foreach ($ticketEntries as $userArray) { foreach ($userArray as $entry) { $notes = strlen($entry->get('notes')) > 0 ? $entry->get('notes') : "..."; $output->writeln(sprintf('%s | %s - %s: "%s" (%s timer @ %s)', self::getUserNameById($entry->get('user-id')), self::getProjectNameById($entry->get('project-id')), self::getTaskNameById($entry->get("task-id")), $notes, $entry->get('hours'), $entry->get('spent-at'))); $sortedEntries[strtotime($entry->get("updated-at"))] = $entry; } } krsort($sortedEntries); $userSortedEntries = null; foreach ($sortedEntries as $updated => $entry) { if (!isset($userSortedEntries[$entry->get('user-id')])) { $userSortedEntries[$entry->get('user-id')]['project'] = self::getProjectNameById($entry->get('project-id')); $userSortedEntries[$entry->get('user-id')]['task'] = self::getTaskNameById($entry->get('task-id')); $userSortedEntries[$entry->get('user-id')]['username'] = self::getUserNameById($entry->get('user-id')); $userSortedEntries[$entry->get('user-id')]['notes'] = $entry->get("notes"); $userSortedEntries[$entry->get('user-id')]['updated-at'] = $entry->get("updated-at"); $userSortedEntries[$entry->get('user-id')]['timer-started-at'] = $entry->get("timer-started-at"); $userSortedEntries[$entry->get('user-id')]['project-id'] = $entry->get('project-id'); $userSortedEntries[$entry->get('user-id')]['spent-at'] = $entry->get('spent-at'); } else { continue; } } $json = json_encode($userSortedEntries); // let's write the response to a file $outputFile = new StreamOutput(fopen('data/' . $outputFilename, 'w', false)); $outputFile->doWrite($json, false); $output->writeln("FetchUserActivity completed -> " . $outputFilename . " updated"); }
/** * Reads the contents of an output stream. * * @param StreamOutput $output The stream output manager. * * @return string The contents of the stream. */ protected function readOutput(StreamOutput $output) { $stream = $output->getStream(); $contents = ''; rewind($stream); do { $contents .= fgets($stream); } while (!feof($stream)); fclose($stream); return $contents; }
public function printLegend() { $symbols = array(); foreach (self::$eventStatusMap as $status) { $symbol = $status['symbol']; if ('' === $symbol || isset($symbols[$symbol])) { continue; } $symbols[$symbol] = sprintf('%s-%s', $this->output->isDecorated() ? sprintf($status['format'], $symbol) : $symbol, $status['description']); } $this->output->write(sprintf("\nLegend: %s\n", implode(', ', $symbols))); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadConfig($input); $from_date = $this->getHarvestFromDate("Ymd", "yesterday"); $to_date = $this->getHarvestToDate("Ymd", "yesterday"); $chartType = $this->getChartType(); $chartPeriod = $this->getChartPeriod(); if (!($outputFilename = $input->getOption("output-file"))) { $outputFilename = 'FetchData-' . $from_date . '-' . $to_date . '.xml'; } $output->writeln('FetchData executed: ' . date('Ymd H:i:s')); $output->writeln('Output filename: ' . $outputFilename); if ($this->getHarvestExcludeContractors()) { $output->writeln('NOTE: Contractors are excluded from the dataset!'); } $output->writeln(sprintf('Chart type is "%s" and period is "%s"', $chartType, $chartPeriod)); $output->writeln(sprintf("Collecting Harvest entries between %s to %s", $from_date, $to_date)); switch ($chartType) { case 'singlecolumn': $sortedTicketEntries = $this->fetchBillableHoursInPeriod($from_date, $to_date); $data = \GeckoChart::makeSingleColumn($sortedTicketEntries, $chartPeriod); break; // used for displaying budget vs. actual billable hours // used for displaying budget vs. actual billable hours case 'columnspline': $sortedTicketEntries = $this->fetchBillableHoursInPeriod($from_date, $to_date); $data = \GeckoChart::makeSingleColumnWithSpline($sortedTicketEntries, $chartPeriod); break; case 'stackedcolumn': $assembledEntries = $this->fetchAllHoursInPeriod($from_date, $to_date); $data = \GeckoChart::makeStackedColumn($assembledEntries, $chartPeriod); break; case 'piechart': $assembledEntries = $this->fetchAllHoursInPeriod($from_date, $to_date); $chartPeriodTitle = date("M. jS", strtotime($from_date)) . " - " . date("M. jS", strtotime($to_date)); $data = \GeckoChart::makePieChart($assembledEntries, $chartPeriodTitle); break; default: $output->writeln("FetchData ChartType not recognized -> " . $chartType . ""); return; break; } // lets write the data to a file if ($data) { $outputFile = new StreamOutput(fopen('data/' . $outputFilename, 'w', false)); $outputFile->doWrite($data, false); $output->writeln("\nFetchData completed -> " . $outputFilename . " updated"); } }
/** * @inheritdoc */ public function execute(ResultCollection $collection, ResultCollection $aggregatedResults) { if (!$this->destination) { return; } $dir = dirname($this->destination); if (!file_exists($dir)) { mkdir($dir, 0777, true); } $this->output->writeln(sprintf('Generating %s Report...', $this->formater->getName())); $handle = fopen($this->destination, 'w'); $stream = new StreamOutput($handle); $stream->write($this->formater->terminate($collection, $aggregatedResults)); fclose($handle); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadConfig($input); $ignore_locked = false; $from_date = $this->getHarvestFromDate("Ymd", "today"); $to_date = $this->getHarvestToDate("Ymd", "today"); $chartType = $this->getChartType(null); $chartPeriod = $this->getChartPeriod(null); if (!($outputFilename = $input->getOption("output-file"))) { $outputFilename = 'FetchEntries-' . $from_date . '-' . $to_date . '.xml'; } $output->writeln('FetchEntries executed: ' . date('Ymd H:i:s')); $output->writeln('Verifying projects in Harvest'); $output->writeln('Output filename: ' . $outputFilename); if ($this->getHarvestExcludeContractors()) { $output->writeln('NOTE: Contractors are excluded from the dataset!'); } $ticketEntries = $this->getEntriesByUsers($from_date, $to_date); $output->writeln(sprintf('Collected %d ticket entries', sizeof($ticketEntries))); if (sizeof($ticketEntries) == 0) { //We have no entries containing ticket ids so bail return; } $sortedEntries = null; foreach ($ticketEntries as $userArray) { foreach ($userArray as $entry) { $notes = strlen($entry->get('notes')) > 0 ? $entry->get('notes') : "..."; $output->writeln(sprintf('%s | %s - %s: "%s" (%s timer @ %s)', self::getUserNameById($entry->get('user-id')), self::getProjectNameById($entry->get('project-id')), self::getTaskNameById($entry->get("task-id")), $notes, $entry->get('hours'), $entry->get('spent-at'))); $sortedEntries[strtotime($entry->get("updated-at"))] = $entry; } } krsort($sortedEntries); // get top 30 $sortedEntries = array_slice($sortedEntries, 0, 30, true); // TODO: Refactor and move to GeckoChart.php // prepare the response! $geckoresponse = new \GeckoResponse(); // format as text foreach ($sortedEntries as $entry) { $notes = strlen($entry->get('notes')) > 0 ? $entry->get('notes') : "[no notes]"; $data['item'][] = array('text' => '<span class="t-size-x18">' . self::getProjectNameById($entry->get('project-id')) . ':</span><br/><span class="t-size-x24">"' . $notes . '"</span><br/><span class="t-size-x18">' . self::getUserNameById($entry->get('user-id')) . ' - ' . self::getTaskNameById($entry->get("task-id")) . ', ' . $entry->get('hours') . ' timer</span>', 'type' => 0); } $response = $geckoresponse->getResponse($data, true); // let's write the response to a file $outputFile = new StreamOutput(fopen('data/' . $outputFilename, 'w', false)); $outputFile->doWrite($response, false); $output->writeln("FetchEntries completed -> " . $outputFilename . " updated"); }
/** * Constructor. * * @param integer $verbosity The verbosity level (self::VERBOSITY_QUIET, self::VERBOSITY_NORMAL, * self::VERBOSITY_VERBOSE) * @param Boolean $decorated Whether to decorate messages or not (null for auto-guessing) * @param OutputFormatter $formatter Output formatter instance * * @api */ public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null) { $outputStream = 'php://stdout'; if (!$this->hasStdoutSupport()) { $outputStream = 'php://output'; } parent::__construct(fopen($outputStream, 'w'), $verbosity, $decorated, $formatter); }
/** * {@inheritDoc} */ public function run(OutputInterface $output) { $arguments = $this->resolveProcessArgs(); $builder = new ProcessBuilder($arguments); if (null !== ($dispatcher = $this->getEventDispatcher())) { $event = new PreExecuteEvent($this, $builder); $dispatcher->dispatch(Event::PRE_EXECUTE, $event); if ($event->isPropagationStopped()) { return true; } } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) { $output->writeln(sprintf(' // Setting timeout for %d seconds.', $this->getParameter('timeout'))); } $builder->setTimeout($this->getParameter('timeout') !== 0 ? $this->getParameter('timeout') : null); if ($this->hasParameter('cwd')) { $builder->setWorkingDirectory($this->getParameter('cwd')); } $process = $builder->getProcess(); if (get_class($this) === 'Bldr\\Block\\Execute\\Task\\ExecuteTask') { $output->writeln(['', sprintf(' <info>[%s]</info> - <comment>Starting</comment>', $this->getName()), '']); } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE || $this->getParameter('dry_run')) { $output->writeln(' // ' . $process->getCommandLine()); } if ($this->getParameter('dry_run')) { return true; } if ($this->hasParameter('output')) { $append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w'; $stream = fopen($this->getParameter('output'), $append); $output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true); } $process->start(function ($type, $buffer) use($output) { $output->write("\r " . str_replace("\n", "\n ", $buffer)); }); while ($process->isRunning()) { } if (null !== $dispatcher) { $event = new PostExecuteEvent($this, $process); $dispatcher->dispatch(Event::POST_EXECUTE, $event); } if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) { throw new TaskRuntimeException($this->getName(), $process->getErrorOutput()); } }
/** * @return string * * @throws \Exception */ private function getRawCommandOutput() { if (!$this->output) { throw new \Exception('No command output!'); } rewind($this->output->getStream()); return stream_get_contents($this->output->getStream()); }
protected function execute(InputInterface $input, OutputInterface $output) { $instance = $this->instances->find(Instance::makeId($input->getOption('root'), $input->getOption('name'))); if (!$instance) { throw new \Exception("Failed to locate instance: " . Instance::makeId($input->getOption('root'), $input->getOption('name'))); } $prefix = $input->getOption('prefix'); $dsnParts = \DB\DSN::parseDSN($instance->getDsn()); $output_file_path = $input->getOption('output-file'); if ($output_file_path != '') { $output_file = fopen($output_file_path, "w"); $output = new StreamOutput($output_file); } $envVars = array("{$prefix}URL" => $instance->getUrl(), "{$prefix}ROOT" => $instance->getRoot(), "{$prefix}DB_DSN" => $instance->getDsn(), "{$prefix}DB_USER" => $dsnParts['username'], "{$prefix}DB_PASS" => $dsnParts['password'], "{$prefix}DB_HOST" => $dsnParts['hostspec'], "{$prefix}DB_PORT" => $dsnParts['port'], "{$prefix}DB_NAME" => $dsnParts['database'], "{$prefix}DB_ARGS" => $instance->getDatasource() ? $instance->getDatasource()->toMySQLArguments() : ''); foreach ($envVars as $var => $value) { $output->writeln($var . '=' . escapeshellarg($value)); } // $output->writeln('export ' . implode(' ', array_keys($envVars))); }
/** * @Request(csrf=true) */ public function updateAction() { if (!($file = App::session()->get('system.update'))) { App::abort(400, __('You may not call this step directly.')); } App::session()->remove('system.update'); return App::response()->stream(function () use($file) { $output = new StreamOutput(fopen('php://output', 'w')); try { if (!file_exists($file) || !is_file($file)) { throw new \RuntimeException('File does not exist.'); } $updater = new SelfUpdater($output); $updater->update($file); } catch (\Exception $e) { $output->writeln(sprintf("\n<error>%s</error>", $e->getMessage())); $output->write("status=error"); } }); }
public function getIdephixMock($targets, $targetName) { $this->output = fopen("php://memory", 'r+'); $output = new StreamOutput($this->output); $currentTarget = new Config($targets[$targetName]); $sshClient = new SshClient(new FakeSsh2Proxy($this)); $sshClient->setParameters($currentTarget->get('ssh_params')); $sshClient->setHost(current($currentTarget->get('hosts'))); $sshClient->connect(); $idx = $this->getMock('\\Idephix\\IdephixInterface'); $idx->sshClient = $sshClient; $idx->output = $output; $idx->expects($this->any())->method('getCurrentTarget')->will($this->returnValue($currentTarget)); $idx->expects($this->any())->method('getCurrentTargetName')->will($this->returnValue($targetName)); $idx->expects($this->any())->method('local')->will($this->returnCallback(function ($cmd) use($output) { $output->writeln('Local: ' . $cmd); })); $idx->expects($this->any())->method('remote')->will($this->returnCallback(function ($cmd) use($output) { $output->writeln('Remote: ' . $cmd); })); return $idx; }
/** * {@inheritDoc} */ public function run(OutputInterface $output) { /** @type DebugFormatterHelper $debugFormatter */ $debugFormatter = $this->getHelperSet()->get('debug_formatter'); $arguments = $this->resolveProcessArgs(); $builder = new ProcessBuilder($arguments); $process = $builder->getProcess(); if (null !== ($dispatcher = $this->getEventDispatcher())) { $event = new PreExecuteEvent($this, $process); $dispatcher->dispatch(Event::PRE_EXECUTE, $event); if ($event->isPropagationStopped()) { return true; } } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) { $output->writeln(sprintf(' // Setting timeout for %d seconds.', $this->getParameter('timeout'))); } $process->setTimeout($this->getParameter('timeout') !== 0 ? $this->getParameter('timeout') : null); if ($this->hasParameter('cwd')) { $process->setWorkingDirectory($this->getParameter('cwd')); } if (get_class($this) === 'Bldr\\Block\\Execute\\Task\\ExecuteTask') { $output->writeln(['', sprintf(' <info>[%s]</info> - <comment>Starting</comment>', $this->getName()), '']); } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE || $this->getParameter('dry_run')) { $output->writeln(' // ' . $process->getCommandLine()); } if ($this->getParameter('dry_run')) { return true; } if ($this->hasParameter('output')) { $append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w'; $stream = fopen($this->getParameter('output'), $append); $output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true); } $output->writeln("<fg=blue>==============================\n</fg=blue>"); $output->writeln($debugFormatter->start(spl_object_hash($process), $process->getCommandLine())); $process->run(function ($type, $buffer) use($output, $debugFormatter, $process) { if ($this->getParameter('raw')) { $output->write($buffer, false, OutputInterface::OUTPUT_RAW); return; } $output->write($debugFormatter->progress(spl_object_hash($process), $buffer, Process::ERR === $type)); }); $output->writeln($debugFormatter->stop(spl_object_hash($process), $process->getCommandLine(), $process->isSuccessful())); $output->writeln("<fg=blue>==============================</fg=blue>"); if (null !== $dispatcher) { $event = new PostExecuteEvent($this, $process); $dispatcher->dispatch(Event::POST_EXECUTE, $event); } if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) { throw new TaskRuntimeException($this->getName(), $process->getErrorOutput()); } }
/** * Runs a command and returns it output. * * @param Client $client * @param string $command * @param int $verbosity Verbosity level to use. * @param int $exitCode Expected command exit code. * * @return string */ protected function runCommand(Client $client, $command, $verbosity = OutputInterface::VERBOSITY_NORMAL, $exitCode = 0) { $application = new Application($client->getKernel()); $application->setAutoExit(false); $fp = tmpfile(); $input = new StringInput($command); $output = new StreamOutput($fp); $output->setVerbosity($verbosity); $realCode = $application->run($input, $output); fseek($fp, 0); $output = ''; while (!feof($fp)) { $output = fread($fp, 4096); } fclose($fp); $this->assertEquals($exitCode, $realCode, $output); return $output; }
/** * Configure output console parameters. * * @param StreamOutput $console */ protected function configureOutputConsole(StreamOutput $console) { $console->setVerbosity($this->parameters->get('verbose') ? StreamOutput::VERBOSITY_VERBOSE : StreamOutput::VERBOSITY_NORMAL); $console->getFormatter()->setDecorated($this->parameters->get('decorated')); }
protected function getOutputContent(StreamOutput $output) { rewind($output->getStream()); return str_replace(PHP_EOL, "\n", stream_get_contents($output->getStream())); }
private function getOutput(StreamOutput $output) { rewind($output->getStream()); return stream_get_contents($output->getStream()); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadConfig($input); $ignore_locked = false; $from_date = $this->getHarvestFromDate("Ymd", "yesterday"); $to_date = $this->getHarvestToDate("Ymd", "yesterday"); $chartType = $this->getChartType("geekometer"); $chartPeriod = $this->getChartPeriod("day"); /* $updated_since = null; // NULL meeans all projects (and is thereby slow), but it doesnt seem to work correctly if I set the date otherwise // Ahh: http://forum.getharvest.com/forums/api-and-developer-chat/topics/announcement-greater-availability-of-updated_since-filtering-in-api // $updated_since = urlencode($this->getHarvestFromDate($input, "Y-m-d 00:00")); */ if (!($outputFilename = $input->getOption("output-file"))) { $outputFilename = 'FetchBillable-' . $from_date . '-' . $to_date . '.xml'; } //Setup Harvest API access $harvest = $this->getHarvestApi(); $output->writeln('FetchBillable executed: ' . date('Ymd H:i:s')); $output->writeln('Verifying projects in Harvest'); $output->writeln('Output filename: ' . $outputFilename); if ($this->getHarvestExcludeContractors()) { $output->writeln('NOTE: Contractors are excluded from the dataset!'); } $output->writeln(sprintf('Chart type is "%s" and period is "%s"', $chartType, $chartPeriod)); $output->writeln(sprintf("Collecting Harvest entries between %s to %s", $from_date, $to_date)); $sortedTicketEntries = $this->fetchBillableHoursInPeriod($from_date, $to_date); $output->writeln(sprintf('Collected %d ticket entries', sizeof($sortedTicketEntries) - 1)); if (!sizeof($sortedTicketEntries) > 0) { //We have no entries containing ticket ids so bail return; } $output->writeln(sprintf('OutputFormat for Geckoboard: %s', $chartType)); switch ($chartType) { default: case "geekometer": $output->writeln(sprintf('"%s" will show data for the entire period regardless of what is specified', $chartType)); // prepare the response! $geckoresponse = new \GeckoResponse(); $billableHours = $sortedTicketEntries["statistics"]["totalhours"]; $output->writeln(sprintf('Billable hours from %s to %s: %s', $from_date, $to_date, $billableHours)); $data['item'] = round($billableHours); $data['type'] = "standard"; $data['min'][] = array('value' => 0, 'text' => ''); $data['max'][] = array('value' => 75, 'text' => ''); // fetch data $response = $geckoresponse->getResponse($data, true); break; case "line": $output->writeln(sprintf('Billable hours from %s to %s: %s', $from_date, $to_date, $sortedTicketEntries["statistics"]["totalhours"])); // lets strip the statistics data array_pop($sortedTicketEntries); $sortedTicketEntries = \GeckoChart::formatValuesToKeys($sortedTicketEntries, $chartPeriod); $response = \GeckoChart::formatXmlGeckoboardLine($sortedTicketEntries); break; } // let's write the response to a file $outputFile = new StreamOutput(fopen('data/' . $outputFilename, 'w', false)); $outputFile->doWrite($response, false); $output->writeln("FetchBillable completed -> " . $outputFilename . " updated"); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $locale = $input->getOption('locale'); if (empty($locale)) { $locale = 'en_US'; } $domain = $input->getOption('domain'); $bundle = $input->getOption('bundle'); $log = $input->getOption('logfile'); $loader = $this->getContainer()->get('mautic.translation.loader'); $factory = $this->getContainer()->get('mautic.factory'); $viewsOnly = $input->getOption('only-views'); $dupsOnly = $input->getOption('only-dups'); $bundles = $factory->getMauticBundles(true); if (!empty($log)) { $logfile = fopen($log, 'w+'); $output = new StreamOutput($logfile, null, false, new OutputFormatter(false)); } if (!empty($bundle)) { if (!isset($bundles[$bundle])) { $output->writeln('Bundle not found'); return; } $bundles = [$bundles[$bundle]]; } // Load defined messages $currentCatalogue = new MessageCatalogue($locale); // Extract used messages from Views $extractedCatalogue = new MessageCatalogue($locale); $phpFormExtractor = new PhpFormTranslationExtractor(); foreach ($bundles as $bundle) { if (!$dupsOnly) { if (file_exists($bundle['directory'] . '/Views')) { $phpFormExtractor->extract($bundle['directory'] . '/Views', $extractedCatalogue); $this->getContainer()->get('translation.extractor')->extract($bundle['directory'] . '/Views', $extractedCatalogue); } if (!$viewsOnly) { $directories = ['/Form/Type', '/EventListener', '/Model', '/EventListener', '/Controller']; foreach ($directories as $d) { if (file_exists($bundle['directory'] . $d)) { $phpFormExtractor->extract($bundle['directory'] . $d, $extractedCatalogue); $this->getContainer()->get('translation.extractor')->extract($bundle['directory'] . $d, $extractedCatalogue); } } } } if (is_dir($bundle['directory'] . '/Translations')) { $currentCatalogue = $loader->load(null, $locale, $domain); } } // Merge defined and extracted messages to get all message ids $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue); $allMessages = $mergeOperation->getResult()->all($domain); if (null !== $domain) { $allMessages = [$domain => $allMessages]; } // No defined or extracted messages if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) { $outputMessage = sprintf('<info>No defined or extracted messages for locale "%s"</info>', $locale); if (null !== $domain) { $outputMessage .= sprintf(' <info>and domain "%s"</info>', $domain); } $output->writeln($outputMessage); return; } /** @var \Symfony\Component\Console\Helper\Table $table */ $table = new Table($output); // Display header line $headers = ['State(s)', 'Id', sprintf('Message Preview (%s)', $locale)]; $table->setHeaders($headers); $duplicateCheck = []; // Iterate all message ids and determine their state foreach ($allMessages as $domain => $messages) { foreach (array_keys($messages) as $messageId) { $value = $currentCatalogue->get($messageId, $domain); $duplicateKey = strtolower($value); if (!isset($duplicateCheck[$duplicateKey])) { $duplicateCheck[$duplicateKey] = []; } $duplicateCheck[$duplicateKey][] = ['id' => $messageId, 'domain' => $domain]; $states = []; if ($extractedCatalogue->defines($messageId, $domain)) { if (!$currentCatalogue->defines($messageId, $domain)) { $states[] = self::MESSAGE_MISSING; } } elseif ($currentCatalogue->defines($messageId, $domain)) { $states[] = self::MESSAGE_UNUSED; } if (!in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused') || !in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) { continue; } $row = [$this->formatStates($states), $this->formatId($messageId), $this->sanitizeString($value)]; $table->addRow($row); } } if (!$dupsOnly) { $table->render(); $output->writeln(''); $output->writeln('<info>Legend:</info>'); $output->writeln(sprintf(' %s Missing message', $this->formatState(self::MESSAGE_MISSING))); $output->writeln(sprintf(' %s Unused message', $this->formatState(self::MESSAGE_UNUSED))); $output->writeln(sprintf(' %s Same as the fallback message', $this->formatState(self::MESSAGE_EQUALS_FALLBACK))); } $output->writeln(''); $output->writeln('<info>Duplicates:</info>'); /** @var \Symfony\Component\Console\Helper\Table $table */ $table = new Table($output); // Display header line $headers = ['Value', 'Domain', 'Message ID']; $table->setHeaders($headers); //Check for duplicates $totalDuplicateCount = 0; foreach ($duplicateCheck as $value => $dups) { $count = count($dups); if ($count > 1) { ++$totalDuplicateCount; $table->addRow(['', '', '']); $table->addRow([$this->sanitizeString($value), $count, '']); foreach ($dups as $dup) { $table->addRow(['', $dup['domain'], $dup['id']]); } } } $table->render(); $output->writeln(''); $output->writeln('<info>Total number of duplicates: ' . $totalDuplicateCount . '</info>'); }
/** * Write to output * * @param array|string $messages Messages * @param bool $newline Whether to append a newline * @param int $type The output type * * @return void */ public function write($messages, $newline = false, $type = \Symfony\Component\Console\Output\Output::OUTPUT_NORMAL) { $messages = (array) $messages; foreach ($messages as &$message) { $l = strlen($message) - 1; if ($l >= 0) { if ($message[$l] === "\n") { $message = substr($message, 0, $l); $l--; $newline = true; } if ($this->previousWasNewLine && $l >= 0 && $message[0] !== "\n") { $message = $this->getIndention() . $message; } if (strpos($message, "\n") !== false) { $message = str_replace("\n", "\n" . $this->getIndention(), $message); } // TODO: Indent wrapped lines - that's just not that easy because of the ANSI color escape codes } } parent::write($messages, $newline, $type); $this->previousWasNewLine = $newline; }
/** * {@inheritdoc} */ public function setVerbosity($level) { parent::setVerbosity($level); $this->stderr->setVerbosity($level); }
/** * Constructor. * * @param StreamOutput $output */ public function __construct(StreamOutput $output) { parent::__construct($output->getStream()); }