protected function execute(InputInterface $input, OutputInterface $output) { $url = $input->getOption('url'); $email = $input->getOption('email'); $disable = $input->getOption('disable'); $events = $input->getOption('event'); if (!$url && !$email) { $output->writeln('<error>Must specify either a url or an email address</error>'); return; } if ($url && $email) { $output->writeln('<error>Must specify only a url or an email address</error>'); return; } if (!($resource = $this->getResource('webhook', $output))) { return; } if ($url) { $resource->setUrl($url); } else { $resource->setEmail($email); } $resource->setEventTypes($events ? $events : Webhook::$events); $this->getApi()->create($resource); $resource = $this->getApi()->getLastResponse(); $resource = $resource['body']['data']; $table = $this->getHelperSet()->get('table'); $this->formatTableRow($resource, $table, false); $output->writeln('<info>Webhook created</info>'); $table->render($output); }
protected function execute(InputInterface $input, OutputInterface $output) { $path = $input->getArgument('path'); if (!file_exists($path)) { $output->writeln("{$path} is not a file or a path"); } $filePaths = []; if (is_file($path)) { $filePaths = [realpath($path)]; } elseif (is_dir($path)) { $filePaths = array_diff(scandir($path), array('..', '.')); } else { $output->writeln("{$path} is not known."); } $generator = new StopwordGenerator($filePaths); if ($input->getArgument('type') === 'json') { echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE); echo json_last_error_msg(); die; $output->write(json_encode($this->toArray($generator->getStopwords()))); } else { $stopwords = $generator->getStopwords(); $stdout = fopen('php://stdout', 'w'); echo 'token,freq' . PHP_EOL; foreach ($stopwords as $token => $freq) { fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL; } fclose($stdout); } }
/** * @see Command */ protected function execute(InputInterface $input, OutputInterface $output) { $doctrine = $this->getContainer()->get('doctrine'); $em = $doctrine->getManager(); $name = $input->getArgument('name'); $system = $input->getArgument('system'); /* @var RepositoryInterface $roleRepository */ $repository = $this->getContainer()->get('sulu.repository.role'); $role = $repository->findOneByName($name); if ($role) { $output->writeln(sprintf('<error>Role "%s" already exists.</error>', $name)); return 1; } /** @var RoleInterface $role */ $role = $repository->createNew(); $role->setName($name); $role->setSystem($system); $pool = $this->getContainer()->get('sulu_admin.admin_pool'); $securityContexts = $pool->getSecurityContexts(); // flatten contexts $securityContextsFlat = []; array_walk_recursive($securityContexts['Sulu'], function ($value) use(&$securityContextsFlat) { $securityContextsFlat[] = $value; }); foreach ($securityContextsFlat as $securityContext) { $permission = new Permission(); $permission->setRole($role); $permission->setContext($securityContext); $permission->setPermissions(127); $role->addPermission($permission); } $em->persist($role); $em->flush(); $output->writeln(sprintf('Created role "<comment>%s</comment>" in system "<comment>%s</comment>".', $role->getName(), $role->getSystem())); }
protected function execute(InputInterface $input, OutputInterface $output) { // Replace this with dependency injection once available /** @var DiagnosticService $diagnosticService */ $diagnosticService = StaticContainer::get('Piwik\\Plugins\\Diagnostics\\DiagnosticService'); $showAll = $input->getOption('all'); $report = $diagnosticService->runDiagnostics(); foreach ($report->getAllResults() as $result) { $items = $result->getItems(); if (!$showAll && $result->getStatus() === DiagnosticResult::STATUS_OK) { continue; } if (count($items) === 1) { $output->writeln($result->getLabel() . ': ' . $this->formatItem($items[0]), OutputInterface::OUTPUT_PLAIN); continue; } $output->writeln($result->getLabel() . ':'); foreach ($items as $item) { $output->writeln("\t- " . $this->formatItem($item), OutputInterface::OUTPUT_PLAIN); } } if ($report->hasWarnings()) { $output->writeln(sprintf('<comment>%d warnings detected</comment>', $report->getWarningCount())); } if ($report->hasErrors()) { $output->writeln(sprintf('<error>%d errors detected</error>', $report->getErrorCount())); return 1; } return 0; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $remoteFilename = 'http://get.insight.sensiolabs.com/insight.phar'; $localFilename = $_SERVER['argv'][0]; $tempFilename = basename($localFilename, '.phar') . '-temp.phar'; try { copy($remoteFilename, $tempFilename); if (md5_file($localFilename) == md5_file($tempFilename)) { $output->writeln('<info>insight is already up to date.</info>'); unlink($tempFilename); return; } chmod($tempFilename, 0777 & ~umask()); // test the phar validity $phar = new \Phar($tempFilename); // free the variable to unlock the file unset($phar); rename($tempFilename, $localFilename); $output->writeln('<info>insight updated.</info>'); } catch (\Exception $e) { if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { throw $e; } unlink($tempFilename); $output->writeln('<error>The download is corrupt (' . $e->getMessage() . ').</error>'); $output->writeln('<error>Please re-run the self-update command to try again.</error>'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $inputSource = $input->getOption('input'); $size = (int) $input->getOption('size'); if ($size < 1 || $size > 2000) { $output->writeln('<error>Sample size must be a positive integer between 1 and 2000.</error>'); return; } // Input size should be 10 times the size of the sample $streamSize = $size * 10; switch ($inputSource) { case 'stdin': $stream = new StreamIterator(); break; case 'random.org': $stream = new RandomOrgIterator($this->httpClient); $stream->setLength($streamSize); break; case 'internal': $stream = new RandomByteIterator(); $stream->setLength($streamSize); break; default: $output->writeln('<error>Unknown input source: "' . $inputSource . '". Use either stdin, random.org or internal.</error>'); return; } $this->sampler->setStream($stream); $result = $this->sampler->getSampleAsString($size); $output->writeln($result); }
protected function runCommand(InputInterface $input, OutputInterface $output) { $output->writeln(''); $executedMigrations = $this->manager->executedMigrations(); $output->writeln('<comment>Executed migrations</comment>'); if (empty($executedMigrations)) { $output->writeln('<info>No executed migrations</info>'); } else { $rows = []; foreach ($executedMigrations as $migration) { $rows[] = [ltrim($migration['classname'], '\\'), $migration['executed_at']]; } $this->printTable(['Class name', 'Executed at'], $rows, $output); } $output->writeln(''); $migrations = $this->manager->findMigrationsToExecute(Manager::TYPE_UP); $output->writeln('<comment>Migrations to execute</comment>'); if (empty($migrations)) { $output->writeln('<info>No migrations to execute</info>'); } else { $rows = []; foreach ($migrations as $migration) { $rows[] = [$migration->getClassName()]; } $this->printTable(['Class name'], $rows, $output); } }
protected function execute(InputInterface $input, OutputInterface $output) { $header_style = new OutputFormatterStyle('white', 'green', array('bold')); $output->getFormatter()->setStyle('header', $header_style); $start = intval($input->getOption('start')); $stop = intval($input->getOption('stop')); if ($start >= $stop || $start < 0) { throw new \InvalidArgumentException('Stop number should be greater than start number'); } $output->writeln('<header>Fibonacci numbers between ' . $start . ' - ' . $stop . '</header>'); $xnM2 = 0; // set x(n-2) $xnM1 = 1; // set x(n-1) $xn = 0; // set x(n) $totalFiboNr = 0; while ($xnM2 <= $stop) { if ($xnM2 >= $start) { $output->writeln('<header>' . $xnM2 . '</header>'); $totalFiboNr++; } $xn = $xnM1 + $xnM2; $xnM2 = $xnM1; $xnM1 = $xn; } $output->writeln('<header>Total of Fibonacci numbers found = ' . $totalFiboNr . ' </header>'); }
protected function execute(InputInterface $input, OutputInterface $output) { $subUrls = $input->getArgument('url'); $outputFile = $input->getArgument('output-file'); // Daten laden $kosS = new KingOfSatScrapper(); $output->writeln('Start Pulling Data'); if (count($subUrls) > 0) { $firstRun = true; foreach ($subUrls as $url) { $data = $kosS->getTransponderData($url); $output->writeln(count($data) . ' Transponders found in ' . $url); if (true === $firstRun && count($data) > 0) { $this->setupExcel(array_keys($data[0])); $firstRun = false; } $this->addRowsToExcel($data); } // Daten ausgeben $output->writeln('Generate Excelfile: ' . $outputFile); $this->saveExcel($outputFile); } else { $output->writeln('<error>Missing pages to Scrap. See help.</error>'); } $output->writeln('<info>(c) Steven Buehner <*****@*****.**></info>'); }
protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get('doctrine')->getManager(); $scheduler = $this->getContainer()->get('scheduler'); $campaignId = $input->getArgument('campaignId'); $deliveryTime = new \DateTime($input->getArgument('deliverytime')); $month = $input->getArgument('month'); $year = $input->getArgument('year'); $date = $input->getArgument('date'); // The date at which the job is to be run $dateParts = explode('-', $date); if (!checkdate($dateParts[1], $dateParts[2], $dateParts[0])) { $output->writeLn("<error>Invalid date or format. Correct format is Y-m-d</error>"); return; } $now = new \DateTime(); $output->writeln("<comment>Scheduling recommendations email started on {$now->format('Y-m-d H:i:s')}</comment>"); // Get All Users $qb = $em->createQueryBuilder(); $qb->add('select', 'DISTINCT u.id')->add('from', 'ClassCentralSiteBundle:User u')->join('u.userPreferences', 'up')->join('u.follows', 'uf')->andWhere('uf is NOT NULL')->andWhere("up.value = 1")->andWhere('u.isverified = 1')->andWhere("up.type=" . UserPreference::USER_PREFERENCE_PERSONALIZED_COURSE_RECOMMENDATIONS); $users = $qb->getQuery()->getArrayResult(); $scheduled = 0; $dt = new \DateTime($date); $deliveryTime = $deliveryTime->format(\DateTime::RFC2822); foreach ($users as $user) { $id = $scheduler->schedule($dt, RecommendationEmailJob::RECOMMENDATION_EMAIL_JOB_TYPE, 'ClassCentral\\MOOCTrackerBundle\\Job\\RecommendationEmailJob', array('campaignId' => $campaignId, 'deliveryTime' => $deliveryTime, 'month' => $month, 'year' => $year), $user['id']); if ($id) { $scheduled++; } } $output->writeln("<info>{$scheduled} recommendation emails jobs scheduled</info>"); }
protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get('doctrine')->getManager(); /** @var PluginManager $processManager */ $output->writeln('Updating Datamaps...'); $json = file_get_contents($input->getArgument('url') . '/datamap/list/json'); if (!$json) { throw new \Exception('Wrong JSON response.'); } $datamaps = json_decode($json, true); if (count($datamaps)) { foreach ($datamaps as $datamap) { $output->write('Updating map "' . $datamap['name'] . '... '); $localDatamap = $em->getRepository('VRAppBundle:Datamap')->findOneBy(['name' => $datamap['name']]); if (!$localDatamap) { $localDatamap = new Datamap(); $localDatamap->setName($datamap['name']); } $localDatamap->setType($datamap['type']); $localDatamap->setMap(base64_decode($datamap['map'])); $localDatamap->setDescription($datamap['description']); $em->persist($localDatamap); $em->flush(); $output->writeln('<info>Done</info>'); } } $output->writeln('Finished.'); }
protected function execute(InputInterface $input, OutputInterface $output) { $i = 0; $kernel = $this->getContainer()->get('kernel'); $doctrine = $this->getContainer()->get('doctrine'); $entityManager = $doctrine->getEntityManager(); $cron = new Cron(); $cron->setTimestamp(time()); $cron->setAction('Observe Alarms Start'); $entityManager->persist($cron); $entityManager->flush(); $isSandbox = $input->getOption('sandbox'); $isEmulation = $input->getOption('emulate'); $output->writeln('Sandbox: ' . $isSandbox); $output->writeln('Emulation: ' . $isEmulation); // operating under the assumption that this thing is executed by a cronjob, this thing needs to be run for just a minute $intervalSpent = 0; while ($intervalSpent <= self::CRON_INTERVAL) { $detector = new AlarmDetector($doctrine); $detector->detectAlarms($isEmulation); $output->writeln(PHP_EOL . ++$i . PHP_EOL); usleep(self::CHECK_INTERVAL); // 250ms $intervalSpent += self::CHECK_INTERVAL; } }
/** * @see Console\Command\Command */ protected function execute(InputInterface $input, OutputInterface $output) { $module = $input->getArgument('module'); $modules = $this->moduleManager->getModules(); $path = "{$this->modulesDir}/{$module}-module"; if (isset($modules[$module])) { $output->writeln("<error>Module '{$module}' already exists.</error>"); return; } if (file_exists($path)) { $output->writeln("<error>Path '" . $path . "' exists.</error>"); return; } if (!is_writable(dirname($path))) { $output->writeln("<error>Path '" . dirname($path) . "' is not writable.</error>"); return; } umask(00); mkdir($path, 0777, TRUE); file_put_contents($path . '/Module.php', $this->getModuleFile($module)); file_put_contents($path . '/composer.json', $this->getComposerFile($module)); file_put_contents($path . '/readme.md', $this->getReadmeFile($module)); mkdir($path . '/Resources/config', 0777, TRUE); mkdir($path . '/Resources/public', 0777, TRUE); mkdir($path . '/Resources/translations', 0777, TRUE); mkdir($path . '/Resources/layouts', 0777, TRUE); mkdir($path . '/' . ucfirst($module) . 'Module', 0777, TRUE); }
/** * Executes installation * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance * * @return null|integer null or 0 if everything went fine, or an error code */ protected function execute(InputInterface $input, OutputInterface $output) { try { $output->write("Creating Branch logo directory..." . "\n"); $this->createBranchLogoDirectory(); $output->writeln("Done" . "\n"); $output->write("Creating attachments directory..." . "\n"); $this->createAttachmentsDirectory(); $output->writeln("Done" . "\n"); $output->write("Installing DB schema..." . "\n"); $this->updateDbSchema(); $output->writeln("Done" . "\n"); $this->loadData($output); $this->updateEntityConfig($output); $output->write("Updating navigation..." . "\n"); $this->updateNavigation($output); $output->writeln("Done" . "\n"); $output->write("Loading migration data" . "\n"); $this->loadDataFixtures($output); $output->writeln("Done" . "\n"); } catch (\Exception $e) { $output->writeln($e->getMessage()); return 255; } $output->writeln("Installed!" . "\n"); return 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $bundleName = $input->getArgument('bundle'); $filterEntity = $input->getOption('entity'); $foundBundle = $this->findBundle($bundleName); if ($metadatas = $this->getBundleMetadatas($foundBundle)) { $output->writeln(sprintf('Generating entities for "<info>%s</info>"', $foundBundle->getName())); $entityGenerator = $this->getEntityGenerator(); foreach ($metadatas as $metadata) { if ($filterEntity && $metadata->getReflClass()->getShortName() !== $filterEntity) { continue; } if (strpos($metadata->name, $foundBundle->getNamespace()) === false) { throw new \RuntimeException( "Entity " . $metadata->name . " and bundle don't have a common namespace, ". "generation failed because the target directory cannot be detected."); } $output->writeln(sprintf(' > generating <comment>%s</comment>', $metadata->name)); $entityGenerator->generate(array($metadata), $this->findBasePathForBundle($foundBundle)); } } else { throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped entities."); } }
/** * {@inheritdoc} */ protected function writePrompt(OutputInterface $output, Question $question) { $text = $question->getQuestion(); $default = $question->getDefault(); switch (true) { case null === $default: $text = sprintf(' <info>%s</info>:', $text); break; case $question instanceof ConfirmationQuestion: $text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no'); break; case $question instanceof ChoiceQuestion && $question->isMultiSelect(): $choices = $question->getChoices(); $default = explode(',', $default); foreach ($default as $key => $value) { $default[$key] = $choices[trim($value)]; } $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, implode(', ', $default)); break; case $question instanceof ChoiceQuestion: $choices = $question->getChoices(); $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $choices[$default]); break; default: $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $default); } $output->writeln($text); if ($question instanceof ChoiceQuestion) { $width = max(array_map('strlen', array_keys($question->getChoices()))); foreach ($question->getChoices() as $key => $value) { $output->writeln(sprintf(" [<comment>%-{$width}s</comment>] %s", $key, $value)); } } $output->write(' > '); }
/** * Execute the command. * * @param Input $input * @param Output $output * @return void */ protected function execute(Input $input, Output $output) { $name = $input->getArgument("name"); // Validate the name straight away. if (count($chunks = explode("/", $name)) != 2) { throw new \InvalidArgumentException("Invalid repository name '{$name}'."); } $output->writeln(sprintf("Cloning <comment>%s</comment> into <info>%s/%s</info>...", $name, getcwd(), end($chunks))); // If we're in a test environment, stop executing. if (defined("ADVISER_UNDER_TEST")) { return null; } // @codeCoverageIgnoreStart if (!$this->git->cloneGithubRepository($name)) { throw new \UnexpectedValueException("Repository https://github.com/{$name} doesn't exist."); } // Change the working directory. chdir($path = getcwd() . "/" . end($chunks)); $output->writeln(sprintf("Changed the current working directory to <comment>%s</comment>.", $path)); $output->writeln(""); // Running "AnalyseCommand"... $arrayInput = [""]; if (!is_null($input->getOption("formatter"))) { $arrayInput["--formatter"] = $input->getOption("formatter"); } $this->getApplication()->find("analyse")->run(new ArrayInput($arrayInput), $output); // Change back, remove the directory. chdir(getcwd() . "/.."); $this->removeDirectory($path); $output->writeln(""); $output->writeln(sprintf("Switching back to <info>%s</info>, removing <comment>%s</comment>...", getcwd(), $path)); // @codeCoverageIgnoreStop }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<comment>Scan begining.</comment>'); $result = $this->getContainer()->get('dokapi.swagger.scanner')->scan(); $output->writeln('<comment>Scan done.</comment>'); $apis = $result->getAll('api'); $output->writeln(sprintf('<info>%s api(s) detected(s)</info>', count($apis))); if ($input->getOption('verbose')) { foreach ($result->getAll('api') as $api) { $output->writeln(sprintf('-----------------------------------------------------------------')); $output->writeln(sprintf('--- Api version: <info>%s</info>, path: <info>%s</info>', $api->getVersion(), $api->getPath())); $output->writeln(sprintf('-----------------------------------------------------------------')); foreach ($api->getResources() as $resource) { $output->writeln(sprintf('------ Resource: <comment>%s</comment>', $resource->getId())); foreach ($resource->getOperations() as $operation) { $output->writeln(sprintf('--------- <comment>%s</comment>, path: <comment>%s</comment>, parameters: <comment>%s</comment>, responses: <comment>%s</comment>', $operation->getId(), $operation->getPath(), count($operation->getParameters()), count($operation->getResponses()))); } } } } if ($outputDir = $input->getOption('output-dir')) { $output->writeln(sprintf('Output results in directory <info>%s</info>', $outputDir)); $renderer = new FilesystemRenderer($outputDir); $renderer->render($result); $output->writeln('<info>Done.</info>'); } }
/** * {@inheritdoc } */ protected function execute(InputInterface $input, OutputInterface $output) { $privateKeyPath = $input->getOption('privateKey'); $keyBundlePath = $input->getOption('certificate'); $path = $input->getOption('path'); if (is_null($privateKeyPath) || is_null($keyBundlePath) || is_null($path)) { $output->writeln('--privateKey, --certificate and --path are required.'); return null; } $privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath); $keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath); if ($privateKey === false) { $output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath)); return null; } if ($keyBundle === false) { $output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath)); return null; } $rsa = new RSA(); $rsa->loadKey($privateKey); $x509 = new X509(); $x509->loadX509($keyBundle); $x509->setPrivateKey($rsa); $this->checker->writeCoreSignature($x509, $rsa, $path); $output->writeln('Successfully signed "core"'); }
/** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int|void */ protected function execute(InputInterface $input, OutputInterface $output) { // Call preExecute (separating it allows that portion to be overloaded in inherited classes) $this->_preExecute($input, $output); // Set the various attributes $this->_resetEverything(); try { if ($this->_hasFSI()) { // Use AvS_FastSimpleImport (this is actually slower for single / smaller quantities), // but since it's faster for larger quantities that's the code path that has been // fully implemented, so we still use it here for single products. $this->_output->write("<info>Generating product... </info>"); $product = array($this->_generateProduct($this->_productData)); $this->_output->writeln("<info>Done.</info>"); $this->_output->write("Importing product... </info>"); $this->_importProducts($product); $this->_output->writeln("<info>Done.</info>"); } else { // Use regular Magento product creation. This path is not fully implemented yet. $this->_output->write("<info>Creating product... </info>"); $product = $this->_createProduct($this->_productData); $this->_output->writeln("<info>Done, id : " . $product->getId() . "</info>"); } } catch (\Exception $e) { $this->_output->writeln("<error>Problem creating product: " . $e->getMessage() . "</error>"); } }
protected function execute(InputInterface $input, OutputInterface $output) { $logins = $input->getOption('login'); $skipExisting = $input->getOption('skip-existing'); if (empty($logins)) { $logins = $this->ldapUsers->getAllUserLogins(); } $count = 0; $failed = array(); foreach ($logins as $login) { if ($skipExisting && $this->userExistsInPiwik($login)) { $output->write("Skipping '{$login}', already exists in Piwik..."); continue; } $output->write("Synchronizing '{$login}'... "); try { $this->loginLdapAPI->synchronizeUser($login); ++$count; $output->writeln("<info>success!</info>"); } catch (Exception $ex) { $failed[] = array('login' => $login, 'reason' => $ex->getMessage()); $output->writeln("<error>failed!</error>"); } } $this->writeSuccessMessage($output, array("Synchronized {$count} users!")); if (!empty($failed)) { $output->writeln("<info>Could not synchronize the following users in LDAP:</info>"); foreach ($failed as $missingLogin) { $output->writeln($missingLogin['login'] . "\t\t<comment>{$missingLogin['reason']}</comment>"); } } return count($failed); }
private function cleanupTerms(Treatment $treatment) { // find terms for this treatment $qb = $this->om->createQueryBuilder(); $qb->select('t2')->from('TermBundle:Term', 't2')->innerJoin('t2.termDocuments', 'td', Join::WITH, 'td.type = :treatmentType')->setParameter('treatmentType', TermDocument::TYPE_TREATMENT)->where('td.documentId = :treatmentId')->setParameter('treatmentId', $treatment->getId()); $terms = $qb->getQuery()->getResult(); $this->output->writeln('Cleaning terms for treatment #' . $treatment->getId() . ' [' . $treatment->getName() . ']'); if (\count($terms)) { $hasInternal = false; foreach ($terms as $term) { $this->output->write($this->indent() . $term->getName() . " [#{$term->getId()}]" . $this->indent()); if (!$term->getInternal()) { // if this has not been flagged as internal yet, flag it $term->setInternal(\strtolower($term->getName()) == \strtolower($treatment->getName())); } if (!$hasInternal) { $hasInternal = $term->getInternal(); } $this->om->persist($term); $this->output->writeln('[OK]'); } if (!$hasInternal) { $term = $this->createTermFromTreatment($treatment); $this->om->persist($term); $this->output->writeln($this->indent() . 'Added internal term'); } } else { $this->output->write($this->indent() . "Found no terms: "); $term = $this->createTermFromTreatment($treatment); $this->om->persist($term); $this->output->writeln('[OK]'); } }
public function copy($sourceLicense, $destination, $destinationFilename = 'LICENSE') { // Check if the source license file exists if (!file_exists($sourceLicense)) { throw new LicenseFileDoesNotExistException(sprintf('%s cannot be read or does not exist', $sourceLicense)); } // Create the full destination $fullDestination = $destination . '/' . $destinationFilename; // Get the checksum value for each file $sourceChecksum = $this->checksum($sourceLicense); $destinationChecksum = $this->checksum($fullDestination); if ($sourceChecksum == $destinationChecksum) { $this->output->writeln('<info>No license changes detected!</info>'); return; } // Perform the copy-file try { $this->performCopy($sourceLicense, $fullDestination); // Output trace msg $msg = sprintf('%s was successfully copied into %s', $sourceLicense, $fullDestination); $this->output->writeln('<info>' . $msg . '</info>'); } catch (\Exception $e) { throw new LicenseCouldNotBeCreatedException(sprintf('%s could not be created, from source: %s; %s', $fullDestination, $sourceLicense, $e->getMessage()), 0, $e); } }
/** * @see \Symfony\Component\Console\Command\Command::execute() */ protected function execute(InputInterface $input, OutputInterface $output) { $username = $input->getArgument('username'); $password = $input->getArgument('password'); $email = $input->getArgument('email'); $displayname = $input->getArgument('displayname'); $role = $input->getArgument('role'); $data = ['username' => $username, 'password' => $password, 'email' => $email, 'displayname' => $displayname, 'roles' => [$role]]; $user = new Entity\Users($data); $valid = true; if (!$this->app['users']->checkAvailability('username', $user->getUsername())) { $valid = false; $output->writeln("<error>Error creating user: username {$user->getUsername()} already exists</error>"); } if (!$this->app['users']->checkAvailability('email', $user->getEmail())) { $valid = false; $output->writeln("<error>Error creating user: email {$user->getEmail()} exists</error>"); } if (!$this->app['users']->checkAvailability('displayname', $user->getDisplayname())) { $valid = false; $output->writeln("<error>Error creating user: display name {$user->getDisplayname()} already exists</error>"); } if ($valid) { $res = $this->app['users']->saveUser($user); if ($res) { $this->auditLog(__CLASS__, "User created: {$user['username']}"); $output->writeln("<info>Successfully created user: {$user['username']}</info>"); } else { $output->writeln("<error>Error creating user: {$user['username']}</error>"); } } }
/** * @param InputInterface $input * @param OutputInterface $output * @param array $items * @param string $prefix */ protected function writeArrayInOutputFormat(InputInterface $input, OutputInterface $output, $items, $prefix = ' - ') { switch ($input->getOption('output')) { case self::OUTPUT_FORMAT_JSON: $output->writeln(json_encode($items)); break; case self::OUTPUT_FORMAT_JSON_PRETTY: $output->writeln(json_encode($items, JSON_PRETTY_PRINT)); break; default: foreach ($items as $key => $item) { if (is_array($item)) { $output->writeln($prefix . $key . ':'); $this->writeArrayInOutputFormat($input, $output, $item, ' ' . $prefix); continue; } if (!is_int($key)) { $value = $this->valueToString($item); if (!is_null($value)) { $output->writeln($prefix . $key . ': ' . $value); } else { $output->writeln($prefix . $key); } } else { $output->writeln($prefix . $this->valueToString($item)); } } break; } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->output = $output; $this->client = $client = SnsClient::factory(array('key' => $this->getContainer()->getParameter('amazon_s3.key'), 'secret' => $this->getContainer()->getParameter('amazon_s3.secret'), 'region' => $this->getContainer()->getParameter('amazon_s3.region'))); if ($input->getOption('list-android')) { $this->showEndpoints($this->getContainer()->getParameter('amazon_sns.android_arn'), 'List of GCM endpoints:'); } if ($input->getOption('list-ios')) { $this->showEndpoints($this->getContainer()->getParameter('amazon_sns.ios_arn'), 'List of APNS endpoints:'); } $endpoint = $input->getArgument('endpoint'); if ($endpoint) { if ($input->getOption('delete')) { $output->writeln('<comment>Delete endpoint</comment>'); $client->deleteEndpoint(array('EndpointArn' => $endpoint)); } else { $testMessage = 'Test notification'; try { $client->publish(array('TargetArn' => $endpoint, 'MessageStructure' => 'json', 'Message' => json_encode(array('APNS' => json_encode(array('aps' => array('alert' => $testMessage))), 'GCM' => json_encode(array('data' => array('message' => $testMessage))))))); } catch (\Aws\Sns\Exception\SnsException $e) { $output->writeln("<error>{$e->getMessage()}</error>"); } } } }
/** * @param \Symfony\Component\Console\Output\OutputInterface $output * @param array $files * @param $permission * @return int */ public function createFolders(\Symfony\Component\Console\Output\OutputInterface $output, $files, $permission) { $dryRun = $this->getConfigurationHelper()->getDryRun(); if (empty($files)) { $output->writeln('<comment>No files found.</comment>'); return 0; } $fs = new Filesystem(); try { if ($dryRun) { $output->writeln("<comment>Folders to be created with permission " . decoct($permission) . ":</comment>"); foreach ($files as $file) { $output->writeln($file); } } else { $output->writeln("<comment>Creating folders with permission " . decoct($permission) . ":</comment>"); foreach ($files as $file) { $output->writeln($file); } $fs->mkdir($files, $permission); } } catch (IOException $e) { echo "\n An error occurred while removing the directory: " . $e->getMessage() . "\n "; } }
protected function execute(InputInterface $input, OutputInterface $output) { foreach ($this->dropOrder as $option) { if ($input->getOption($option)) { $drop[] = $option; } } // Default to the full drop order if no options were specified $drop = empty($drop) ? $this->dropOrder : $drop; $class = $input->getOption('class'); $sm = $this->getSchemaManager(); $isErrored = false; foreach ($drop as $option) { try { if (isset($class)) { $this->{'processDocument' . ucfirst($option)}($sm, $class); } else { $this->{'process' . ucfirst($option)}($sm); } $output->writeln(sprintf('Dropped <comment>%s%s</comment> for <info>%s</info>', $option, isset($class) ? self::INDEX === $option ? '(es)' : '' : (self::INDEX === $option ? 'es' : 's'), isset($class) ? $class : 'all classes')); } catch (\Exception $e) { $output->writeln('<error>' . $e->getMessage() . '</error>'); $isErrored = true; } } return $isErrored ? 255 : 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $this->em = $this->getContainer()->get('doctrine')->getEntityManager(); $this->output = $output; $supported_locales = $this->getContainer()->getParameter('supported_locales'); $default_locale = $this->getContainer()->getParameter('locale'); $locales = $input->getOption('locale'); if (empty($locales)) { $locales = $supported_locales; } $path = $input->getArgument('path'); if (substr($path, -1) === '/') { $path = substr($path, 0, strlen($path) - 1); } $things = ['faction', 'type', 'cycle', 'pack']; foreach ($locales as $locale) { if ($locale === $default_locale) { continue; } $output->writeln("Importing translations for <info>{$locale}</info>"); foreach ($things as $thing) { $output->writeln("Importing translations for <info>{$thing}s</info> in <info>{$locale}</info>"); $fileInfo = $this->getFileInfo("{$path}/translations/{$locale}", "{$thing}s.json"); $this->importThingsJsonFile($fileInfo, $locale, $thing); } $this->em->flush(); $fileSystemIterator = $this->getFileSystemIterator("{$path}/translations/{$locale}"); $output->writeln("Importing translations for <info>cards</info> in <info>{$locale}</info>"); foreach ($fileSystemIterator as $fileInfo) { $output->writeln("Importing translations for <info>cards</info> from <info>" . $fileInfo->getFilename() . "</info>"); $this->importCardsJsonFile($fileInfo, $locale); } $this->em->flush(); } }
protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get('doctrine')->getManager(); $scheduler = $this->getContainer()->get('scheduler'); $subject = $input->getArgument('subject'); $template = $input->getArgument('template'); $campaignId = $input->getArgument('campaignId'); $deliveryTime = new \DateTime($input->getArgument('deliverytime')); $date = $input->getArgument('date'); // The date at which the job is to be run $dateParts = explode('-', $date); if (!checkdate($dateParts[1], $dateParts[2], $dateParts[0])) { $output->writeLn("<error>Invalid date or format. Correct format is Y-m-d</error>"); return; } $now = new \DateTime(); $output->writeln("<comment>Scheduling announcement email started on {$now->format('Y-m-d H:i:s')}</comment>"); // Get All Users $qb = $em->createQueryBuilder(); $qb->add('select', 'u.id')->add('from', 'ClassCentralSiteBundle:User u')->join('u.userPreferences', 'up')->andWhere("up.value = 1")->andWhere("up.type=" . UserPreference::USER_PREFERENCE_FOLLOW_UP_EMAILs); $users = $qb->getQuery()->getArrayResult(); $scheduled = 0; foreach ($users as $user) { $id = $scheduler->schedule(new \DateTime($date), AnnouncementEmailJob::ANNOUNCEMENT_EMAIL_JOB_TYPE, 'ClassCentral\\MOOCTrackerBundle\\Job\\AnnouncementEmailJob', array('template' => $template, 'subject' => $subject, 'campaignId' => $campaignId, 'deliveryTime' => $deliveryTime->format(\DateTime::RFC2822)), $user['id']); if ($id) { $scheduled++; } } $output->writeln("<info>{$scheduled} jobs scheduled</info>"); }