A wizard generator.

@param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@param null $firstKey

@return \Generator|\Symfony\Component\Console\Question\Question[]
4291
private function getWizard(InputInterface $input, OutputInterface $output, $firstKey = null)
    {
        $questions = $this->wizardSteps();
        $tryAgain = false;
        $result = null;

        // Loop over the questions, parse them, then yield them out
        foreach ($questions as $question) {
            if (!$firstKey && $question instanceof \Closure) {
                $result = $question($input, $output, $this);

                if ($result === false || is_string($result)) {
                    $tryAgain = true;
                    break;
                }

                continue;
            }

            $question = (array) $question;
            if ($firstKey && $question[0] !== $firstKey) {
                continue;
            }

            // If we still have a firstKey set, that means we've hit the first key. Unset so that we don't test again
            if ($firstKey) {
                $firstKey = null;
            }

            if (in_array($question[0], ['demo-password', 'demo-email'], true) && '' === (string) $input->getOption('demo-username')) {
                continue;
            }

            yield $question[0] => $this->getQuestion($question, $input);
        }

        if ($tryAgain) {
            // Try again, passing the result as the first next item. This allows us to use this like a goto
            foreach ($this->getWizard($input, $output, $result) as $key => $value) {
                yield $key => $value;
            }
        }
    }
1157482
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Start generating...');
        $generated = $this->getFacade()->generateDataProvider();

        if ($output->isVerbose()) {
            foreach ($generated as $provider) {
                $output->writeln($provider . ' generated');
            }
        }
    }
133478
protected function configureIO(InputInterface $input, OutputInterface $output)
    {
        if (true === $input->hasParameterOption(array('--ansi'), true)) {
            $output->setDecorated(true);
        } elseif (true === $input->hasParameterOption(array('--no-ansi'), true)) {
            $output->setDecorated(false);
        }

        if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) {
            $input->setInteractive(false);
        } elseif (function_exists('posix_isatty')) {
            $inputStream = null;

            if ($input instanceof StreamableInputInterface) {
                $inputStream = $input->getStream();
            }

            // This check ensures that calling QuestionHelper::setInputStream() works
            // To be removed in 4.0 (in the same time as QuestionHelper::setInputStream)
            if (!$inputStream && $this->getHelperSet()->has('question')) {
                $inputStream = $this->getHelperSet()->get('question')->getInputStream(false);
            }

            if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
                $input->setInteractive(false);
            }
        }

        if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) {
            $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
            $input->setInteractive(false);
        } else {
            if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || $input->getParameterOption('--verbose', false, true) === 3) {
                $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
            } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || $input->getParameterOption('--verbose', false, true) === 2) {
                $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
            } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
                $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
            }
        }
    }
1302694
private function implementGetIterator(ClassGenerator $class, Property $firstProperty)
    {
        $methodName = 'getIterator';
        $class->removeMethod($methodName);
        $class->addMethodFromGenerator(
            MethodGenerator::fromArray([
                'name' => $methodName,
                'parameters' => [],
                'visibility' => MethodGenerator::VISIBILITY_PUBLIC,
                'body' => sprintf(
                    'return new \\ArrayIterator(is_array($this->%1$s) ? $this->%1$s : []);',
                    $firstProperty->getName()
                ),
                'docblock' => DocBlockGeneratorFactory::fromArray([
                    'tags' => [
                        [
                            'name' => 'return',
                            'description' => '\\ArrayIterator'
                        ]
                    ]
                ])
            ])
        );
    }
156923
protected function init(InputInterface $input, OutputInterface $output)
    {
    	$this->input = $input;
    	$this->output = $output;

    	$this->bbapp = $this->getContainer()->get('bbapp');
    	$this->entyMgr = $this->bbapp->getEntityManager();

    	return $this;
    }
1372739
protected function waitForUserInput(InputInterface $input, OutputInterface $output)
    {
        $helper   = $this->getHelper('question');
        $question = new Question('<info>You > </info>');

        $message = $helper->ask($input, $output, $question);

        $this->listenForConsoleCommands($input, $output, $message);

        $this->getBotResponse($input, $output, $message);
    }
