Executes a DOWN Migration

@param AbstractQuery    $oQuery  The query object that is being executed
@param OutputInterface  $oOutput The output handler for the console output that might be generated

@return bool
169232
protected function _goDown(AbstractQuery $oQuery, OutputInterface $oOutput = null)
    {
        if (!$this->isExecuted($oQuery)) {
            return false;
        }

        if ($oOutput) {
            $oOutput->writeLn(
                sprintf(
                    '[DEBUG] Migrating down %s %s',
                    $oQuery->getTimestamp(),
                    $oQuery->getClassName()
                )
            );
        }

        $oQuery->down();
        $this->setUnexecuted($oQuery);

        return true;
    }
497846
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $questionHelper = $this->getQuestionHelper();
        $questionHelper->writeSection($output, 'Search Page Generation');

        $prefix = $input->getOption('prefix');
        $createPage = $input->getOption('createpage');
        if (Kernel::VERSION_ID < 40000) {
            GeneratorUtils::ensureOptionsProvided($input, ['namespace']);

            $namespace = Validators::validateBundleNamespace($input->getOption('namespace'));
            $bundle = strtr($namespace, ['\\' => '']);

            $bundle = $this
                ->getApplication()
                ->getKernel()
                ->getBundle($bundle);
        } else {
            $bundle = new Sf4AppBundle($this->getContainer()->getParameter('kernel.project_dir'));
        }

        $rootDir = $this->getApplication()->getKernel()->getRootDir();

        $generator = $this->getGenerator($this->getApplication()->getKernel()->getBundle('KunstmaanGeneratorBundle'));
        $generator->generate($bundle, $prefix, $rootDir, $createPage, $output);

        $output->writeln(array(
                'Make sure you update your database first before you test the pagepart:',
                '    Directly update your database:          <comment>bin/console doctrine:schema:update --force</comment>',
                '    Create a Doctrine migration and run it: <comment>bin/console doctrine:migrations:diff && bin/console doctrine:migrations:migrate</comment>', )
        );

        if ($createPage) {
            $output->writeln('    New DataFixtures were created. You can load them via: <comment>bin/console doctrine:fixtures:load --fixtures=src/'.str_replace('\\', '/', $bundle->getNamespace()).'/DataFixtures/ORM/SearchPageGenerator/ --append</comment>');
        }

        $output->writeln('');
    }
565404
protected function execute(InputInterface $oInput, OutputInterface $oOutput)
    {
        parent::execute($oInput, $oOutput);

        $oOutput->writeln('');
        $oOutput->writeln('<info>--------------------</info>');
        $oOutput->writeln('<info>CDN Driver Migration</info>');
        $oOutput->writeln('<info>--------------------</info>');
        $oOutput->writeln('');

        $oStorageDriver = Factory::service('StorageDriver', 'nails/module-cdn');
        $sDriver        = $oInput->getArgument('driver');
        $bOverwrite     = $oInput->getOption('overwrite');
        $bRemove        = $oInput->getOption('remove-src');
        $aAllDrivers    = $oStorageDriver->getAll();

        //  Auto-detect the driver if not specified
        if (empty($sDriver)) {
            $oEnabledDriver = $oStorageDriver->getEnabled();
            if (empty($oEnabledDriver)) {
                throw new NailsException('No CDN drivers are enabled');
            } else {
                $sDriver = $oEnabledDriver->slug;
            }
        }

        //  Validate driver
        $aDrivers    = [];
        $aDriversOld = [];
        foreach ($aAllDrivers as $oDriver) {
            $aDrivers[$oDriver->slug] = $oDriver;
            if ($oDriver->slug != $sDriver) {
                $aDriversOld[$oDriver->slug] = $oDriver;
            }
        }

        if (!array_key_exists($sDriver, $aDrivers)) {
            throw new NailsException('"' . $sDriver . '" is not a valid storage driver.');
        }

        // --------------------------------------------------------------------------

        //  Work out what's going to happen
        $oObjectModel = Factory::model('Object', 'nails/module-cdn');

        //  How many objects are already migrated
        $iMigrated = $oObjectModel->countAll([
            'where' => [
                ['driver', $sDriver],
            ],
        ]);

        //  How many objects will be migrated
        $iToMigrate = $oObjectModel->countAll([
            'where_in' => [
                ['driver', array_keys($aDriversOld)],
            ],
        ]);

        //  How many objects which need to be migrated but won't be
        $iCannotMigrate = $oObjectModel->countAll([
            'where_not_in' => [
                ['driver', array_keys($aDrivers)],
            ],
        ]);

        //  Summarise for the user and seek confirmation
        $oOutput->writeln('');
        $oOutput->writeln('Migrate CDN objects to <info>' . $sDriver . '</info>');
        $oOutput->writeln('');
        if ($iToMigrate) {
            $oOutput->writeln('- <info>' . $iToMigrate . '</info> objects will be migrated');
            $oOutput->writeln('- <info>' . $iMigrated . '</info> objects already exist and will not be migrated');
            if (!empty($iCannotMigrate)) {
                $oOutput->writeln(
                    '- <info>' . $iCannotMigrate . '</info> objects cannot be migrated as their driver is not available'
                );
            }

            if ($bOverwrite) {
                $oOutput->writeln('- <fg=red;options=bold>Target overwriting is enabled</>');
            }

            if ($bRemove) {
                $oOutput->writeln('- <fg=red;options=bold>The original file will be deleted</>');
            }

            $oOutput->writeln('');
            if ($this->confirm('Continue?', true)) {
                $oOutput->writeln('<comment>Migrating...</comment>');
                $this->doMigrate($sDriver, $bOverwrite, $bRemove, $aDriversOld);
            } else {
                $oOutput->writeln('');
                $oOutput->writeln('Aborting Migration');
            }

        } else {
            $oOutput->writeln('There are no objects requiring migration.');
        }

        // --------------------------------------------------------------------------

        //  Cleaning up
        $oOutput->writeln('');
        $oOutput->writeln('<comment>Cleaning up...</comment>');

        //  And we're done!
        $oOutput->writeln('');
        $oOutput->writeln('Complete!');
    }
