private function testEnv(array $functions, $url, OutputInterface $output) { $soapClient = new \SoapClient($url, array('cache_wsdl' => 0, 'trace' => 1, 'soap_version' => SOAP_1_1)); foreach ($functions as $function => $parameters) { $output->writeln('Test de la fonction soap <comment>' . $function . '</comment>'); $output->writeln('Parameters : '); dump($parameters); if (!array_key_exists('methodCall', $this->config) || $this->config['methodCall'] == 'soapCall') { $result = $soapClient->__soapCall($function, $parameters); } else { $result = $soapClient->{$function}($parameters); } $headers = $soapClient->__getLastResponseHeaders(); if ($output->isDebug()) { $output->writeln('Entete de la reponse : '); dump($headers); } if (false === ($site = $this->getSiteHeader($headers))) { throw new \Exception('Site Header introuvable dans la réponse.', 1); } $output->writeln('Serveur ayant repondu : <info>' . $site . '</info>'); $output->writeln('Reponse : '); dump($result); if ($output->isDebug()) { dump($soapClient->__getLastResponse()); } } }
protected function execute(InputInterface $input, OutputInterface $output) { Wp::load(); $targetTheme = null; $targetThemeSlug = $input->getArgument('theme'); if (static::CURRENT_THEME == $input->getArgument('theme')) { // no user chosen theme: load current /** @var \WP_Theme $targetTheme */ $targetTheme = wp_get_theme(); $targetThemeSlug = $targetTheme->get_stylesheet(); } if (!$targetTheme) { // load user chosen theme $targetTheme = wp_get_theme($targetThemeSlug); } if (!$targetTheme->exists()) { throw new \DomainException('Theme ' . $targetThemeSlug . ' does not exist.'); } if ($output->isDebug()) { $output->writeln('Theme: ' . $targetTheme->get_stylesheet()); } $morphMethod = $this->getMorphMethod($input); // resolve readable name $name = $targetThemeSlug; if ($targetTheme->get('Name')) { $name = $targetTheme->get('Name'); } $this->verbose('Checking ' . $name); // resolve theme text domain $textDomain = $name; if ($targetTheme->get('TextDomain')) { $textDomain = $targetTheme->get('TextDomain'); } $this->verbose(' (TextDomain: ' . $textDomain . ')' . PHP_EOL); $langPath = WpTheme::resolveLanguagesPath($targetTheme); // fetch strings $extractor = new WordPressExtractor(); $extractor::$extractComments = true; $extractor::$textDomain = $textDomain; $translatable = $extractor->fromDirectory($targetTheme->get_stylesheet_directory()); // todo B fetch and merge translations from po file $translatable->setDomain($textDomain); $translatable->ksort(); // skeleton created // file name is same as the slug which is a common way if you look at twenty* themes. $skeletonBasename = $targetThemeSlug . '.' . $input->getOption('format'); if ('po' == $input->getOption('format')) { // po templates have the pot extension in the filename $skeletonBasename .= 't'; } // merge with existing template $skeletonPath = $langPath . '/' . $skeletonBasename; $extractMethod = 'from' . ucfirst($input->getOption('format')) . 'File'; /** @var Translations $skeletonTranslation */ $skeletonTranslation = call_user_func(['\\Gettext\\Translations', $extractMethod], [$skeletonPath]); $this->sanitizeTranslation($translatable, $textDomain, $targetTheme->get_stylesheet_directory()); $skeletonTranslation->mergeWith($translatable, $translatable::MERGE_ADD | $translatable::MERGE_REFERENCES); $this->writeTranslation($input, $output, $skeletonPath, $skeletonTranslation); $this->updateTranslations($input, $output, $targetTheme, $skeletonTranslation, $textDomain); }
protected function execute(InputInterface $input, OutputInterface $output) { $serverSection = $input->getOption('server'); $config = new \Zend_Config_Ini('config.ini', $serverSection); $server = $config->server; if (!isset($server->host)) { throw new \Exception("Invalid server settings for section '{$serverSection}': host is required"); } if (isset($server->user)) { $host = $server->user . '@' . $server->host; } else { $host = $server->host; } if (isset($server->port)) { $host .= ' -p ' . $server->port; } if (isset($server->dir)) { $cmd = "cd " . $server->dir . ';'; } $gitEnvVars = "GIT_AUTHOR_NAME=" . escapeshellarg(isset($_ENV['GIT_AUTHOR_NAME']) ? $_ENV['GIT_AUTHOR_NAME'] : trim(`git config user.name`)) . " GIT_AUTHOR_EMAIL=" . escapeshellarg(isset($_ENV['GIT_AUTHOR_EMAIL']) ? $_ENV['GIT_AUTHOR_EMAIL'] : trim(`git config user.email`)) . " GIT_COMMITTER_NAME=" . escapeshellarg(isset($_ENV['GIT_COMITTER_NAME']) ? $_ENV['GIT_COMITTER_NAME'] : trim(`git config user.name`)) . " GIT_COMMITTER_EMAIL=" . escapeshellarg(isset($_ENV['GIT_COMITTER_EMAIL']) ? $_ENV['GIT_COMITTER_EMAIL'] : trim(`git config user.email`)); $cmd .= $gitEnvVars . ' '; $cmd .= "exec bash"; $cmd = "ssh -t {$host} " . escapeshellarg($cmd); if ($output->isDebug()) { $output->writeln($cmd); } $ret = null; passthru($cmd, $ret); exit($ret); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $manifest = Manifest::download($this->pharUpdateManifestUrl, $output->isDebug()); $manager = new Manager($manifest, $this->getLocalFilesystem()); !$this->logger ?: $manager->setLogger($this->logger); $currentVersion = $this->getApplication()->getVersion(); $newVersion = null !== $input->getArgument('version') ? $input->getArgument('version') : null; $major = $input->getOption('major'); // Lock to current major version? $pre = true; //Allow pre-releases? if (false === $manager->update($currentVersion, $major, $pre, $newVersion, $output->isDebug())) { return self::EXIT_ERROR; } return self::EXIT_SUCCESS; }
/** * Runs an external process. * * @param OutputInterface $output An OutputInterface instance * @param string|array|Process $cmd An instance of Process or an array of arguments to escape and run or a command to run * @param string|null $error An error message that must be displayed if something went wrong * @param callable|null $callback A PHP callback to run whenever there is some * output available on STDOUT or STDERR * @param int $verbosity The threshold for verbosity * * @return Process The process that ran */ public function run(OutputInterface $output, $cmd, $error = null, $callback = null, $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE) { $formatter = $this->getHelperSet()->get('debug_formatter'); if (is_array($cmd)) { $process = ProcessBuilder::create($cmd)->getProcess(); } elseif ($cmd instanceof Process) { $process = $cmd; } else { $process = new Process($cmd); } if ($verbosity <= $output->getVerbosity()) { $output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine()))); } if ($output->isDebug()) { $callback = $this->wrapCallback($output, $process, $callback); } $process->run($callback); if ($verbosity <= $output->getVerbosity()) { $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode()); $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful())); } if (!$process->isSuccessful() && null !== $error) { $output->writeln(sprintf('<error>%s</error>', $this->escapeString($error))); } return $process; }
/** * Build Process instance for each testcase file * * @param string $fileName * @param array $phpunitArgs * @return Process */ protected function buildProcess($fileName, array $phpunitArgs = []) { $processBuilder = new ProcessBuilder(); $dispatcher = $this->command->getDispatcher(); $dispatcher->dispatch(CommandEvents::RUN_TESTS_PROCESS, $processEvent = new RunTestsProcessEvent($this->command, $this->input, $this->output, $processBuilder, $phpunitArgs)); $process = $processBuilder->setEnv('BROWSER_NAME', $this->input->getArgument('browser'))->setEnv('ENV', strtolower($this->input->getArgument('environment')))->setEnv('SERVER_URL', $this->input->getOption('server-url'))->setEnv('PUBLISH_RESULTS', $this->input->getOption('publish-results') ? '1' : '0')->setEnv('FIXTURES_DIR', $this->input->getOption('fixtures-dir'))->setEnv('LOGS_DIR', $this->input->getOption('logs-dir'))->setEnv('DEBUG', $this->output->isDebug() ? '1' : '0')->setPrefix(STEWARD_BASE_DIR . '/vendor/bin/phpunit')->setArguments(array_merge($processEvent->getArgs(), [$fileName]))->setTimeout(3600)->getProcess(); return $process; }
/** * {@inheritdoc} */ protected function executeCommandByProject($projectName, ProjectConfiguration $projectConfig, OutputInterface $output) { $this->getSshExec()->passthru(strtr('cd %project_dir% && /usr/local/bin/sami update sami_config.php' . ($output->isDebug() ? ' -v' : ''), ['%project_dir%' => $projectConfig->getRemoteWebappDir()])); $localBuildDir = sprintf('%s/build/apidoc', $projectConfig->getLocalWebappDir()); $apiDocIndexFilepath = strtr('%build_dir%/index.html', ['%project_name%' => $projectConfig->getProjectName(), '%build_dir%' => $localBuildDir]); if (file_exists($apiDocIndexFilepath)) { $this->openFile($apiDocIndexFilepath); } }
/** * Creates a debug message. */ public function debug($message, \PhpParser\Node $expr = null) { if ($this->output->isDebug()) { $this->output->writeln('[DEBUG] ' . $message); $this->output->write($this->filepath); if ($expr) { $this->output->write(':' . $expr->getLine()); } $this->output->writeln(''); } }
private function _systemCheckRet($cmd, InputInterface $input, OutputInterface $output) { $ret = null; if ($output->isDebug()) { $output->writeln($cmd); } passthru($cmd, $ret); if ($ret != 0) { throw new \Exception("command failed"); } }
/** * @{inheritdoc} */ protected function executeCommandByProject($projectName, ProjectConfiguration $projectConfig, OutputInterface $output) { $remoteReportFilePath = strtr('%build_dir%/%project_name%.html', ['%project_name%' => $projectConfig->getProjectName(), '%build_dir%' => $this->remoteBuildDir]); // Analyse source project code $this->getSshExec()->passthru(strtr('mkdir -p %build_dir% && /usr/local/bin/phpmetrics --level=0 --report-html=%report_file% %project_dir%/src' . ($output->isDebug() ? ' --verbose' : ''), ['%report_file%' => $remoteReportFilePath, '%build_dir%' => $this->remoteBuildDir, '%project_dir%' => $projectConfig->getRemoteWebappDir()])); $localReportFilePath = str_replace($this->remoteBuildDir, $this->localBuildDir, $remoteReportFilePath); $this->getRemoteFilesystem()->copyRemoteFileToLocal($remoteReportFilePath, $localReportFilePath); if ($this->getLocalFilesystem()->exists($localReportFilePath)) { $this->openFile($localReportFilePath); } return $this->getSshExec()->getLastReturnStatus(); }
protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('host'); $username = $input->getOption('username'); $password = $input->getOption('password'); //Debug: print received options if ($output->isDebug()) { $output->writeln("host=" . $host); $output->writeln("username="******"password=" . $password); } }
protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Get weather info from yandex. CityId = ' . $this->_config['weather']['cityId']); $info = new \Petun\YaSpeech\Weather\Info($this->_config['weather']['cityId']); $composer = new \Petun\YaSpeech\Weather\Composer($info); if ($output->isDebug()) { $output->writeln('Generated text is ' . $composer->getComposition($this->_config['weather']['composition'])); } $output->writeln('Send text to yandex speech'); $speech = new \Petun\YaSpeech\Speech\Processor($this->_config['speech']['apiKey'], $this->_config['speech']['speaker'], $this->_config['speech']['emotion']); $content = $speech->getMp3($composer->getComposition($this->_config['weather']['composition'])); if ($content) { $fileToSave = $this->_config['cacheDir'] . '/today_weather.mp3'; $output->writeln('Save to file - ' . $fileToSave); $bytes = file_put_contents($fileToSave, $content); if ($output->isDebug()) { $output->writeln('Write ' . $bytes . ' bytes'); } } else { $output->writeln('Error while download file'); } }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var ConsoleOutput $output */ $container = $this->getContainer(); $logger = $container->get('logger'); /** @var LocaleRepository $localeRepository */ $localeRepository = $container->get('doctrine')->getManager()->getRepository('OmCmsI18nBundle:Locale'); $aliases = $localeRepository->getActiveAliases(); if ($output->isDebug()) { $logger->debug('Find aliases', $aliases); } $parameters = ['parameters' => ['om_cms_i18n.locale.aliases' => $aliases]]; $filename = $container->getParameter('om_cms_i18n.locale.filename'); $fs = new Filesystem(); $dumper = new Dumper(); $data = $dumper->dump($parameters); $fs->dumpFile($filename, $data); if ($output->isDebug()) { $logger->debug('Dump data', ['filename' => $filename, $data]); } if ($input->getOption('cache-clear')) { $cmd = $this->getContainer()->getParameter('kernel.root_dir') . '/console '; $inputParameters = ['command' => 'cache:clear', '--env' => $container->getParameter('kernel.environment')]; if ($output->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) { $inputParameters['--no-debug'] = null; } $cmd .= (new ArrayInput($inputParameters))->__toString(); $process = new Process($cmd); $process->mustRun(function ($type, $buffer) use($output) { if (Process::ERR === $type) { $output->write('<error>' . $buffer . '</error>'); } else { if ($output->isDebug()) { $output->write($buffer); } } }); } }
/** * @{inheritdoc} */ protected function executeCommandByProject($projectName, ProjectConfiguration $projectConfig, OutputInterface $output) { $this->getSshExec()->passthru(strtr('cd %project_dir% && phpspec run --format=%format% --stop-on-failure ' . ($output->isDebug() ? ' --verbose' : ''), ['%format%' => $this->format, '%project_dir%' => $projectConfig->getRemoteWebappDir()])); $buildDir = $this->remoteBuildDir . '/tests'; $this->getRemoteFilesystem()->mkdir($buildDir); $report = $this->getSshExec()->exec(strtr('cd %project_dir% && phpspec run --format=html --no-interaction > %build_dir%/unit.html', ['%project_dir%' => $projectConfig->getRemoteWebappDir(), '%build_dir%' => $buildDir])); $this->getRemoteFilesystem()->syncRemoteToLocal($this->remoteBuildDir, $this->localBuildDir, ['delete' => true]); $statusCode = $this->getSshExec()->getLastReturnStatus() == 0 && strpos($report, 'broken') === false ? 0 : 1; if ($this->displayStatusText) { $output->writeln(sprintf('<comment>Executes unit tests for project "<info>%s</info>"</comment>: %s', $projectName, $statusCode == 0 ? '<info>SUCCESS</info>' : '<error>ERROR</error>')); } return $statusCode; }
/** * @param Process $process * @param OutputInterface $output */ private function runTests($process, $output) { if ($output->isDebug()) { $process->run(function ($type, $buffer) use($output) { if (Process::ERR === $type) { $output->write('<fg=yellow>' . $buffer . '</fg=yellow>'); } else { $output->write($buffer); } }); } else { $process->run(); } }
protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('host'); $username = $input->getOption('username'); $password = $input->getOption('password'); //Debug: print received options if ($output->isDebug()) { $output->writeln("host=" . $host); $output->writeln("username="******"password="******"TODO Format address-list"); }
protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('host'); $username = $input->getOption('username'); $password = $input->getOption('password'); //Debug: print received options if ($output->isDebug()) { $output->writeln("host=" . $host); $output->writeln("username="******"password=" . $password); } $data = $this->getResources($host, $username, $password); $this->outFormatter($input, $output, $data); }
public function computeLogThreshold(OutputInterface $output) { if ($output->isDebug()) { return Logger::DEBUG; } if ($output->isVeryVerbose()) { return Logger::INFO; } if ($output->isVerbose()) { return Logger::INFO; } if ($output->isQuiet()) { return \PHP_INT_MAX; } return Logger::WARNING; }
protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('host'); $username = $input->getOption('username'); $password = $input->getOption('password'); //Debug: print received options if ($output->isDebug()) { $output->writeln("host=" . $host); $output->writeln("username="******"password="******"Time missing: i.e. reboot in 10m"); exit; } $output->writeln("TODO reboot in " . $input->getArgument('action')[1]); break; case 'cancel': //cancels scheduled reboot break; case 'now': //no prompt $output->writeln("TODO reboot now " . $host); $this->doReboot($host, $username, $password); break; default: //prompt confirm reboot $ans = $this->askConfirm($input, $output); if ($ans !== true) { exit; } $output->writeln("TODO reboot " . $host); $this->doReboot($host, $username, $password); } }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $logger = new ConsoleLogger($output); $questionAsker = new QuestionAsker($this->getHelper('question'), $input, $output); try { $targetDir = call_user_func_array($this->dirValidatorFactory, [$questionAsker, $this->filesystem])->validateValue($input->getArgument('path')); $data = call_user_func_array($this->dataProviderFactory, [$questionAsker])->getData(); $assets = call_user_func_array($this->assetCollectionFactory, [$this->filesystem, $data]); $assets->exportToDir($targetDir); } catch (\Exception $e) { if ($output->isDebug()) { throw $e; } $logger->error($e->getMessage()); return Application::EXIT_CODE_MAPPING[get_class($e)] ?? Application::EXIT_CODE_UNKOWN_ERROR; } }
protected function execute(InputInterface $input, OutputInterface $output) { $runtimeTask = new RuntimeTask($this, $this->definedTask, $input, $output); if ($output->isVerbose()) { $output->writeln("<info>Starting </info>" . $this->definedTask->getName()); } $this->ancestry[] = $this->definedTask->getName(); if ($output->isDebug()) { $output->writeln("<info>Current ancestry is </info>" . implode(" > ", $this->ancestry)); } $this->runBeforeTask($output); if ($output->isVerbose()) { $output->writeln("<info>Running </info>" . $this->definedTask->getName()); } $retVal = $this->fire($runtimeTask); $this->runAfterTask($output); if ($output->isVerbose()) { $output->writeln("<info>Finished </info>" . $this->definedTask->getName()); } return $retVal; }
protected function execute(InputInterface $input, OutputInterface $output) { $this->setThreshold($input->getOption('days')); if ($input->getOption('dry-run')) { $output->writeln('<info>This is a dry-run run, no pad will deleted.</info>'); } if ($output->isVerbose()) { $output->writeln(sprintf('<info>INFO:</info> Pads before %s will be deleted', $this->threshold->format($this->dateFormat))); } $padIds = $this->getAllPads($input->getOption('apikey'), $input->getOption('host')); if ($padIds === false) { $output->writeln('<error>Could not receive all pads.</error>'); return; } if ($output->isVerbose()) { $output->writeln(sprintf('<info>INFO:</info> %s pad(s) stored', $this->countPads)); } foreach ($padIds as $padId) { $lastEdited = Pad::getLastEdited($padId, $input->getOption('apikey'), $input->getOption('host')); if ($lastEdited === false) { $this->countPadsFailed++; continue; } if ($lastEdited < $this->threshold->getTimestamp()) { if ($output->isDebug()) { $output->writeln(sprintf('<info>DEBUG:</info> "%s" was last edited on %s and will purged', $padId, date($this->dateFormat, $lastEdited))); } if (!$input->getOption('dry-run')) { if (!Pad::deletePad($padId, $input->getOption('apikey'), $input->getOption('host'))) { $this->countPadsFailed++; } } $this->countPadsDeleted++; } } if ($output->isVerbose()) { $output->writeln(sprintf('<info>INFO:</info> %s pad(s) deleted', $this->countPadsDeleted)); $output->writeln(sprintf('<info>INFO:</info> %s pad(s) failed', $this->countPadsFailed)); } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->info('Start tail on ' . date('d.m.Y H:i')); $file = $this->config->receivers['log']['to']; $lastContent = false; if (file_exists($file)) { while ($content = file_get_contents($file)) { if ($output->isDebug()) { $this->comment('Check log file for new content'); } if ($content !== $lastContent) { $newContent = preg_replace('/^' . preg_quote($lastContent) . '/', '', $content); // is not first while run if ($lastContent != false) { $this->comment($newContent); } $lastContent = $content; } sleep(1); } } else { $this->error("Log file not exists."); } }
/** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $verbosity = $output->getVerbosity(); if ($verbosity > 0) { $verbosityMapping = [1 => Logger::WARNING, 2 => Logger::NOTICE, 3 => Logger::INFO, 4 => Logger::DEBUG]; $handler = new StreamHandler('php://stdout', $verbosityMapping[$verbosity]); $handler->setFormatter(new ColoredLineFormatter()); $this->logger->pushHandler($handler); } if ($output->isVerbose()) { $this->eventDispatcher->addListener(EventEnum::QUEUE_BINDED, function (AMQPQueueBindedEvent $event) use($output) { $output->writeln('topic binded: ' . $event->getBindingKey()); }); $this->eventDispatcher->addListener(\Lexsign\StateMachine\Events\EventEnum::VALUE_UPDATED, function (ValueEvent $event) use($output) { $changeSet = $event->getChangeSet(); if ($changeSet->hasChanged()) { $output->writeln('<info>' . $changeSet->getTimestamp()->format(DateTime::ISO8601) . ' - ' . $changeSet->getKey() . ': ' . var_export($changeSet->getPreviousValue(), true) . ' -> ' . var_export($changeSet->getCurrentValue(), true) . '</info>'); } }); } if ($output->isVeryVerbose()) { $this->eventDispatcher->addListener(\Lexsign\StateMachine\Events\EventEnum::VALUE_UPDATED, function (ValueEvent $event) use($output) { $changeSet = $event->getChangeSet(); if (!$changeSet->hasChanged()) { $output->writeln($changeSet->getTimestamp()->format(DateTime::ISO8601) . ' - ' . $changeSet->getKey() . ': not changed - ' . var_export($changeSet->getPreviousValue(), true)); } }); } if ($output->isDebug()) { $this->eventDispatcher->addListener(EventEnum::INCOMING_MESSAGE, function (AMQPIncomingEvent $event) use($output) { $msg = $event->getMessage(); $output->writeln('<comment>' . $msg->delivery_info['routing_key'] . ' - ' . $msg->body . '</comment>'); }, 1000); } $this->amqpFetcher->run(); }
/** * Returns whether verbosity is debug (-vvv). * * @return bool */ public function isDebug() { return $this->output->isDebug(); }
protected function execute(InputInterface $input, OutputInterface $output) { $skipExtensions = $input->getOption('skip-extensions'); $skipModules = $input->getOption('skip-modules'); $skipHooks = $input->getOption('skip-hooks'); $skipWidgets = $input->getOption('skip-widgets'); $skipTasks = $input->getOption('skip-tasks'); $skipPlugins = $input->getOption('skip-plugins'); $skipSetup = $input->getOption('skip-setup'); $save_path = $input->getOption('path'); $save_basedir = join(\DIRECTORY_SEPARATOR, [getcwd(), $save_path]); // Check for any existing files if ($output->isVeryVerbose()) { $output->writeln('Checking for any existing proxy class files in ' . $save_basedir); } if (is_dir($save_basedir)) { $glob_path = join(\DIRECTORY_SEPARATOR, [$save_basedir, '*']); $files = glob($glob_path); if ($output->isVerbose()) { $output->writeln(sprintf('Removing %d old proxy class files', count($files))); } else { $output->writeln('Removing old proxy class files'); } // Iterate over the files and delete them foreach ($files as $file) { if (is_file($file)) { if ($output->isDebug()) { $output->writeln('Removing file: ' . $file); } unlink($file); } } } // Make sure our base directories exist if (!is_dir($save_basedir)) { if ($output->isVeryVerbose()) { $output->writeln('Creating proxy classes directory: ' . $save_basedir); } mkdir($save_basedir, 0755); } $excluded = [$save_path, 'datastore']; $filter = function ($file, $key, $iterator) use($excluded) { if ($iterator->hasChildren() && !in_array($file->getFilename(), $excluded)) { return true; } return $file->isFile(); }; $dirIterator = new \RecursiveDirectoryIterator(getcwd(), \RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new \RecursiveIteratorIterator(new \RecursiveCallbackFilterIterator($dirIterator, $filter), \RecursiveIteratorIterator::SELF_FIRST); // Get a list of files to iterate over $files_to_parse = []; $iterator = new \RegexIterator($iterator, '/^.+\\.php$/i', \RecursiveRegexIterator::GET_MATCH); foreach ($iterator as $file) { $files_to_parse[] = $file; } $count = count($files_to_parse); if ($output->isDebug()) { $output->writeln(count($files_to_parse) . ' files matched'); } // Start our progress bar and disable the console cursor $output->write("[?25l", true); $progress = new ProgressBar($output, $count); $progress->setFormat(" %namespace%\n %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%"); $i = 0; foreach ($files_to_parse as $file) { $filePath = $file[0]; $handle = @fopen($filePath, "r"); if ($handle) { $namespace = ''; while (!feof($handle)) { $line = fgets($handle, 4096); $matches = array(); // Get the namespace preg_match('/^namespace(.+?)([^\\;]+)/', $line, $matched); if (isset($matched[0])) { $namespace = $matched[0]; } // Filter results # Extensions if (mb_strpos($namespace, '\\extensions\\') and $skipExtensions) { if ($output->isDebug()) { $output->writeln('Skipping extension: ' + $filePath); } $progress->advance(); continue; } # Modules if (mb_strpos($namespace, '\\modules\\front\\') or mb_strpos($namespace, '\\modules\\admin\\')) { if ($skipModules) { if ($output->isDebug()) { $output->writeln('Skipping module: ' + $filePath); } $progress->advance(); continue; } } # Hooks if (mb_strpos($filePath, \DIRECTORY_SEPARATOR . 'hooks' . \DIRECTORY_SEPARATOR) and $skipHooks) { if ($output->isDebug()) { $output->writeln('Skipping hook: ' + $filePath); } $progress->advance(); continue; } # Widgets if (mb_strpos($filePath, \DIRECTORY_SEPARATOR . 'widgets' . \DIRECTORY_SEPARATOR) and $skipWidgets) { if ($output->isDebug()) { $output->writeln('Skipping widget: ' + $filePath); } $progress->advance(); continue; } # Tasks if (mb_strpos($filePath, \DIRECTORY_SEPARATOR . 'tasks' . \DIRECTORY_SEPARATOR) and $skipTasks) { if ($output->isDebug()) { $output->writeln('Skipping task: ' + $filePath); } $progress->advance(); continue; } # Plugins if (mb_strpos($filePath, \DIRECTORY_SEPARATOR . 'plugins' . \DIRECTORY_SEPARATOR) and $skipPlugins) { if ($output->isDebug()) { $output->writeln('Skipping plugin: ' + $filePath); } $progress->advance(); continue; } # Setup if (mb_strpos($filePath, \DIRECTORY_SEPARATOR . 'setup' . \DIRECTORY_SEPARATOR) and $skipSetup) { if ($output->isDebug()) { $output->writeln('Skipping setup: ' + $filePath); } $progress->advance(); continue; } if (preg_match('#^(\\s*)((?:(?:abstract|final|static)\\s+)*)class\\s+([-a-zA-Z0-9_]+)(?:\\s+extends\\s+([-a-zA-Z0-9_]+))?(?:\\s+implements\\s+([-a-zA-Z0-9_,\\s]+))?#', $line, $matches)) { if (substr($matches[3], 0, 1) === '_') { $content = ''; $append = ltrim($matches[3], '\\'); $m = ltrim($matches[3], '\\'); $m = str_replace('_', '', $m); $content = "<?php\n\n"; if ($namespace) { $content .= $namespace . ";\n\n"; } $content .= $matches[2] . 'class ' . $m . ' extends ' . $append . '{}' . "\n"; $progress->setMessage($namespace, 'namespace'); $filename = mb_strtolower($m) . '.php'; $filePath = join(\DIRECTORY_SEPARATOR, [getcwd(), $save_path, $filename]); if (!is_file($filePath)) { file_put_contents($filePath, $content); } else { $alt = str_replace(["\\", " ", ";"], "_", $namespace); $filename = $alt . "_" . $filename; $filePath = join(\DIRECTORY_SEPARATOR, [getcwd(), $save_path, $filename]); file_put_contents($filePath, $content); } $i++; } } } $progress->advance(); fclose($handle); } else { $progress->advance(); } } // Finish and re-enable the cursor $progress->finish(); $output->write("[?25h", true); }
/** * Returns whether verbosity is debug (-vvv). * * @return bool true if verbosity is set to VERBOSITY_DEBUG, false otherwise */ public function isDebug() { return $this->decoratedOutput->isDebug(); }
private function recursive_copy(InputInterface $input, OutputInterface $output, ProgressBar $progress, $dirsourceparent, $dirsource = "", $newinstall = true, $make_links = false) { global $amp_conf; $bmoinst = \FreePBX::create()->Installer; $moh_subdir = isset($amp_conf['MOHDIR']) ? trim(trim($amp_conf['MOHDIR']), '/') : 'moh'; // total # files, # actually copied $num_files = $num_copied = 0; if ($dirsource && $dirsource[0] != "/") { $dirsource = "/" . $dirsource; } if (is_dir($dirsourceparent . $dirsource)) { $dir_handle = opendir($dirsourceparent . $dirsource); } while (isset($dir_handle) && ($file = readdir($dir_handle))) { if ($file == "." || $file == ".." || $file == "CVS" || $file == ".svn" || $file == ".git") { continue; } if ($dirsource == "" && $file == "moh" && !$newinstall) { // skip to the next dir continue; } $source = $dirsourceparent . $dirsource . "/" . $file; if (!is_dir($source)) { $destination = $bmoinst->getDestination('framework', str_replace($this->rootPath . "/", "", $source)); // These are modified by apply_conf.sh, there may be others that fit in this category also. This keeps these from // being symlinked and then developers inadvertently checking in the changes when they should not have. // $never_symlink = array("cdr_adaptive_odbc.conf", "indications.conf", "manager.conf", "modules.conf"); $num_files++; if ($make_links && !in_array(basename($source), $never_symlink)) { // symlink, unlike copy, doesn't overwrite - have to delete first // ^^ lies! :( if (is_link($destination) || file_exists($destination)) { if (!is_dir($destination)) { unlink($destination); } } if (file_exists($source)) { if ($output->isDebug()) { $output->writeln("Linking " . basename($source) . " to " . dirname($destination)); } @symlink($source, $destination); } } else { $ow = false; if (file_exists($destination) && !is_link($destination)) { if ($input->isInteractive() && $this->check_diff($source, $destination) && !$make_links) { $output->writeln($destination . " has been changed from the original version."); $ow = $this->ask_overwrite($input, $output, $source, $destination); } elseif (!$input->isInteractive() && $this->check_diff($source, $destination) && !$make_links) { if (basename($source) == "manager.conf") { $ow = false; } else { $output->writeln($destination . " has been changed from the original version."); $ow = true; } } } else { $ow = true; } if ($ow) { //Copy will not overwrite a symlink, phpnesssss if (file_exists($destination) && is_link($destination)) { if (!is_dir($destination)) { unlink($destination); } } if ($output->isDebug()) { $output->writeln("Copying " . basename($source) . " to " . dirname($destination)); } copy($source, $destination); } else { continue; } } $num_copied++; } else { $destination = $bmoinst->getDestination('framework', str_replace($this->rootPath . "/", "", $source) . "/"); // if this is a directory, ensure destination exists if (!file_exists($destination)) { if ($destination != "") { if ($output->isDebug()) { $output->writeln("Creating " . $destination); } @mkdir($destination, "0750", true); } } list($tmp_num_files, $tmp_num_copied) = $this->recursive_copy($input, $output, $progress, $dirsourceparent, $dirsource . "/" . $file, $newinstall, $make_links); $num_files += $tmp_num_files; $num_copied += $tmp_num_copied; } if ($progress->getStep() < $progress->getMaxSteps()) { $progress->advance(); } } if (isset($dir_handle)) { closedir($dir_handle); } return array($num_files, $num_copied); }
/** * @param string $command * @param OutputInterface $output * @param array $options Process options, includes: * bool logfile * bool stderr * bool stdout * int timeout * string input * array env * string cwd * @return Process */ public static function process(OutputInterface $output, $command, array $options = []) { $options = array_merge(['stderr' => true, 'stdout' => $output->isDebug(), 'timeout' => 60, 'input' => null, 'env' => null, 'cwd' => null, 'logfile' => null], $options); $output->writeDebug(str_repeat('-', 55)); $output->writeDebug("Executing command: {$command}"); $output->writeDebug(str_repeat('-', 55)); $process = new Process($command, $options['cwd'], $options['env'], $options['input'], $options['timeout']); $process->run(function ($type, $buffer) use($output, $options) { if ($type === Process::ERR) { if ($options['stderr']) { $output->writeStderr($buffer); } return; } if (!$options['stdout']) { return; } $buffer = trim($buffer, "\n"); if (empty($buffer)) { return; } $output->writeStdout($buffer); }); $output->writeDebug(str_repeat('-', 55)); return $process; }
private function createClient(OutputInterface $output) { $debug = $output->isDebug() && $output instanceof ConsoleOutput ? $output->getErrorOutput()->getStream() : false; return new GuzzleClient(['cookies' => true, 'debug' => $debug]); }