/**
  * Import Projects
  */
 private function importProjects()
 {
     $this->output->write(sprintf('%-30s', 'Importing projects'));
     $previewProjects = $this->previewService->getProjects();
     $created = 0;
     $updated = 0;
     foreach ($previewProjects as $previewProject) {
         /**
          * @var Project $project
          */
         $project = $this->entityManager->getRepository('ProjectPreviewProjectBundle:Project')->find($previewProject->id);
         if (is_null($project)) {
             $project = new Project();
             $project->setId($previewProject->id);
             $created++;
         } else {
             $updated++;
         }
         $project->setName($previewProject->name);
         $project->setArchived($previewProject->archived);
         $this->entityManager->persist($project);
     }
     $this->output->writeln(sprintf('done (total: % 4d, created: % 4d, updated: % 4d)', $created + $updated, $created, $updated));
     $this->entityManager->flush();
 }
 /**
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $dm = $this->getHelper('documentManager')->getDocumentManager();
     $metadatas = $dm->getMetadataFactory()->getAllMetadata();
     $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter'));
     // Process destination directory
     if (($destPath = $input->getArgument('dest-path')) === null) {
         $destPath = $dm->getConfiguration()->getProxyDir();
     }
     if (!is_dir($destPath)) {
         mkdir($destPath, 0775, true);
     }
     $destPath = realpath($destPath);
     if (!file_exists($destPath)) {
         throw new \InvalidArgumentException(sprintf("Proxies destination directory '<info>%s</info>' does not exist.", $destPath));
     } elseif (!is_writable($destPath)) {
         throw new \InvalidArgumentException(sprintf("Proxies destination directory '<info>%s</info>' does not have write permissions.", $destPath));
     }
     if (count($metadatas)) {
         foreach ($metadatas as $metadata) {
             $output->write(sprintf('Processing document "<info>%s</info>"', $metadata->name) . PHP_EOL);
         }
         // Generating Proxies
         $dm->getProxyFactory()->generateProxyClasses($metadatas, $destPath);
         // Outputting information message
         $output->write(PHP_EOL . sprintf('Proxy classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
 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]');
     }
 }
Example #4
0
 /**
  * Displays a security report as plain text.
  *
  * @param OutputInterface $output
  * @param string          $lockFilePath    The file path to the checked lock file
  * @param array           $vulnerabilities An array of vulnerabilities
  */
 public function displayResults(OutputInterface $output, $lockFilePath, array $vulnerabilities)
 {
     $output->writeln("\n<fg=blue>Security Check Report\n~~~~~~~~~~~~~~~~~~~~~</>\n");
     $output->writeln(sprintf('Checked file: <comment>%s</>', realpath($lockFilePath)));
     $output->write("\n");
     if ($count = count($vulnerabilities)) {
         $status = 'CRITICAL';
         $style = 'error';
     } else {
         $status = 'OK';
         $style = 'bg=green;fg=white';
     }
     $output->writeln($this->formatter->formatBlock(array('[' . $status . ']', $count . ' packages have known vulnerabilities'), $style, true));
     $output->write("\n");
     if (0 !== $count) {
         foreach ($vulnerabilities as $dependency => $issues) {
             $dependencyFullName = $dependency . ' (' . $issues['version'] . ')';
             $output->writeln('<info>' . $dependencyFullName . "\n" . str_repeat('-', strlen($dependencyFullName)) . "</>\n");
             foreach ($issues['advisories'] as $issue => $details) {
                 $output->write(' * ');
                 if ($details['cve']) {
                     $output->write('<comment>' . $details['cve'] . ': </comment>');
                 }
                 $output->writeln($details['title']);
                 if ('' !== $details['link']) {
                     $output->writeln('   ' . $details['link']);
                 }
                 $output->writeln('');
             }
         }
     }
     $output->writeln("<bg=yellow;fg=white>            </> This checker can only detect vulnerabilities that are referenced");
     $output->writeln("<bg=yellow;fg=white> Disclaimer </> in the SensioLabs security advisories database. Execute this");
     $output->writeln("<bg=yellow;fg=white>            </> command regularly to check the newly discovered vulnerabilities.\n");
 }
 /**
  * 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;
 }
Example #6
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @throws \RuntimeException
  * @throws \InvalidArgumentException
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var ResourceHelper $helper */
     $helper = $this->getHelper('resource');
     $ryzomDataPath = $input->getOption('ryzom');
     if (empty($ryzomDataPath) || !file_exists($ryzomDataPath . '/gamedev.bnp') || !file_exists($ryzomDataPath . '/lmconts.packed') || !file_exists($ryzomDataPath . '/world.packed_sheets')) {
         throw new \InvalidArgumentException("Invalid Ryzom data path. gamedev.bnp, lmconts.packed or world.packed_sheets not found");
     }
     $psLoader = new PackedSheetsLoader($ryzomDataPath);
     // labels.json
     $output->write('<info>building labels.json</info>...');
     /** @var TranslateHelper $translator */
     $translator = $this->getHelper('translator');
     /** @var StringsManager $sm */
     $sm = $translator->load($ryzomDataPath);
     $lmconts = $psLoader->load('lmconts');
     $continents = $lmconts->get('continents');
     $this->buildLabels($continents, $sm, $helper->get('labels.json.file'));
     $output->writeln('');
     // server.json
     $output->write('<info>building server.json</info>...');
     $ps = $psLoader->load('world');
     // 6 == sheetid for 'ryzom.world'
     $world = $ps->get(6);
     if (!$world) {
         throw new \RuntimeException("Failed to load world.packed_sheets");
     }
     $this->buildServerZones($world, $helper->get('server.json.file'));
     $output->writeln('');
 }