511797
public function run(Migration $migration, $executeQueries = false, $forcedRollback = false)
    {
        $this->migration = $migration;

        try {
            $this->playQueries($executeQueries);
            if ($forcedRollback) {
                $this->playRollbackQueries($executeQueries);
            }
        } catch (Exception $e) {
            $this->playRollbackQueries($executeQueries);

            throw $e;
        }
    }
1177029
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);

        $this->setOutput($output);
        $this->setVerbosity($output->getVerbosity());

        $isChild = $input->getOption('child');

        if ($isChild && $output->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
            $this->setVerbosity(self::VERBOSITY_CHILD);
        }

        $this->getContainer()->get('ez_migration_bundle.step_executed_listener.tracing')->setOutput($output);

        // q: is it worth declaring a new, dedicated migration service ?
        $migrationService = $this->getMigrationService();
        $migrationService->setLoader($this->getContainer()->get('ez_migration_bundle.loader.filesystem_recursive'));

        $force = $input->getOption('force');

        $toExecute = $this->buildMigrationsList($input->getOption('path'), $migrationService, $force, $isChild);

        if (!count($toExecute)) {
            $this->writeln('<info>No migrations to execute</info>');
            return 0;
        }

        if ($isChild) {
            return $this->executeAsChild($input, $output, $toExecute, $force, $migrationService);
        } else {
            return $this->executeAsParent($input, $output, $toExecute, $start);
        }
    }
71332
public function purge(bool $force, OutputInterface $output)
    {
        $tables = $this->db->getSchemaManager()->listTableNames();
        foreach ($tables as $table) {
            $output->writeln("<info>Dropping table $table</info>");
            if ($force) {
                $this->db->getSchemaManager()->dropTable($table);
            }
        }

        if (!$force) {
            $output->writeln('<comment>No query was run, use the --force option to run the queries</comment>');
        } else {
            $output->writeln('<comment>Queries were successfully run against the database</comment>');
        }

        $this->update($force, $output);
    }
601942
protected function execute(InputInterface $input, OutputInterface $output)
        {
            $aData = array();
            // set colors and formats
            $oErrStyle  = new OutputFormatterStyle('red', null, array('bold'));
            $oOkStyle   = new OutputFormatterStyle('green', null, array('bold'));
            $oLogoStyle = new OutputFormatterStyle('cyan', null);
            $output->getFormatter()->setStyle('err', $oErrStyle);
            $output->getFormatter()->setStyle('ok', $oOkStyle);
            $output->getFormatter()->setStyle('sw', $oLogoStyle);

            // print logo
            $this->_printLogo($output);


            // Get active remote apps
            $aRemoteApps = RemoteAppQuery::create()->findByActivated(true);
            /** @var RemoteApp $oRemoteApp */
            $iCnt       = 0;
            foreach ($aRemoteApps as $oRemoteApp) {
                // get cron string
                $aData[] = array(
                    $oRemoteApp->getId(),
                    $oRemoteApp->getName(),
                    $oRemoteApp->getLastRun()->format("d.m.Y H:i:s"),
                );
                $iCnt++;
            }

            // get tablehelper for cli
            $oTable = $this->getHelper('table');
            $oTable
                ->setHeaders(array('ID', 'Title', 'Lastrun'))
                ->setRows($aData)
            ;
            $oTable->render($output);

            // green text
            $output->writeln("\n<fg=white;options=bold>     " . $iCnt . " Job(s) found</fg=white;options=bold>\n");

        }