1006015
protected function createConfiguration(InputInterface $input, OutputInterface $output)
    {
        $path = $this->getApplication()->getRoot() . '/.jedi.php';

        $output->writeln('  - Configuration');

        if (file_exists($path)) {
            $question = new ConfirmationQuestion(
                '    <error>Configuration file ' . $path . ' already exists</error>' . PHP_EOL
                . '    <info>Overwrite? [Y/n]</info> ',
                true,
                '/^(y|j)/i'
            );

            if (!$this->questionHelper->ask($input, $output, $question)) {
                return;
            }
        }

        $fs = new Filesystem();

        $question = new Question('    <info>Enter path to web directory relative to '
            . $this->getApplication()->getRoot() . ':</info> ' . PHP_EOL
            . '    (or do not specify if you are already in the web directory)' . PHP_EOL);

        $question->setValidator(function ($answer) use ($fs) {
            $path = $answer;

            if ($answer === null) {
                $path = $this->getApplication()->getRoot();
            } elseif (!$fs->isAbsolutePath($answer)) {
                $path = $this->getApplication()->getRoot() . '/' . $answer;
            }

            if (!is_dir($path)) {
                throw new \RuntimeException('Directory "' . $path . '" is missing');
            }

            return $answer;
        });

        $webDir = $this->questionHelper->ask($input, $output, $question);

        $content = file_get_contents($this->tmplDir . '/.jedi.php');
        $content = str_replace(
            ['%web-dir%', '%env-dir%'],
            [addslashes($webDir), addslashes($this->envDir)],
            $content
        );
        $fs->dumpFile($path, $content);

        $output->writeln('    Created configuration file of application <comment>' . $path . '</comment>');
    }
835684
private function doAsk(OutputInterface $output, Question $question)
    {
        $this->writePrompt($output, $question);

        $inputStream = $this->inputStream ?: STDIN;
        $autocomplete = $question->getAutocompleterCallback();

        if (null === $autocomplete || !$this->hasSttyAvailable()) {
            $ret = false;
            if ($question->isHidden()) {
                try {
                    $ret = trim($this->getHiddenResponse($output, $inputStream));
                } catch (RuntimeException $e) {
                    if (!$question->isHiddenFallback()) {
                        throw $e;
                    }
                }
            }

            if (false === $ret) {
                $ret = fgets($inputStream, 4096);
                if (false === $ret) {
                    throw new RuntimeException('Aborted.');
                }
                $ret = trim($ret);
            }
        } else {
            $ret = trim($this->autocomplete($output, $question, $inputStream, $autocomplete));
        }

        if ($output instanceof ConsoleSectionOutput) {
            $output->addContent($ret);
        }

        $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();

        if ($normalizer = $question->getNormalizer()) {
            return $normalizer($ret);
        }

        return $ret;
    }
893083
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->setManagerFactory($this->getContainer()->get('symfonyid.admin.manager.manager_factory'));
        $questionHelper = $this->getQuestionHelper();

        $this->interactive($input, $output);

        $forceOverwrite = $input->getOption('overwrite');
        $onlyForm = $input->getOption('only-form');
        $onlyController = $input->getOption('only-controller');
        if ($model = $input->getArgument('model')) {
            $this->generate($output, $model, $forceOverwrite);
        } else {
            if ($input->isInteractive()) {
                $question = new ConfirmationQuestion($questionHelper->getQuestion('Are you sure generate crud from all models', 'yes', '?'), true);
                if (!$questionHelper->ask($input, $output, $question)) {
                    $output->writeln('<error>Command aborted</error>');

                    return 1;
                }
            }

            $bundles = $this->getContainer()->getParameter('symfonyid.admin.bundles');
            foreach ($bundles as $bundle) {
                $bundle = $this->getContainer()->get('kernel')->getBundle($bundle);

                $finder = new Finder();
                $finder->name('*.php')->in(array($bundle->getPath().'/Entity', $bundle->getPath().'/Document'));

                $this->findModelAndGenerate($finder, $bundle, $output, $forceOverwrite, $onlyForm, $onlyController);
            }
        }

        /** @var KernelInterface $kernel */
        $kernel = $this->getContainer()->get('kernel');
        $cacheClearCommand = $this->getApplication()->find('cache:clear');
        $cacheClearCommand->run(new ArrayInput(array('--env' => $kernel->getEnvironment())), $output);

        $output->writeln('<info>CRUD Generation is successfully!</info>');
    }