Example #7
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $only_chekc = $input->getOption('only-check');
     if (file_exists('composer.phar')) {
         if ($only_chekc) {
             $output->writeln('<info>Composer installed</info>');
             return 0;
         }
         $output->write('Composer already installed, upgrading it...');
         exec('php composer.phar selfupdate', $res, $ret);
         if ($ret == 0) {
             $output->writeln('<info>DONE</info>');
         } else {
             $output->writeln('<error>ERROR</error>');
             return 1;
         }
     } else {
         if ($only_chekc) {
             $output->writeln('<error>Composer not installed</error>');
             return 1;
         }
         $output->write('Installing composer...');
         exec('php -r "readfile(\'https://getcomposer.org/installer\');" | php', $res, $ret);
         if ($ret == 0) {
             $output->writeln('<info>DONE</info>');
             return 0;
         } else {
             $output->writeln('<error>ERROR - please install composer manually (https://getcomposer.org/download/)</error>');
             return 1;
         }
     }
 }
Example #8
0
 /** flush printer buffer */
 public function flush()
 {
     fseek($this->stream, 0);
     $this->output->write(stream_get_contents($this->stream));
     fclose($this->stream);
     $this->initStream();
 }
Example #9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $fileInfo = new \SplFileInfo($this->getContainer()->getParameter('kernel.root_dir') . '/../web/sitemap.xml');
     if ($fileInfo->isFile() && $fileInfo->isReadable()) {
         $output->write('Reading sitemap.xml...');
         $file = $fileInfo->openFile();
         $xml = '';
         while (!$file->eof()) {
             $xml .= $file->fgets();
         }
         $output->writeln(' done.');
         $output->write('Updating sitemap.xml...');
         $sitemap = new \SimpleXMLIterator($xml);
         $sitemap->rewind();
         $lastmodDate = new \DateTime();
         $lastmodDate->sub(new \DateInterval('P1D'));
         $lastmodDateFormatted = $lastmodDate->format('Y-m-d');
         while ($sitemap->valid()) {
             $sitemap->current()->lastmod = $lastmodDateFormatted;
             $sitemap->next();
         }
         $file = $file->openFile('w');
         $file->fwrite($sitemap->asXML());
         $output->writeln(' done.');
     } else {
         $output->writeln('Error: Cannot open file web/sitemap.xml');
     }
 }