1066134
public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->createAppMigrationsTable();

        $migrations = $this->migrationsToRun();

        usort($migrations, function ($a, $b) {
            return strcmp($a->getTimestamp(), $b->getTimestamp());
        });

        $count     = 0;
        $totalTime = 0;
        foreach ($migrations as $migration) {
            $output->writeln(sprintf(
                '  * STARTING *  %s (%s)',
                $migration->getDescription(),
                $migration->getTimestamp()
            ));
            $start = microtime(true);

            $migration->execute($this->db);

            $time = microtime(true) - $start;
            $totalTime += $time;
            $output->writeln(sprintf(
                '  * DONE *  %s (%s) - Took %.2fs',
                $migration->getDescription(),
                $migration->getTimestamp(),
                $time
            ));

            $this->recordMigration($migration);

            $count++;
        }

        if ($count === 0) {
            $message = '  No new migrations to run';
        } else {
            $message = sprintf('  Executed %d migrations in %.2fs', $count, $totalTime);
        }

        $output->writeln([$message, ''], true);
    }
1169993
protected function execute(InputInterface $oInput, OutputInterface $oOutput)
    {
        parent::execute($oInput, $oOutput);

        $oOutput->writeln('');
        $oOutput->writeln('<info>--------------------</info>');
        $oOutput->writeln('<info>Nails Routes Rewrite</info>');
        $oOutput->writeln('<info>--------------------</info>');
        $oOutput->writeln('');

        $oRoutesService = Factory::service('Routes');

        try {
            if (!$oRoutesService->update(null, $oOutput)) {
                throw new NailsException($oRoutesService->lastError());
            }
        } catch (\Exception $e) {
            $this->abort(
                static::EXIT_CODE_FAILURE,
                [
                    'There was a problem writing the routes.',
                    $e->getMessage(),
                ]
            );
        }

        //  Cleaning up
        $oOutput->writeln('');
        $oOutput->writeln('<comment>Cleaning up...</comment>');

        //  And we're done!
        $oOutput->writeln('');
        $oOutput->writeln('Complete!');

        return static::EXIT_CODE_SUCCESS;
    }
1324469
protected function execute(InputInterface $oInput, OutputInterface $oOutput)
    {
        parent::execute($oInput, $oOutput);

        foreach (\Nails\Components::available() as $oComponent) {
            if (!empty($oComponent->scripts->install)) {
                $this->oOutput->writeln('Executing post-install scripts for: <comment>' . $oComponent->slug . '</comment>');
                $this->oOutput->writeln('> <info>cd ' . $oComponent->path . '</info>');
                chdir($oComponent->path);
                $this->executeCommand($oComponent->scripts->install);
            }
        }

        return static::EXIT_CODE_SUCCESS;
    }