663018
private function askForResources(InputInterface $input, OutputInterface $output) {
        $question = new ChoiceQuestion(
            'Which resources should the public key have access to? ',
            [
                self::RESOURCES_READ_ONLY,
                self::RESOURCES_READ_WRITE,
                self::RESOURCES_ALL,
                self::RESOURCES_SPECIFIC,
                self::RESOURCES_CUSTOM,
            ],
            self::RESOURCES_SPECIFIC
        );

        $type = $this->getHelper('question')->ask($input, $output, $question);
        switch ($type) {
            case self::RESOURCES_READ_ONLY:
                return Resource::getReadOnlyResources();
            case self::RESOURCES_READ_WRITE:
                return Resource::getReadWriteResources();
            case self::RESOURCES_ALL:
                return Resource::getAllResources();
            case self::RESOURCES_CUSTOM:
                return $this->askForCustomResources($input, $output);
        }

        return $this->askForSpecificResources($input, $output);
    }
30494
public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator)
    {
        $classes = [
            'QueryType' =>[
                'namespace' => 'GraphQL\\Query',
                'template' => 'Query.tpl.php',
                'variables' => [
                    'fields' => []
                ]
            ],
            'MutationType' =>[
                'namespace' => 'GraphQL\\Mutation',
                'template' => 'Mutation.tpl.php',
                'variables' => [
                    'fields' => []
                ]
            ],
            'schema' =>[
                'namespace' => 'GraphQL',
                'template' =>'Schema.tpl.php',
                'variables' => []
            ],
        ];

        $configFile = dirname($this->rootDir).'/config/packages/graphql.yaml';
        if(!is_file($configFile)) {
            $generator->generateFile(
                $configFile,
                dirname(dirname(__FILE__)) . '/Resources/skeleton/graphql.tpl.yaml',
                []
            );
        }

        foreach ($classes as $name => $class) {
            $classNameDetails = $generator->createClassNameDetails(
                $name,
                $class['namespace']
            );

            $generator->generateClass(
                $classNameDetails->getFullName(),
                dirname(dirname(__FILE__)) . '/Resources/skeleton/' . $class['template'],
                $class['variables']
            );

            $generator->writeChanges();
        }

        $this->writeSuccessMessage($io);
        $io->text(
            [
                'Next: Create type (able to generate type from existing Entity).',
                'To create type use "maker:graphql:type"',
            ]
        );
    }
267994
private function askForDocument(InputInterface $input, OutputInterface $output, QuestionHelper $dialog)
    {
        do {
            $retry = true;
            $question = new Question($dialog->getQuestion('The Document shortcut name', $input->getOption('document')), $input->getOption('document'));
            $question->setValidator(array(
                'IsmaAmbrosi\Bundle\GeneratorBundle\Command\Validators',
                'validateDocumentName',
            ), $input->getOption('document'));
            $document = $dialog->ask($input, $output, $question);

            list($bundle, $document) = $this->parseShortcutNotation($document);

            try {
                $b = $this->getKernel()->getBundle($bundle);

                if (!file_exists($b->getPath().'/Document/'.str_replace('\\', '/', $document).'.php')) {
                    $retry = false;
                } else {
                    $output->writeln(sprintf('<bg=red>Document "%s:%s" already exists</>.', $bundle, $document));
                }
            } catch (\Exception $e) {
                $output->writeln(sprintf('<bg=red>Bundle "%s" does not exist.</>', $bundle));
            }
        } while ($retry);
        $input->setOption('document', $bundle.':'.$document);

        return array($bundle, $document);
    }