Example #10
0
 /**
  * Displays a security report as simple plain text.
  *
  * @param OutputInterface $output
  * @param string          $lockFilePath    The file path to the checked lock file
  * @param array           $vulnerabilities An array of vulnerabilities
  */
 public function displayResults(OutputInterface $output, $lockFilePath, array $vulnerabilities)
 {
     $output->writeln(sprintf('Security Check Report: <comment>%s</>', realpath($lockFilePath)));
     if ($count = count($vulnerabilities)) {
         $status = 'CRITICAL';
         $style = 'error';
     } else {
         $status = 'OK';
         $style = 'info';
     }
     $output->writeln(sprintf('<%s>[%s] %d %s known vulnerabilities</>', $style, $status, $count, 1 === $count ? 'package has' : 'packages have'));
     if (0 !== $count) {
         $output->write("\n");
         foreach ($vulnerabilities as $dependency => $issues) {
             $dependencyFullName = $dependency . ' (' . $issues['version'] . ')';
             $output->writeln('<info>' . $dependencyFullName . "\n" . str_repeat('-', strlen($dependencyFullName)) . "</>\n");
             foreach ($issues['advisories'] as $issue => $details) {
                 $output->write(' * ');
                 if ($details['cve']) {
                     $output->write('<comment>' . $details['cve'] . ': </comment>');
                 }
                 $output->writeln($details['title']);
                 if ('' !== $details['link']) {
                     $output->writeln('   ' . $details['link']);
                 }
                 $output->writeln('');
             }
         }
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $notFound = false;
     $source = $input->getArgument('source');
     $outputPath = $input->getArgument('output');
     $worker = new \MySQLExtractor\Application();
     $scanPathname = realpath($source);
     preg_match('/(.*):(.*)@(.*)\\/(.*)/', $source, $serverDetails);
     if (is_array($serverDetails) && count($serverDetails) === 5) {
         $mysqlCredentials = new \stdClass();
         $mysqlCredentials->dbuser = $serverDetails[1];
         $mysqlCredentials->dbpass = $serverDetails[2];
         $mysqlCredentials->host = $serverDetails[3];
         $mysqlCredentials->dbname = $serverDetails[4];
         $worker->processServer($mysqlCredentials);
     } else {
         if ($scanPathname) {
             $worker->processDisk($scanPathname);
         } else {
             // error, path not found
             $notFound = true;
         }
     }
     if ($notFound) {
         $output->write('Error: invalid source format, check if the source path exists and the format is valid.');
     } else {
         $worker->output($outputPath, $results = $worker->getDatabases());
         // will output .json files for each database
         $output->write('Finished. Check the output folder.' . PHP_EOL . implode(PHP_EOL, $worker->statistics()) . PHP_EOL);
     }
 }
Example #12
0
 /**
  * @SuppressWarnings(PHPMD.ExitExpression)
  * @param \Symfony\Component\Console\Input\InputInterface $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  */
 protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output)
 {
     $entityManager = $this->getHelper('em')->getEntityManager();
     $users = $entityManager->getRepository('\\Jazzee\\Entity\\User')->findAll();
     if (!$users) {
         $output->write('<error>There are no users in the system.  User add-user to create one.</error>' . PHP_EOL);
         exit;
     }
     $find = array('name' => $input->getArgument('role name'));
     if ($input->getOption('global-only')) {
         $find['isGlobal'] = true;
     }
     $roles = $entityManager->getRepository('\\Jazzee\\Entity\\Role')->findBy($find);
     if (count($roles) == 0) {
         $output->write('<error>There are no roles with that name.</error>' . PHP_EOL);
         exit;
     }
     if (!$input->getOption('multiple') and count($roles) > 1) {
         $output->write('<error>There are ' . count($roles) . ' roles with that name.  In order to add users to muliple roles you must use the --multiple option.</error>' . PHP_EOL);
         exit;
     }
     $results = array();
     foreach ($entityManager->getRepository('\\Jazzee\\Entity\\User')->findBy(array(), array('lastName' => 'ASC', 'firstName' => 'ASC')) as $user) {
         foreach ($roles as $role) {
             if (!$user->hasRole($role)) {
                 $user->addRole($role);
                 $results[] = "<info>{$user->getLastName()}, {$user->getFirstName()} added to {$role->getName()} role</info>";
             }
         }
         $entityManager->persist($user);
     }
     $entityManager->flush();
     $output->write(implode(PHP_EOL, $results) . PHP_EOL . '<info>Total of ' . count($results) . ' changes</info>' . PHP_EOL);
 }
 public function execute(MinimumStrictCoverage $minimumStrictCoverage, $errorMessage)
 {
     $outputMessage = new PreCommitOutputWriter(self::EXECUTE_MESSAGE);
     $this->output->write($outputMessage->getMessage());
     $this->strictCoverageTool->run($minimumStrictCoverage, $errorMessage);
     $this->output->writeln($outputMessage->getSuccessfulMessage());
 }
