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); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $class_name = ltrim($input->getArgument('class_name'), '\\'); $namespace_root = $input->getArgument('namespace_root_path'); $match = []; preg_match('/([a-zA-Z0-9_]+\\\\[a-zA-Z0-9_]+)\\\\(.+)/', $class_name, $match); if ($match) { $root_namespace = $match[1]; $rest_fqcn = $match[2]; $proxy_filename = $namespace_root . '/ProxyClass/' . str_replace('\\', '/', $rest_fqcn) . '.php'; $proxy_class_name = $root_namespace . '\\ProxyClass\\' . $rest_fqcn; $proxy_class_string = $this->proxyBuilder->build($class_name); $file_string = <<<EOF <?php // @codingStandardsIgnoreFile /** * This file was generated via php core/scripts/generate-proxy-class.php '{$class_name}' "{$namespace_root}". */ {{ proxy_class_string }} EOF; $file_string = str_replace(['{{ proxy_class_name }}', '{{ proxy_class_string }}'], [$proxy_class_name, $proxy_class_string], $file_string); mkdir(dirname($proxy_filename), 0775, TRUE); file_put_contents($proxy_filename, $file_string); $output->writeln(sprintf('Proxy of class %s written to %s', $class_name, $proxy_filename)); } }
public function execute(InputInterface $input, OutputInterface $output) { $username = $input->getArgument('userId'); $password = $input->getArgument('password'); $workspaceName = $input->getArgument('workspaceName'); $this->get('phpcr.session_manager')->relogin($username, $password, $workspaceName); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getHelper('em')->getEntityManager(); $entityClass = $input->getArgument('entity-class'); $entityId = $input->getArgument('entity-id'); $cache = $em->getCache(); if (!$cache instanceof Cache) { throw new \InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); } if (!$entityClass && !$input->getOption('all')) { throw new \InvalidArgumentException('Invalid argument "--entity-class"'); } if ($input->getOption('flush')) { $entityRegion = $cache->getEntityCacheRegion($entityClass); if (!$entityRegion instanceof DefaultRegion) { throw new \InvalidArgumentException(sprintf('The option "--flush" expects a "Doctrine\\ORM\\Cache\\Region\\DefaultRegion", but got "%s".', is_object($entityRegion) ? get_class($entityRegion) : gettype($entityRegion))); } $entityRegion->getCache()->flushAll(); $output->writeln(sprintf('Flushing cache provider configured for entity named <info>"%s"</info>', $entityClass)); return; } if ($input->getOption('all')) { $output->writeln('Clearing <info>all</info> second-level cache entity regions'); $cache->evictEntityRegions(); return; } if ($entityId) { $output->writeln(sprintf('Clearing second-level cache entry for entity <info>"%s"</info> identified by <info>"%s"</info>', $entityClass, $entityId)); $cache->evictEntity($entityClass, $entityId); return; } $output->writeln(sprintf('Clearing second-level cache for entity <info>"%s"</info>', $entityClass)); $cache->evictEntityRegion($entityClass); }
/** * @see Command * @see SecurityChecker */ protected function execute(InputInterface $input, OutputInterface $output) { if ($endPoint = $input->getOption('end-point')) { $this->checker->getCrawler()->setEndPoint($endPoint); } if ($timeout = $input->getOption('timeout')) { $this->checker->getCrawler()->setTimeout($timeout); } try { $vulnerabilities = $this->checker->check($input->getArgument('lockfile')); } catch (ExceptionInterface $e) { $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($e->getMessage(), 'error', true)); return 1; } switch ($input->getOption('format')) { case 'json': $formatter = new JsonFormatter(); break; case 'simple': $formatter = new SimpleFormatter($this->getHelperSet()->get('formatter')); break; case 'text': default: $formatter = new TextFormatter($this->getHelperSet()->get('formatter')); } $formatter->displayResults($output, $input->getArgument('lockfile'), $vulnerabilities); if ($this->checker->getLastVulnerabilityCount() > 0) { return 1; } }
protected function execute(InputInterface $input, OutputInterface $output) { $masterLanguage = $input->getArgument('master'); $slaveLanguage = $input->getArgument('slave'); $masterLanguageFile = $this->path . 'messages.' . $masterLanguage . '.yml'; $slaveLanguageFile = $this->path . 'messages.' . $slaveLanguage . '.yml'; $catMasterFile = $this->loader->load($masterLanguageFile, $masterLanguage); $catSlaveFile = $this->loader->load($slaveLanguageFile, $slaveLanguage); foreach ($catMasterFile->all('messages') as $key => $value) { if (!$catSlaveFile->has($key)) { $catSlaveFile->set($key, "TODO: {$value}"); } } $messages = $catMasterFile->all('messages'); ksort($messages); $catSlaveFile->replace($messages); foreach ($messages as $key => $value) { $catSlaveFile->set($key, $value); } $output->writeln('Slave file can modify'); $dumper = new YamlFileDumper(); $dumper->dump($catSlaveFile, array('path' => $this->path)); /*unlink created trash file*/ if (file_exists($slaveLanguageFile . '~')) { unlink($slaveLanguageFile . '~'); } $output->writeln($slaveLanguageFile . ' --> <info>Slave file updated</info>'); }
protected function execute(InputInterface $input, OutputInterface $output) { # MVC object $mvc = MVCStore::retrieve('mvc'); if ($input->getArgument('folder') == 'web') { $input->setArgument('folder', dirname($mvc->getAppDir()) . '/web'); } $folderArg = rtrim($input->getArgument('folder'), '/'); if (!is_dir($folderArg)) { throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('folder'))); } $modulesPath = $folderArg . '/modules/'; @mkdir($modulesPath); if ($input->getOption('symlinks')) { $output->writeln('Trying to install assets as <comment>symbolic links</comment>.'); } else { $output->writeln('Installing assets as <comment>hard copies</comment>.'); } foreach ($mvc->getModules() as $module) { if (is_dir($originDir = $module->getPath() . '/Resources/public')) { $targetDir = $modulesPath . preg_replace('/module$/', '', strtolower($module->getName())); $output->writeln(sprintf('Installing assets for <comment>%s</comment> into <comment>%s</comment>', $module->getNamespace(), $targetDir)); if (!$this->recursiveRemoveDir($targetDir)) { $output->writeln(sprintf('Could\'t been removed the dir "%s".', $targetDir)); } if ($input->getOption('symlinks')) { #link($originDir, $targetDir); @symlink($originDir, $targetDir); } else { $this->resourceCopy($originDir, $targetDir); } } } }
/** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $client = new Client(); $modname = $input->getArgument('modname'); $modversion = $input->getArgument('modversion'); $config = solder_config(); $response = $client->get($config->api); $server = $response->json(); $response = $client->get($config->api . '/mod/' . $modname . '/' . $modversion); $json = $response->json(); if (isset($json['error'])) { throw new \Exception($json['error']); } $rows = array(); foreach ($json as $key => $value) { if ($key == 'versions') { $rows[] = array("<info>{$key}</info>", implode($value, "\n")); } else { $rows[] = array("<info>{$key}</info>", mb_strimwidth($value, 0, 80, "...")); } } $output->writeln('<comment>Server:</comment>'); $output->writeln(" <info>{$server['api']}</info> version {$server['version']}"); $output->writeln(" {$api}"); $output->writeln(''); $output->writeln("<comment>Mod:</comment>"); $table = new Table($output); $table->setRows($rows)->setStyle('compact')->render(); }
protected function execute(InputInterface $input, OutputInterface $output) { $dateTime = new \DateTime($input->getArgument('date')); $event = new TicketEvent($input->getArgument('from'), $input->getArgument('to'), $dateTime); $salePerson = $this->getContainer()->get('sale'); $salePerson->checkAvailableTicket($event); }
protected function execute(InputInterface $input, OutputInterface $output) { $login = $input->getArgument("login"); $helper = $this->getHelper('question'); $question = new Question("Unix password for « {$login} » : "); $question->setHidden(true); $question->setHiddenFallback(false); $password = $input->getArgument("password") ? $input->getArgument("password") : $helper->ask($input, $output, $question); $blih = new Blih($login, $password); $blihRepositoriesResponse = $blih->repository()->all(); if ($blihRepositoriesResponse->code == 200) { $user = $this->getUserOrCreateIt($login); $repositoryNames = array_keys(get_object_vars($blihRepositoriesResponse->body->repositories)); foreach ($repositoryNames as $repositoryName) { $output->writeln("> Repository « {$login}/{$repositoryName} »"); $repository = $this->getRepoOrCreateIt($user, $repositoryName); $aclResponse = $blih->repository($repositoryName)->acl()->get(); if ($aclResponse->code == 200) { $acls = get_object_vars($aclResponse->body); foreach ($acls as $aclLogin => $acl) { $output->writeln(" ACL for « {$aclLogin} »: {$acl}"); $aclUser = $this->getUserOrCreateIt($aclLogin); $repositoryACL = $this->getACLOrCreateIt($aclUser, $repository); $repositoryACL->setR(strpos($acl, "r") !== false); $repositoryACL->setW(strpos($acl, "w") !== false); $repositoryACL->setA(strpos($acl, "a") !== false); $this->getContainer()->get("doctrine")->getManager()->persist($repositoryACL); } } $output->writeln(""); $this->getContainer()->get("doctrine")->getManager()->persist($repository); $this->getContainer()->get("doctrine")->getManager()->flush(); } } }
/** * @param InputInterface $input * @param string $file * @return int */ protected function extractArguments(InputInterface $input, &$file) { $file = $input->getArgument('path'); $count = $input->getArgument('includeFirstLine'); $counter = null === $count ? 0 : 1; return $counter; }
protected function askPassword(InputInterface $input, OutputInterface $output, $encoder, $properties) { $encoder = $this->createEncoder($properties); $dialog = $this->getHelperSet()->get('dialog'); $verified = true; do { if ($verified === false) { $output->writeln("<error>Passwords are not the same.</error>"); } if ($input->getArgument('password')) { $password = $input->getArgument('password'); } else { $password = $dialog->askHiddenResponse($output, "<question>Password:</question> "); if ($input->getOption('check-password')) { $repeat = $dialog->askHiddenResponse($output, "<question>Repeat password:</question> "); $verified = $repeat === $password; } } } while ($verified === false); if ($input->getOption('ask-salt')) { $salt = $dialog->ask($output, "<question>Salt:</question> "); } else { $salt = hash('sha256', $this->getSecureRandom()->nextBytes(32)); $output->writeln("<info>A salt was generated for you:</info>"); $output->writeln($salt); } $output->writeln("<info>The hashed password:</info>"); $output->writeln($encoder->encodePassword($password, 'blurp')); }
/** * {@inheritdoc} * * @throws \InvalidArgumentException When the target directory does not exist or symlink cannot be used */ protected function execute(InputInterface $input, OutputInterface $output) { $targetArg = rtrim($input->getArgument('target'), '/'); if (!is_dir($targetArg)) { throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target'))); } if (!function_exists('symlink') && $input->getOption('symlink')) { throw new \InvalidArgumentException('The symlink() function is not available on your system. You need to install the assets without the --symlink option.'); } $filesystem = $this->getContainer()->get('filesystem'); // Create the bundles directory otherwise symlink will fail. $bundlesDir = $targetArg . '/bundles/'; $filesystem->mkdir($bundlesDir, 0777); $output->writeln(sprintf('Installing assets using the <comment>%s</comment> option', $input->getOption('symlink') ? 'symlink' : 'hard copy')); foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) { if (is_dir($originDir = $bundle->getPath() . '/Resources/public')) { $targetDir = $bundlesDir . preg_replace('/bundle$/', '', strtolower($bundle->getName())); $output->writeln(sprintf('Installing assets for <comment>%s</comment> into <comment>%s</comment>', $bundle->getNamespace(), $targetDir)); $filesystem->remove($targetDir); if ($input->getOption('symlink')) { if ($input->getOption('relative')) { $relativeOriginDir = $filesystem->makePathRelative($originDir, realpath($bundlesDir)); } else { $relativeOriginDir = $originDir; } $filesystem->symlink($relativeOriginDir, $targetDir); } else { $filesystem->mkdir($targetDir, 0777); // We use a custom iterator to ignore VCS files $filesystem->mirror($originDir, $targetDir, Finder::create()->ignoreDotFiles(false)->in($originDir)); } } } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $configName = $input->getArgument('config-name'); $editor = $input->getArgument('editor'); $config = $this->getConfigFactory()->getEditable($configName); $configSystem = $this->getConfigFactory()->get('system.file'); $temporalyDirectory = $configSystem->get('path.temporary') ?: '/tmp'; $configFile = $temporalyDirectory . '/config-edit/' . $configName . '.yml'; $ymlFile = new Parser(); $fileSystem = new Filesystem(); try { $fileSystem->mkdir($temporalyDirectory); $fileSystem->dumpFile($configFile, $this->getYamlConfig($configName)); } catch (IOExceptionInterface $e) { throw new \Exception($this->trans('commands.config.edit.messages.no-directory') . ' ' . $e->getPath()); } if (!$editor) { $editor = $this->getEditor(); } $processBuilder = new ProcessBuilder(array($editor, $configFile)); $process = $processBuilder->getProcess(); $process->setTty('true'); $process->run(); if ($process->isSuccessful()) { $value = $ymlFile->parse(file_get_contents($configFile)); $config->setData($value); $config->save(); $fileSystem->remove($configFile); } if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getHelper('em')->getEntityManager(); $metadatas = $em->getMetadataFactory()->getAllMetadata(); $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter')); $repositoryName = $em->getConfiguration()->getDefaultRepositoryClassName(); // Process destination directory $destPath = realpath($input->getArgument('dest-path')); if (!file_exists($destPath)) { throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not exist.", $input->getArgument('dest-path'))); } if (!is_writable($destPath)) { throw new \InvalidArgumentException(sprintf("Entities destination directory '<info>%s</info>' does not have write permissions.", $destPath)); } if (count($metadatas)) { $numRepositories = 0; $generator = new EntityRepositoryGenerator(); $generator->setDefaultRepositoryName($repositoryName); foreach ($metadatas as $metadata) { if ($metadata->customRepositoryClassName) { $output->writeln(sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName)); $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destPath); $numRepositories++; } } if ($numRepositories) { // Outputting information message $output->writeln(PHP_EOL . sprintf('Repository classes generated to "<info>%s</INFO>"', $destPath)); } else { $output->writeln('No Repository classes were found to be processed.'); } } else { $output->writeln('No Metadata Classes to process.'); } }
/** * @see \Symfony\Component\Console\Command\Command::execute() */ protected function execute(InputInterface $input, OutputInterface $output) { $key = $input->getArgument('key'); $value = $input->getArgument('value'); if ($input->getOption('backup')) { $backup = true; } else { $backup = false; } if ($input->getOption('file')) { $file = $input->getOption('file'); } else { $file = 'config.yml'; } try { $yaml = new YamlUpdater($this->app, $file); if ($yaml->change($key, $value, $backup)) { $result = sprintf("New value for <info>%s: %s</info> was successful. File updated.", $key, $value); } else { $result = sprintf("<error>The key '%s' was not found in %s.</error>", $key, $file); } } catch (FileNotFoundException $e) { $result = sprintf("<error>Can't read file: %s.</error>", $file); } catch (ParseException $e) { $result = sprintf("<error>Invalid YAML in file: %s.</error>", $file); } catch (FilesystemException $e) { $result = sprintf('<error>' . $e->getMessage() . '</error>'); } $this->auditLog(__CLASS__, "Config value '{$key}: {$value}' set"); $output->writeln($result); }
public function execute(InputInterface $input, OutputInterface $output) { $suite = $input->getArgument('suite'); $step = $input->getArgument('step'); $config = $this->getSuiteConfig($suite, $input->getOption('config')); $class = $this->getClassName($step); $path = $this->buildPath(Configuration::supportDir() . 'Step' . DIRECTORY_SEPARATOR . ucfirst($suite), $step); $dialog = $this->getHelperSet()->get('question'); $filename = $path . $class . '.php'; $helper = $this->getHelper('question'); $question = new Question("Add action to StepObject class (ENTER to exit): "); $gen = new StepObjectGenerator($config, ucfirst($suite) . '\\' . $step); if (!$input->getOption('silent')) { do { $question = new Question('Add action to StepObject class (ENTER to exit): ', null); $action = $dialog->ask($input, $output, $question); if ($action) { $gen->createAction($action); } } while ($action); } $res = $this->save($filename, $gen->produce()); if (!$res) { $output->writeln("<error>StepObject {$filename} already exists</error>"); exit; } $output->writeln("<info>StepObject was created in {$filename}</info>"); }
protected function execute(InputInterface $input, OutputInterface $output) { if (!filter_var($input->getArgument("url"), FILTER_VALIDATE_URL)) { throw new \Exception(sprintf("'%s' does not look like a valid url", $input->getArgument("url"))); } $output->write($this->formatter->format($this->dataProvider->scrape($input->getArgument("url")))); }
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) { $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) { $command = $input->getArgument('cmd'); $params = json_decode($input->getArgument('params'), true); // Create new job /** @var JobFactory $jobFactory */ $jobFactory = $this->getContainer()->get('syrup.job_factory'); $jobFactory->setStorageApiClient($this->storageApi); $job = $jobFactory->create($command, $params); // Add job to Elasticsearch /** @var JobMapper $jobMapper */ $jobMapper = $this->getContainer()->get('syrup.elasticsearch.current_component_job_mapper'); $jobId = $jobMapper->create($job); $output->writeln('Created job id ' . $jobId); // Run Job if ($input->getOption('run')) { $runJobCommand = $this->getApplication()->find('syrup:run-job'); $returnCode = $runJobCommand->run(new ArrayInput(['command' => 'syrup:run-job', 'jobId' => $jobId]), $output); if ($returnCode == 0) { $output->writeln('Job successfully executed'); } elseif ($returnCode == 2 || $returnCode == 64) { $output->writeln('DB is locked. Run job later using syrup:run-job'); } else { $output->writeln('Error occured'); } } return 0; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { try { echo "Making a go at starting a Thruway worker.\n"; $name = $input->getArgument('name'); $config = $this->getContainer()->getParameter('voryx_thruway'); $loop = $this->getContainer()->get('voryx.thruway.loop'); $kernel = $this->getContainer()->get('wamp_kernel'); $workerAnnotation = $kernel->getResourceMapper()->getWorkerAnnotation($name); if ($workerAnnotation) { $realm = $workerAnnotation->getRealm() ?: $config['realm']; $url = $workerAnnotation->getUrl() ?: $config['url']; } else { $realm = $config['realm']; $url = $config['url']; } $transport = new PawlTransportProvider($url); $client = new Client($realm, $loop); $client->addTransportProvider($transport); $kernel->setProcessName($name); $kernel->setClient($client); $kernel->setProcessInstance($input->getArgument('instance')); $client->start(); } catch (\Exception $e) { $logger = $this->getContainer()->get('logger'); $logger->addCritical("EXCEPTION:" . $e->getMessage()); $output->writeln("EXCEPTION:" . $e->getMessage()); } }
/** * @see Console\Command\Command */ protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $dm = $this->getHelper('dm')->getDocumentManager(); $query = json_decode($input->getArgument('query')); $cursor = $dm->getRepository($input->getArgument('class'))->findBy((array) $query); $cursor->hydrate((bool) $input->getOption('hydrate')); $depth = $input->getOption('depth'); if (!is_numeric($depth)) { throw new \LogicException("Option 'depth' must contain an integer value"); } if (($skip = $input->getOption('skip')) !== null) { if (!is_numeric($skip)) { throw new \LogicException("Option 'skip' must contain an integer value"); } $cursor->skip((int) $skip); } if (($limit = $input->getOption('limit')) !== null) { if (!is_numeric($limit)) { throw new \LogicException("Option 'limit' must contain an integer value"); } $cursor->limit((int) $limit); } $resultSet = $cursor->toArray(); \Doctrine\Common\Util\Debug::dump($resultSet, $depth); }
protected function execute(InputInterface $input, OutputInterface $output) { $rc = 0; $default_environment = \Config::getEnvironment(); $environment = $input->getOption('environment') ?: $default_environment; $file_system = new Filesystem(); $file_loader = new FileLoader($file_system); if ($input->getOption('generated-overrides')) { $file_saver = new FileSaver($file_system, $environment == $default_environment ? null : $environment); } else { $file_saver = new DirectFileSaver($file_system, $environment == $default_environment ? null : $environment); } $this->repository = new Repository($file_loader, $file_saver, $environment); try { $item = $input->getArgument('item'); switch ($input->getArgument('operation')) { case self::OPERATION_GET: $output->writeln($this->serialize($this->repository->get($item))); break; case self::OPERATION_SET: $value = $input->getArgument('value'); if (!isset($value)) { throw new Exception('Missing new configuration value'); } $this->repository->save($item, $this->unserialize($value)); break; default: throw new Exception('Invalid operation specified. Allowed operations: ' . implode(', ', $this->getAllowedOperations())); } } catch (Exception $x) { $output->writeln('<error>' . $x->getMessage() . '</error>'); $rc = 1; } return $rc; }
protected function execute(InputInterface $input, OutputInterface $output) { $profileName = $input->getArgument('profile'); $repository = $input->getArgument('repository'); $force = $input->getOption('force'); $profile = \Tiki_Profile::fromNames($repository, $profileName); if (!$profile) { $output->writeln('<error>Profile not found.</error>'); return; } $tikilib = \TikiLib::lib('tiki'); $installer = new \Tiki_Profile_Installer(); $isInstalled = $installer->isInstalled($profile); if ($isInstalled && $force) { $installer->forget($profile); $isInstalled = false; } if (!$isInstalled) { $transaction = $tikilib->begin(); if ($installer->install($profile)) { $transaction->commit(); $output->writeln('Profile applied.'); } else { $output->writeln("<error>Installation failed:</error>"); foreach ($installer->getFeedback() as $error) { $output->writeln("<error>{$error}</error>"); } } } else { $output->writeln('<info>Profile was already applied. Nothing happened.</info>'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine')); try { $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name')); $output->writeln(sprintf('Clearing entities for bundle "<info>%s</info>"', $bundle->getName())); $metadata = $manager->getBundleMetadata($bundle); } catch (\InvalidArgumentException $e) { $name = strtr($input->getArgument('name'), '/', '\\'); if (false !== ($pos = strpos($name, ':'))) { $name = $this->getContainer()->get('doctrine')->getAliasNamespace(substr($name, 0, $pos)) . '\\' . substr($name, $pos + 1); } if (class_exists($name)) { $output->writeln(sprintf('Fixing entity "<info>%s</info>"', $name)); $metadata = $manager->getClassMetadata($name, $input->getOption('path')); } else { $output->writeln(sprintf('Fixing entities for namespace "<info>%s</info>"', $name)); $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path')); } } foreach ($metadata->getMetadata() as $m) { // Getting the metadata for the entity class once more to get the correct path if the namespace has multiple occurrences try { $entityMetadata = $manager->getClassMetadata($m->getName(), $input->getOption('path')); } catch (\RuntimeException $e) { // fall back to the bundle metadata when no entity class could be found $entityMetadata = $metadata; } $output->writeln(sprintf(' > fixing <comment>%s</comment>', $m->name)); $res = $this->fixEntity($m, $entityMetadata->getPath()); if (!$res) { $output->writeln(sprintf('> FAILED')); } } }
protected function execute(InputInterface $input, OutputInterface $output) { $magento = new Magento($input->getOption('magento-root')); $config_adapter = new ConfigurationAdapter($magento); $yaml = new Parser(); if ($input->getArgument('config-yaml-file')) { $config_yaml_file = $input->getArgument('config-yaml-file'); if (!file_exists($config_yaml_file)) { throw new \Exception("File ({$config_yaml_file}) does not exist"); } if (!is_readable($config_yaml_file)) { throw new \Exception("File ({$config_yaml_file}) is not readable"); } $config_db_yaml = ConfigYaml::build($config_adapter); $config_file_contents = $yaml->parse(file_get_contents($config_yaml_file)); $config_file_yaml = new ConfigYaml($config_file_contents, $input->getOption('env')); $diff = ConfigYaml::compare($config_file_yaml, $config_db_yaml); if (count($diff) > 0) { $db_data = $config_db_yaml->getData(); $file_data = $config_file_yaml->getData(); $diff_count = 0; foreach ($diff as $scope => $scope_data) { foreach ($scope_data as $key => $value) { $diff_count++; $diff_message = sprintf("%s/%s is different (File: %s, DB: %s)", $scope, $key, $this->decorateValue($file_data[$scope][$key]), $this->decorateValue($db_data[$scope][$key])); $output->writeln($diff_message); } } return $diff_count; } else { return 0; } } }
/** * @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>"); } } }
protected function execute(InputInterface $input, OutputInterface $output) { if ($input->getOption('list')) { $this->listImport($output); return; } $importRef = $input->getArgument('ref'); $path = $input->getArgument('filePath'); if ($importRef === null || $path === null) { throw new \RuntimeException('Not enough arguments.' . PHP_EOL . 'If no options are provided, ref and filePath arguments are required.'); } /** @var \Thelia\Handler\ImportHandler $importHandler */ $importHandler = $this->getContainer()->get('thelia.import.handler'); $import = $importHandler->getImportByRef($importRef); if ($import === null) { throw new \RuntimeException($importRef . ' import doesn\'t exist.'); } $importEvent = $importHandler->import($import, new File($input->getArgument('filePath')), (new LangQuery())->findOneByLocale($input->getOption('locale'))); $formattedLine = $this->getHelper('formatter')->formatBlock('Successfully import ' . $importEvent->getImport()->getImportedRows() . ' row(s)', 'fg=black;bg=green', true); $output->writeln($formattedLine); if (count($importEvent->getErrors()) > 0) { $formattedLine = $this->getHelper('formatter')->formatBlock('With error', 'fg=black;bg=yellow', true); $output->writeln($formattedLine); foreach ($importEvent->getErrors() as $error) { $output->writeln('<comment>' . $error . '</comment>'); } } }
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>"); }