267698
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();
        $doctrine = $container->get('doctrine');
        $manager = $doctrine->getManager();

        /** @var Connection $connection */
        $connection = $doctrine->getConnection();

        /** @var JobRepository $jobsRepository */
        $jobsRepository = $manager->getRepository(Job::class);

        /** @var QueryBuilder $queryBuilder */
        $queryBuilder = $jobsRepository->createQueryBuilder('j');

        $queryBuilder->select('MAX(j.createdAt) AS createdAt , j.command, j.args');

        $queryBuilder->where($queryBuilder->expr()->notIn('j.state', ['new', 'pending', 'running']));

        $queryBuilder->orderBy('j.createdAt', 'desc');

        $queryBuilder->groupBy('j.command', 'j.args');

        $jobs = $queryBuilder->getQuery()->getArrayResult();

        /** @var Job $job */
        foreach ($jobs as $job) {
            $output->writeln($job['command'] . ' ' . implode(' ', $job['args']));

            $queryBuilder = $jobsRepository->createQueryBuilder('j');

            $queryBuilder->where($queryBuilder->expr()->notIn('j.state', ['new', 'pending', 'running']));

            $queryBuilder->andWhere('j.command = :command');
            $queryBuilder->andWhere('j.args = :args');

            $queryBuilder->andWhere('j.createdAt < :createdAt');

            $queryBuilder->setParameter('command', $job['command']);
            $queryBuilder->setParameter('args', $job['args'], Type::JSON_ARRAY);

            $queryBuilder->setParameter('createdAt', $job['createdAt']);

            $queryBuilder->select('j.id');

            $ids = $queryBuilder->getQuery()->getArrayResult();

            foreach ($ids as $item) {
                $connection->executeQuery('DELETE FROM jms_job_related_entities WHERE job_id = :id', ['id' => $item['id']]);
                $connection->executeQuery('DELETE FROM jms_job_dependencies WHERE dest_job_id = :id', ['id' => $item['id']]);
                $connection->executeQuery('DELETE FROM jms_jobs WHERE id = :id', ['id' => $item['id']]);
            }
        }
    }
924523
private function createOperationOutput(array &$output, OperationInterface $operation)
    {
        $operationHandler = $this->getOperationHandler($operation);

        if (!$operationHandler) {
            return;
        }

        $output[] = '';

        $urlGenerator = $this->getUrlGenerator(
            $operationHandler->extractSourceUrl($operation)
        );

        $output = array_merge(
            $output,
            $operationHandler->getOutput($operation, $urlGenerator)
        );
    }
1083551
public function execute(InputInterface $input, OutputInterface $output)
    {
        // graviton root
        $baseDir = __DIR__.'/../../../';

        // vendorized? - go back some more..
        if (strpos($baseDir, '/vendor/') !== false) {
            $baseDir .= '../../../';
        }

        $this->finder
            ->in($baseDir)
            ->path('Resources/config')
            ->name('/migrations.(xml|yml)/')
            ->files();

        foreach ($this->finder as $file) {
            if (!$file->isFile()) {
                continue;
            }

            $output->writeln('Found '.$file->getRelativePathname());

            $command = $this->getApplication()->find('mongodb:migrations:migrate');

            $helperSet = $command->getHelperSet();
            $helperSet->set($this->documentManager, 'dm');
            $command->setHelperSet($helperSet);

            $configuration = $this->getConfiguration($file->getPathname(), $output);
            self::injectContainerToMigrations($this->container, $configuration->getMigrations());
            $command->setMigrationConfiguration($configuration);

            $arguments = $input->getArguments();
            $arguments['command'] = 'mongodb:migrations:migrate';
            $arguments['--configuration'] = $file->getPathname();

            $migrateInput = new ArrayInput($arguments);
            $migrateInput->setInteractive($input->isInteractive());
            $returnCode = $command->run($migrateInput, $output);

            if ($returnCode !== 0) {
                $this->errors[] = sprintf(
                    'Calling mongodb:migrations:migrate failed for %s',
                    $file->getRelativePathname()
                );
            }
        }

        if (!empty($this->errors)) {
            $output->writeln(
                sprintf('<error>%s</error>', implode(PHP_EOL, $this->errors))
            );
            return -1;
        }

        return 0;
    }
646660
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
        $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
        $errOutput->setVerbosity(OutputInterface::VERBOSITY_NORMAL);

        $batchSize = NumberUtils::bound($input->getOption('batch-size'), 1, 2000);
        $batchDelay = NumberUtils::bound($input->getOption('batch-delay'), 10, 600000);
        $context = json_decode($input->getOption('context') ?: '{}', true);
        $context['tenant_id'] = (string)$input->getOption('tenant-id');
        $context['exporting'] = true;
        $qname = $input->getArgument('qname') ? SchemaQName::fromString($input->getArgument('qname')) : null;
        $context['exporting_all'] = null === $qname;

        $i = 0;

        $receiver = function (Node $node) use ($errOutput, $batchSize, $batchDelay, &$i) {
            ++$i;

            try {
                echo json_encode($node) . PHP_EOL;
            } catch (\Exception $e) {
                $errOutput->writeln($e->getMessage());
            }

            if (0 === $i % $batchSize) {
                if ($batchDelay > 0) {
                    usleep($batchDelay * 1000);
                }
            }
        };

        foreach ($this->getSchemasUsingMixin(NodeV1Mixin::create(), (string)$qname ?: null) as $schema) {
            $this->ncr->pipeNodes($schema->getQName(), $receiver, $context);
        }
    }