Example #14
0
 /**
  * Parses the clover XML file and spits out coverage results to the console.
  *
  * @param  InputInterface  $input
  * @param  OutputInterface $output
  * @return int
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     // Get options
     $project = $input->getOption('project');
     if ($input->getOption('file')) {
         $file = $input->getOption('file');
     } else {
         $file = '';
     }
     // First step : Analysing config
     $config_path = $input->getArgument('config');
     $guardian = new Guardian($config_path);
     $output->writeln(sprintf('Analysing config file : <info>%s</info>', $config_path));
     $output->write("\n");
     $output->writeln(sprintf('> Start SQL restore : <info>%s</info>', $project));
     $output->writeln('------------------------------');
     try {
         $guardian->restoreDatabase($project, $file);
     } catch (\Exception $e) {
         if ($e->getCode() == 0) {
             $style = 'error';
         } else {
             $style = 'comment';
         }
         $output->write(sprintf(' : <' . $style . '>%s</' . $style . '>', $e->getMessage()));
     }
     $output->write("\n");
     $output->writeln('Finished : <info>Done</info>');
 }
 private function install(OutputInterface $output, $targetFolder, $symlinkName, $forceDownload, HttpSource $source)
 {
     $version = $source->getVersion();
     $extractedFolder = 'PhpStorm-' . $version;
     if (is_dir($targetFolder . '/' . $extractedFolder) && false === $forceDownload) {
         $output->writeln(sprintf('<comment>Phpstorm <info>%s</info> already exists, skipping download..</comment>', $version));
     } else {
         $output->write(sprintf('<comment>Download %s </comment><info>%s</info><comment>...</comment>', $source->getName(), $version));
         $downloadProcess = new Process(sprintf("wget %s -O phpstorm.tar.gz", escapeshellarg($source->getUrl())));
         $downloadProcess->setTimeout(3600);
         $downloadProcess->run();
         $output->writeln(' <info>OK</info>');
         if (!$downloadProcess->isSuccessful()) {
             throw new \RuntimeException($downloadProcess->getErrorOutput());
         }
         $output->write('<comment>Extracting...</comment>');
         $extractProcess = new Process(sprintf('tar xfz phpstorm.tar.gz; rm phpstorm.tar.gz; mv %1$s %2$s', escapeshellarg($extractedFolder), escapeshellarg($targetFolder)));
         $extractProcess->run();
         $output->writeln(' <info>OK</info>');
         if (!$extractProcess->isSuccessful()) {
             throw new \RuntimeException($extractProcess->getErrorOutput());
         }
     }
     $output->write('<comment>Linking...</comment>');
     $command = sprintf('cd %2$s && ln -s -f -T %1$s %3$s', escapeshellarg($extractedFolder), escapeshellarg($targetFolder), escapeshellarg($symlinkName));
     $linkProcess = new Process($command);
     $linkProcess->run();
     $output->writeln(' <info>OK</info>');
     if (!$linkProcess->isSuccessful()) {
         throw new \RuntimeException($linkProcess->getErrorOutput());
     }
 }
 protected function setupStep(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('<info>Running installer actions</info>');
     foreach ($this->getContainer()->get('accesto.installer.actions') as $collection) {
         /**
          * @var $collection ActionCollection
          */
         $output->writeln(sprintf('<comment>%s</comment>', $collection->getLabel()));
         foreach ($collection as $action) {
             /**
              * @var $action ActionInterface
              */
             $output->write($action->getLabel());
             $output->write($action->getDescription());
             if ($action->run($this, $input, $output)) {
                 $output->writeln(' <info>OK</info>');
             } else {
                 $output->writeln(' <error>ERROR</error>');
                 $output->writeln(sprintf('<comment>%s</comment>', $action->getError()));
             }
         }
     }
     $output->writeln('');
     $output->writeln('<info>Successfully installed.</info>');
     return $this;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $rc = 0;
     try {
         $what = $input->getArgument('generate-what');
         if (in_array('all', $what) || in_array('ide-classes', $what)) {
             $output->write('Generating fake PHP classes to help IDE... ');
             if (!Core::make('app')->isInstalled()) {
                 $output->writeln('<error>failed: concrete5 is not installed.</error>');
                 $rc = 1;
             } else {
                 $this->generateIDEClasses();
                 $output->writeln('<info>done.</info>');
             }
         }
         if (in_array('all', $what) || in_array('phpstorm', $what)) {
             $output->write('Generating PHP metadata for PHPStorm... ');
             $this->generatePHPStorm();
             $output->writeln('<info>done.</info>');
         }
     } catch (Exception $x) {
         $output->writeln('<error>' . $x->getMessage() . '</error>');
         $rc = 1;
     }
     return $rc;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var $repository \eZ\Publish\API\Repository\Repository */
     $repository = $this->getContainer()->get('ezpublish.api.repository');
     $contentService = $repository->getContentService();
     $locationService = $repository->getLocationService();
     $urlAliasService = $repository->getURLAliasService();
     $sectionService = $repository->getSectionService();
     $userService = $repository->getUserService();
     $repository->setCurrentUser($repository->getUserService()->loadUser(14));
     $contentId = $input->getArgument('contentId');
     try {
         $contentInfo = $contentService->loadContentInfo($contentId);
         // show all locations of the content
         $locations = $locationService->loadLocations($contentInfo);
         $output->writeln("<info>LOCATIONS</info>");
         foreach ($locations as $location) {
             $urlAlias = $urlAliasService->reverseLookup($location);
             $output->writeln("  {$location->pathString}  ({$urlAlias->path})");
         }
         // show all relations of the current version
         $versionInfo = $contentService->loadVersionInfo($contentInfo);
         $relations = $contentService->loadRelations($versionInfo);
         if (count($relations)) {
             $output->writeln("<info>RELATIONS</info>");
             foreach ($relations as $relation) {
                 $name = $relation->destinationContentInfo->name;
                 $output->write("  Relation of type " . $this->outputRelationType($relation->type) . " to content {$name}");
             }
         }
         // show meta data
         $output->writeln("\n<info>METADATA</info>");
         $output->writeln("  <info>Name:</info> {$contentInfo->name}");
         $output->writeln("  <info>Type:</info> " . $contentInfo->contentType->identifier);
         $output->writeln("  <info>Last modified:</info> " . $contentInfo->modificationDate->format('Y-m-d'));
         $output->writeln("  <info>Published:</info> " . $contentInfo->publishedDate->format('Y-m-d'));
         $output->writeln("  <info>RemoteId:</info> {$contentInfo->remoteId}");
         $output->writeln("  <info>Main Language:</info> {$contentInfo->mainLanguageCode}");
         $output->writeln("  <info>Always available:</info> " . ($contentInfo->alwaysAvailable ? 'Yes' : 'No'));
         $owner = $userService->loadUser($contentInfo->ownerId);
         $output->writeln("  <info>Owner:</info> " . $owner->contentInfo->name);
         $section = $sectionService->loadSection($contentInfo->sectionId);
         $output->writeln("  <info>Section:</info> {$section->name}");
         // show versions
         $versionInfoArray = $contentService->loadVersions($contentInfo);
         if (count($versionInfoArray)) {
             $output->writeln("\n<info>VERSIONS</info>");
             foreach ($versionInfoArray as $versionInfo) {
                 $creator = $userService->loadUser($versionInfo->creatorId);
                 $output->write("  Version {$versionInfo->versionNo} ");
                 $output->write(" by " . $creator->contentInfo->name);
                 $output->writeln(" " . $this->outputStatus($versionInfo->status) . " " . $versionInfo->initialLanguageCode);
             }
         }
     } catch (\eZ\Publish\API\Repository\Exceptions\NotFoundException $e) {
         $output->writeln("<error>No content with id {$contentId}</error>");
     } catch (\eZ\Publish\API\Repository\Exceptions\UnauthorizedException $e) {
         $output->writeln("<error>Anonymous users are not allowed to read content with id {$contentId}</error>");
     }
 }
 /**
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $dm = $this->getHelper('dm')->getDocumentManager();
     $metadatas = $dm->getMetadataFactory()->getAllMetadata();
     $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter'));
     // Process destination directory
     $destPath = realpath($input->getArgument('dest-path'));
     if (!file_exists($destPath)) {
         throw new \InvalidArgumentException(sprintf("Documents destination directory '<info>%s</info>' does not exist.", $destPath));
     } else {
         if (!is_writable($destPath)) {
             throw new \InvalidArgumentException(sprintf("Documents destination directory '<info>%s</info>' does not have write permissions.", $destPath));
         }
     }
     if (count($metadatas)) {
         $numRepositories = 0;
         $generator = new DocumentRepositoryGenerator();
         foreach ($metadatas as $metadata) {
             if ($metadata->customRepositoryClassName) {
                 $output->write(sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName) . PHP_EOL);
                 $generator->writeDocumentRepositoryClass($metadata->customRepositoryClassName, $destPath);
                 $numRepositories++;
             }
         }
         if ($numRepositories) {
             // Outputting information message
             $output->write(PHP_EOL . sprintf('Repository classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
         } else {
             $output->write('No Repository classes were found to be processed.' . PHP_EOL);
         }
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     if (!$input->getOption('site')) {
         $output->writeln('Please provide an <info>--site=SITE_ID</info> option or the <info>--site=all</info> directive');
         $output->writeln('');
         $output->writeln(sprintf(" % 5s - % -30s - %s", "ID", "Name", "Url"));
         foreach ($this->getSiteManager()->findBy(array()) as $site) {
             $output->writeln(sprintf(" % 5s - % -30s - %s", $site->getId(), $site->getName(), $site->getUrl()));
         }
         return;
     }
     foreach ($this->getSites($input) as $site) {
         if ($input->getOption('site') != 'all') {
             if ($input->getOption('mode') == 'async') {
                 $output->write(sprintf("<info>%s</info> - Publish a notification command ...", $site->getName()));
             } else {
                 $output->write(sprintf("<info>%s</info> - Generating snapshots ...", $site->getName()));
             }
             $this->getNotificationBackend($input->getOption('mode'))->createAndPublish('sonata.page.create_snapshots', array('siteId' => $site->getId(), 'mode' => $input->getOption('mode')));
             $output->writeln(" done!");
         } else {
             $p = new Process(sprintf('%s sonata:page:create-snapshots --env=%s --site=%s --mode=%s %s ', $input->getOption('base-console'), $input->getOption('env'), $site->getId(), $input->getOption('mode'), $input->getOption('no-debug') ? '--no-debug' : ''));
             $p->run(function ($type, $data) use($output) {
                 $output->write($data, OutputInterface::OUTPUT_RAW);
             });
         }
     }
     $output->writeln("<info>done!</info>");
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     global $container;
     /** @var string $cacheDir */
     $cacheDir = $container['doctrine.orm.proxiesCacheDir'];
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($cacheDir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
     /** @var \SplFileInfo $file */
     foreach ($iterator as $file) {
         if ($file->isDir()) {
             rmdir($file);
         } else {
             unlink($file);
         }
     }
     /** @var EntityManager $entityManager */
     $entityManager = $container['doctrine.orm.entityManager'];
     $metadatas = $entityManager->getMetadataFactory()->getAllMetadata();
     if (count($metadatas)) {
         // Generating Proxies
         $entityManager->getProxyFactory()->generateProxyClasses($metadatas, $cacheDir);
         // Outputting information message
         $output->write(PHP_EOL . sprintf('Proxy classes generated to "<info>%s</INFO>"', $cacheDir) . PHP_EOL);
     } else {
         $output->write('No Metadata Classes to process.' . PHP_EOL);
     }
 }
 /**
  * Import Users
  */
 private function importUsers()
 {
     $this->output->write(sprintf('%-30s', 'Importing users'));
     $previewUsers = $this->previewService->getUsers();
     $created = 0;
     $updated = 0;
     foreach ($previewUsers as $previewUser) {
         if (!strlen($previewUser->email)) {
             continue;
         }
         /**
          * @var User $user
          */
         $user = $this->entityManager->getRepository('ProjectPreviewUserBundle:User')->find($previewUser->id);
         if (is_null($user)) {
             $user = new User();
             $user->setId($previewUser->id);
             $user->setPassword('toto');
             $created++;
         } else {
             $updated++;
         }
         $user->setEmail($previewUser->email);
         $user->setUsername($previewUser->email);
         $user->setLastname($previewUser->lastname);
         $user->setFirstname($previewUser->firstname);
         if (isset($previewUser->avatar->urls->avatar_xs)) {
             $user->setAvatar($previewUser->avatar->urls->avatar_xs);
         }
         $this->entityManager->persist($user);
     }
     $this->output->writeln(sprintf('done (total: % 4d, created: % 4d, updated: % 4d)', $created + $updated, $created, $updated));
     $this->entityManager->flush();
 }