1109969
public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator)
    {
        if (!$this->workflowRegistry instanceof Registry) {
            throw new Exception('Can not make subject: No workflows were defined');
        }

        $model = $input->getArgument('model');
        $workflow = WorkflowHelper::get($this->workflowRegistry, $model);

        if ($this->subjectManager->hasSubject($model)) {
            $subject = $this->subjectManager->getSubject($model);
            if (class_exists($subject)) {
                $io->text(sprintf('The subject for model %s has been already defined: %s!', $model, $subject));

                return;
            }
        } else {
            $subject = $input->getArgument('subject-class');
        }

        $subjectClassNameDetails = $generator->createClassNameDetails(
            $subject,
            'Subject\\'
        );

        $methods = [];
        foreach ($workflow->getDefinition()->getPlaces() as $place => $status) {
            if ($status) {
                $methods[] = $place;
            }
        }
        foreach ($workflow->getDefinition()->getTransitions() as $transition) {
            $methods[] = $transition->getName();
        }

        $generator->generateClass(
            $subjectClassNameDetails->getFullName(),
            __DIR__.'/../Resources/skeleton/subject/Subject.php.tpl',
            [
                'methods' => array_unique($methods),
                'model' => $model,
            ]
        );

        $generator->writeChanges();

        $this->writeSuccessMessage($io);
        $io->text([
            'Next: Open the new generated subject class and implement places and transitions!',
        ]);
    }
332065
public function generate(ParameterHolder $input, array $output = [])
    {
        $table_oid          = $this->checkRelationInformation();
        $field_information = $this->getFieldInformation($table_oid);
        $primary_key        = $this->getPrimaryKey($table_oid);
        $table_comment      = $this->getTableComment($table_oid);

        if ($table_comment === null) {
            $table_comment = <<<TEXT

Class and fields comments are inspected from table and fields comments. Just add comments in your database and they will appear here.
@see http://www.postgresql.org/docs/9.0/static/sql-comment.html
TEXT;
        }

        $this
            ->outputFileCreation($output)
            ->saveFile(
                $this->filename,
                $this->mergeTemplate(
                    [
                        'namespace'      => $this->namespace,
                        'class_name'     => $input->getParameter('class_name', Inflector::studlyCaps($this->relation)),
                        'relation'       => sprintf("%s.%s", $this->schema, $this->relation),
                        'primary_key'    => join(
                            ', ',
                            array_map(
                                function ($val) { return sprintf("'%s'", $val); },
                                $primary_key
                            )
                        ),
                        'add_fields'     => $this->formatAddFields($field_information),
                        'table_comment'  => $this->createPhpDocBlockFromText($table_comment),
                        'fields_comment' => $this->formatFieldsComment($field_information),
                    ]
                )
            );

        return $output;
    }
268890
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->applicationConfig->validate();
        $this->injectOutputIntoLogger($output, $this->logger);
        $this->applicationDestroyer->setLogger($this->logger);
        $appName = $this->applicationConfig->getAppName();

        if (!$input->getOption('force')) {
            /** @var QuestionHelper $helper */
            $helper = $this->getHelper('question');
            $question = new ConfirmationQuestion(
                sprintf(
                    '<question>Are you sure you want to destroy deployment of application "%s"? [y/N]</question>',
                    $appName
                ),
                false
            );

            if (!$helper->ask($input, $output, $question)) {
                return 0;
            }
        }

        $this->logger->info("Destroying deployment of application \"$appName\".");
        $this->applicationDestroyer->destroy();
        $this->logger->info("Deployment of application \"$appName\" destroyed.");
        return 0;
    }
962488
protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $styles = [
            // ---------------------------------------
            // Style    => [ Color, BgColor, Options ]
            // ---------------------------------------
            'title'     => [ 'white', null, ['bold'] ],
            'info'      => [ 'cyan' ],
            'warn'      => [ 'yellow', null, ['bold'] ],
            'erro'      => [ 'red', null, ['bold'] ],
            'success'   => [ 'green' ],
            'failure'   => [ 'yellow' ],
            'label'     => [ 'cyan', null, ['underscore'] ],
            'comment'   => [ 'white', null, ['reverse'] ],
            'highlight' => [ 'yellow' ],
        ];

        foreach ($styles as $name => $style) {
            $output->getFormatter()->setStyle(
                $name,
                Reflection::newInstance(
                    OutputFormatterStyle::class,
                    $style
                )
            );
        }

        $this->output = new OutputStyle($input, $output);
    }
217528
private function promptOption(InputInterface $input, OutputInterface $output, $questionText, $default)
    {
        $questionHelper = $this->getQuestionHelper();
        $question = new Question($questionHelper->getQuestion($questionText, $default), $default);
        return $questionHelper->ask($input, $output, $question);
    }