1330995
protected function execute(InputInterface $input, OutputInterface $output)
    {
        ini_set('memory_limit', '1024M');
        $reader = new OekobaudatReader();

        $this->store('contact', $reader, $reader->getContactList(), $output);
        $this->store('flow_property', $reader, $reader->getFlowPropertyList(), $output);
        $this->store('process', $reader, $reader->getProcessList(), $output);
        $this->store('source', $reader, $reader->getSourceList(), $output);
        $this->store('unit_group', $reader, $reader->getUnitGroupList(), $output);

        $this->storeFlows($reader, $output);

        //$this->getContainer()->get('beaast.oekobaudat.manager.process')->updateAllfromXml();
        //$this->getContainer()->get('beaast.oekobaudat.manager.flow')->updateAllfromXml();
        //$this->getContainer()->get('beaast.oekobaudat.manager.flow_property')->updateAllfromXml();

        $this->getContainer()->get('beaast.oekobaudat.manager.contact')->updateReferences();
        $this->getContainer()->get('beaast.oekobaudat.manager.flow')->updateReferences();
        $this->getContainer()->get('beaast.oekobaudat.manager.flow_property')->updateReferences();
        $this->getContainer()->get('beaast.oekobaudat.manager.process')->updateReferences();
        $this->getContainer()->get('beaast.oekobaudat.manager.source')->updateReferences();
        $this->getContainer()->get('beaast.oekobaudat.manager.unit_group')->updateReferences();

        return 0;
    }
591902
protected function execute(InputInterface $oInput, OutputInterface $oOutput): int
    {
        parent::execute($oInput, $oOutput);

        $oOutput->writeln('');
        $oOutput->writeln('<info>----------------</info>');
        $oOutput->writeln('<info>Nails Maker Tool</info>');
        $oOutput->writeln('<info>----------------</info>');

        // --------------------------------------------------------------------------

        //  Setup Factory - config files are required prior to set up
        Factory::setup();

        // --------------------------------------------------------------------------

        //  Check environment
        if (Environment::not(Environment::ENV_DEV)) {
            return $this->abort(
                self::EXIT_CODE_FAILURE,
                'This tool is only available on ' . Environment::ENV_DEV . ' environments'
            );
        }

        return self::EXIT_CODE_SUCCESS;
    }
1203946
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;

        /** @var $repository Repository */
        $repository = $this->getContainer()->get('ezpublish.api.repository');

        /** @var $contentService ContentService */
        $contentService = $repository->getContentService();
        /** @var $contentTypeService ContentTypeService*/
        $contentTypeService = $repository->getContentTypeService();
        /** @var $locationService LocationService */
        $locationService = $repository->getLocationService();

        /** @var $questionHelper QuestionHelper */
        $questionHelper = $this->getHelper('question');

        $struct = array();

        $struct['parentLocationID'] = $this->getParentLocationID($locationService, $questionHelper);
        $struct['contentTypeIdentifier'] = $this->getContentTypeIdentifier($contentTypeService, $questionHelper);
        $contentType = $contentTypeService->loadContentTypeByIdentifier($struct['contentTypeIdentifier']);
        $languageCode = $contentType->mainLanguageCode;
        $struct['languageCode'] = $languageCode;

        $struct['fields'] = array();
        $fields = $contentType->getFieldDefinitions();
        foreach ($fields as $field) {
            $fieldName = $field->getName($languageCode);
            $fieldIdentifier = $field->identifier;

            $fieldValue = $this->getFieldValue($questionHelper, $fieldName);
            $struct['fields'][] = array(
                'identifier' => $fieldIdentifier,
                'value' => $fieldValue
            );
        }

        /** @var $configResolver ConfigResolver */
        $configResolver = $this->getContainer()->get('ezpublish.config.resolver');
        $adminID = $this->getContainer()->getParameter('smile_ez_tools.adminid');

        $smileEzContentService = new Content($repository);
        $smileEzContentService->setAdminID($adminID);
        try {
            $smileEzContentService->add($struct);
            $output->writeln("<info>Content created</info>");
        } catch (UnauthorizedException $e) {
            $output->writeln("<error>" . $e->getMessage() . "</error>");
        } catch (ForbiddenException $e ) {
            $output->writeln("<error>" . $e->getMessage() . "</error>");
        }
    }