Example #23
0
 /**
  * Prints a result set from Detector::copyPasteDetection().
  *
  * @param OutputInterface $output
  * @param CodeCloneMap    $clones
  */
 public function printResult(OutputInterface $output, CodeCloneMap $clones)
 {
     $numClones = count($clones);
     $verbose = $output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL;
     if ($numClones > 0) {
         $buffer = '';
         $files = array();
         $lines = 0;
         foreach ($clones as $clone) {
             foreach ($clone->getFiles() as $file) {
                 $filename = $file->getName();
                 if (!isset($files[$filename])) {
                     $files[$filename] = true;
                 }
             }
             $lines += $clone->getSize() * (count($clone->getFiles()) - 1);
             $buffer .= "\n  -";
             foreach ($clone->getFiles() as $file) {
                 $buffer .= sprintf("\t%s:%d-%d\n ", $file->getName(), $file->getStartLine(), $file->getStartLine() + $clone->getSize());
             }
             if ($verbose) {
                 $buffer .= "\n" . $clone->getLines('      ');
             }
         }
         $output->write(sprintf("Found %d exact clones with %d duplicated lines in %d files:\n%s", $numClones, $lines, count($files), $buffer));
     }
     $output->write(sprintf("%s%s duplicated lines out of %d total lines of code.\n\n", $numClones > 0 ? "\n" : '', $clones->getPercentage(), $clones->getNumLines()));
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $systemCheck = new SystemCheck();
     $systemCheck->checkRedisIsInstalled();
     $settings = Queue\Factory::getSettings();
     if ($settings->queueEnabled->getValue()) {
         $output->writeln('Queue is enabled');
     } else {
         $output->writeln('<comment>' . strtoupper('Queue is disabled: ') . 'No new requests will be written into the queue, processing the remaining requests is still possible.</comment>');
     }
     $backend = Queue\Factory::makeBackend();
     $manager = Queue\Factory::makeQueueManager($backend);
     $queues = $manager->getAllQueues();
     $lock = Queue\Factory::makeLock($backend);
     if ($settings->processDuringTrackingRequest->getValue()) {
         $output->writeln('Request sets in the queue will be processed automatically after a tracking request');
     } else {
         $output->writeln('The command <comment>./console queuedtracking:process</comment> has to be executed to process request sets within queue');
     }
     $output->writeln(sprintf('Up to %d workers will be used', $manager->getNumberOfAvailableQueues()));
     $output->writeln(sprintf('Processor will start once there are at least %s request sets in the queue', $manager->getNumberOfRequestsToProcessAtSameTime()));
     while (1) {
         $memory = $backend->getMemoryStats();
         // I know this will only work with redis currently as it is not defined in backend interface etc. needs to be refactored once we add another backend
         $numInQueue = array();
         foreach ($queues as $queue) {
             $numInQueue[] = $queue->getNumberOfRequestSetsInQueue();
         }
         $message = sprintf('%s (%s) request sets left in queue. %s used memory (%s peak). %d workers active.        ', array_sum($numInQueue), implode('+', $numInQueue), $memory['used_memory_human'], $memory['used_memory_peak_human'], $lock->getNumberOfAcquiredLocks());
         $output->write("\r");
         $output->write($message);
         sleep(2);
     }
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         if (!$this->option('url')) {
             $output->write('Requesting Version...');
             $versions = $this->getVersions();
             $output->writeln('<info>done.</info>');
             $output->writeln('');
             $output->writeln('<comment>Latest Version: ' . $versions['latest']['version'] . '</comment> ');
             $output->writeln('');
             if (!$this->confirm('Update to Version ' . $versions['latest']['version'] . '? [y/n]')) {
                 return;
             }
             $output->writeln('');
             $url = $versions['latest']['url'];
         } else {
             $url = $this->option('url');
         }
         $tmpFile = tempnam($this->container['path.temp'], 'update_');
         $output->write('Downloading...');
         $this->download($url, $tmpFile);
         $output->writeln('<info>done.</info>');
         $updater = new SelfUpdater($output);
         $updater->update($tmpFile);
         $output->write('Migrating...');
         system(sprintf('php %s migrate', $_SERVER['PHP_SELF']));
     } catch (\Exception $e) {
         if (isset($tmpFile) && file_exists($tmpFile)) {
             unlink($tmpFile);
         }
         throw $e;
     }
 }
Example #26
0
 /**
  * @inheritdoc
  */
 public function execute(ResultCollection $collection, ResultCollection $aggregatedResults)
 {
     if (!$this->enabled) {
         return;
     }
     $this->output->write($this->formater->terminate($collection, $aggregatedResults));
 }
 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);
 }
 /**
  * {@inheritdoc}
  */
 protected function doExecute(InputInterface $input, OutputInterface $output)
 {
     $ret = static::CHECK_OK;
     foreach ($this->provideRequirements() as $collection) {
         $output->writeln('');
         $output->writeln($collection->getName() . ' requirements : ');
         $output->writeln('');
         foreach ($collection->getRequirements() as $requirement) {
             $result = $requirement->isFulfilled() ? '<info>OK       </info>' : ($requirement->isOptional() ? '<comment>WARNING</comment>  ' : '<error>ERROR</error>    ');
             $output->write(' ' . $result);
             $output->writeln($requirement->getTestMessage());
             if (!$requirement->isFulfilled()) {
                 $ret = static::CHECK_ERROR;
                 $output->writeln("          " . $requirement->getHelpText());
                 $output->writeln('');
             }
         }
         $output->writeln('');
         $output->writeln($collection->getName() . ' recommendations : ');
         $output->writeln('');
         foreach ($collection->getRecommendations() as $requirement) {
             $result = $requirement->isFulfilled() ? '<info>OK       </info>' : ($requirement->isOptional() ? '<comment>WARNING</comment>  ' : '<error>ERROR</error>    ');
             $output->write(' ' . $result);
             $output->writeln($requirement->getTestMessage());
             if (!$requirement->isFulfilled()) {
                 if ($ret === static::CHECK_OK) {
                     $ret = static::CHECK_WARNING;
                 }
                 $output->writeln("          " . $requirement->getHelpText());
                 $output->writeln('');
             }
         }
     }
     return $ret;
 }
Example #29
0
 /**
  * @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>");
     }
 }
Example #30
0
 /**
  * @param \Generated\Shared\Transfer\LocaleTransfer $locale
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  *
  * @return array
  */
 public function exportStorageByLocale(LocaleTransfer $locale, OutputInterface $output)
 {
     $results = [];
     $types = array_keys($this->exporter->getCollectorPlugins());
     $availableTypes = $this->getAvailableCollectorTypes($types);
     $output->writeln('');
     $output->writeln(sprintf('<fg=yellow>Locale:</fg=yellow> <fg=white>%s</fg=white>', $locale->getLocaleName()));
     $output->writeln('<fg=yellow>-------------</fg=yellow>');
     foreach ($availableTypes as $type) {
         if (!in_array($type, $types)) {
             $output->write('<fg=yellow> * </fg=yellow><fg=green>' . $type . '</fg=green> ');
             $output->write('<fg=white>N/A</fg=white>');
             $output->writeln('');
             continue;
         }
         $result = $this->exporter->exportByType($type, $locale, $output);
         $this->handleResult($result);
         if ($result instanceof BatchResultInterface) {
             if ($this->nothingWasProcessed($result)) {
                 continue;
             }
             $results[$type] = $result;
         }
     }
     return $results;
 }