Completed
Push — master ( aba493...5356ed )
by Ruud
315:38 queued 305:00
created

Command/GenerateAdminListCommand.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\GeneratorBundle\Command;
4
5
use Kunstmaan\GeneratorBundle\Generator\AdminListGenerator;
6
use Kunstmaan\GeneratorBundle\Helper\EntityValidator;
7
use Kunstmaan\GeneratorBundle\Helper\GeneratorUtils;
8
use Kunstmaan\GeneratorBundle\Helper\Sf4AppBundle;
9
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCommand;
10
use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Question\ConfirmationQuestion;
15
use Symfony\Component\Console\Question\Question;
16
use Symfony\Component\HttpKernel\Bundle\Bundle;
17
use Symfony\Component\HttpKernel\Kernel;
18
19
/**
20
 * Generates a KunstmaanAdminList
21
 */
22
class GenerateAdminListCommand extends GenerateDoctrineCommand
23
{
24
    /**
25
     * @see Command
26
     */
27
    protected function configure()
28
    {
29
        $this
30
            ->setDefinition(
31
                array(
32
                    new InputOption(
33
                        'entity',
34
                        '',
35
                        InputOption::VALUE_REQUIRED,
36
                        'The entity class name to create an admin list for (shortcut notation)'
37
                    ),
38
                    new InputOption(
39
                        'sortfield',
40
                        '',
41
                        InputOption::VALUE_OPTIONAL,
42
                        'The name of the sort field if entity needs to be sortable'
43
                    ),
44
                )
45
            )
46
            ->setDescription('Generates a KunstmaanAdminList')
47
            ->setHelp(
48
                <<<'EOT'
49
                The <info>kuma:generate:adminlist</info> command generates an AdminList for a Doctrine ORM entity.
50
51
<info>php bin/console kuma:generate:adminlist Bundle:Entity</info>
52
EOT
53
            )
54
            ->setName('kuma:generate:adminlist');
55
    }
56
57
    /**
58
     * Executes the command.
59
     *
60
     * @param InputInterface  $input  An InputInterface instance
61
     * @param OutputInterface $output An OutputInterface instance
62
     *
63
     * @throws \RuntimeException
64
     *
65
     * @return int|null|void
66
     */
67
    protected function execute(InputInterface $input, OutputInterface $output)
68
    {
69
        $questionHelper = $this->getQuestionHelper();
70
71
        GeneratorUtils::ensureOptionsProvided($input, array('entity'));
72
73
        $entity = EntityValidator::validate($input->getOption('entity'));
74
        if (Kernel::VERSION_ID < 40000) {
75
            list($bundle, $entity) = $this->parseShortcutNotation($entity);
76
77
            $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle) . '\\' . $entity;
78
            $metadata = $this->getEntityMetadata($entityClass)[0];
79
            $bundle = $this->getContainer()->get('kernel')->getBundle($bundle);
80
        } else {
81
            $entityClass = $entity;
82
            $em = $this->getContainer()->get('doctrine')->getManager();
83
84
            $metadata = $em->getClassMetadata($entityClass);
85
            $bundle = new Sf4AppBundle($this->getContainer()->getParameter('kernel.project_dir'));
86
        }
87
88
        $questionHelper->writeSection($output, 'AdminList Generation');
89
90
        $generator = $this->getGenerator($this->getApplication()->getKernel()->getBundle('KunstmaanGeneratorBundle'));
91
        $generator->setQuestion($questionHelper);
92
        $generator->generate($bundle, $entityClass, $metadata, $output, $input->getOption('sortfield'));
93
94
        if (Kernel::VERSION_ID >= 40000) {
95
            return;
96
        }
97
98
        $parts = explode('\\', $entity);
99
        $entityClass = array_pop($parts);
100
101
        $this->updateRouting($questionHelper, $input, $output, $bundle, $entityClass);
102
    }
103
104
    /**
105
     * Interacts with the user.
106
     *
107
     * @param InputInterface  $input  An InputInterface instance
108
     * @param OutputInterface $output An OutputInterface instance
109
     */
110
    protected function interact(InputInterface $input, OutputInterface $output)
111
    {
112
        $questionHelper = $this->getQuestionHelper();
113
        $questionHelper->writeSection($output, 'Welcome to the Kunstmaan admin list generator');
114
115
        // entity
116
        $entity = null;
117
118
        try {
119
            $entity = $input->getOption('entity') ? EntityValidator::validate($input->getOption('entity')) : null;
120
        } catch (\Exception $error) {
121
            $output->writeln(
122
                $questionHelper->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error')
123
            );
124
        }
125
126
        if (Kernel::VERSION_ID < 40000) {
127
            $message = 'You must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.';
128
        } else {
129
            $message = 'You must use the FQCN like <comment>\App\Entity\Post</comment>.';
130
        }
131
132
        if (is_null($entity)) {
133
            $output->writeln(
134
                array(
0 ignored issues
show
array('', 'This command ...ty.', '', $message, '') is of type array<integer,string,{"0..."string","4":"string"}>, but the function expects a string|object<Symfony\Co...onsole\Output\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
135
                    '',
136
                    'This command helps you to generate an admin list for your entity.',
137
                    '',
138
                    $message,
139
                    '',
140
                )
141
            );
142
143
            if (Kernel::VERSION_ID < 40000) {
144
                $message = 'The entity shortcut name';
145
            } else {
146
                $message = 'The entity FQCN';
147
            }
148
149
            $question = new Question($questionHelper->getQuestion($message, $entity), $entity);
150
            $question->setValidator(['\Kunstmaan\GeneratorBundle\Helper\EntityValidator', 'validate']);
151
            $entity = $questionHelper->ask($input, $output, $question);
152
            $input->setOption('entity', $entity);
153
154
            $question = new Question($questionHelper->getQuestion('The name of the sort field if entity needs to be sortable', false, '?'), false);
155
            $sortfield = $questionHelper->ask($input, $output, $question);
156
            $input->setOption('sortfield', $sortfield);
157
        }
158
    }
159
160
    /**
161
     * @param QuestionHelper  $questionHelper The question helper
162
     * @param InputInterface  $input          The command input
163
     * @param OutputInterface $output         The command output
164
     * @param Bundle          $bundle         The bundle
165
     * @param string          $entityClass    The classname of the entity
166
     */
167
    protected function updateRouting(
168
        QuestionHelper $questionHelper,
169
        InputInterface $input,
170
        OutputInterface $output,
171
        Bundle $bundle,
172
        $entityClass
173
    ) {
174
        $adminKey = $this->getContainer()->getParameter('kunstmaan_admin.admin_prefix');
175
        $auto = true;
176
        $multilang = false;
177
        if ($input->isInteractive()) {
178
            $confirmationQuestion = new ConfirmationQuestion(
179
                $questionHelper->getQuestion('Is it a multilanguage site', 'yes', '?'), true
180
            );
181
            $multilang = $questionHelper->ask($input, $output, $confirmationQuestion);
182
            $confirmationQuestion = new ConfirmationQuestion(
183
                $questionHelper->getQuestion('Do you want to update the routing automatically', 'yes', '?'), true
184
            );
185
            $auto = $questionHelper->ask($input, $output, $confirmationQuestion);
186
        }
187
188
        $prefix = $multilang ? '/{_locale}' : '';
189
190
        $code = sprintf("%s:\n", strtolower($bundle->getName()) . '_' . strtolower($entityClass) . '_admin_list');
191
        $code .= sprintf("    resource: '@%s/Controller/%sAdminListController.php'\n", $bundle->getName(), $entityClass, "'");
192
        $code .= "    type:     annotation\n";
193
        $code .= sprintf("    prefix:   %s/%s/%s/\n", $prefix, $adminKey, strtolower($entityClass));
194
        if ($multilang) {
195
            $code .= "    requirements:\n";
196
            $code .= "         _locale: \"%requiredlocales%\"\n";
197
        }
198
199
        if ($auto) {
200
            $file = $bundle->getPath() . '/Resources/config/routing.yml';
201
            $content = '';
202
203
            if (file_exists($file)) {
204
                $content = file_get_contents($file);
205
            } elseif (!is_dir($dir = dirname($file))) {
206
                mkdir($dir, 0777, true);
207
            }
208
209
            $content .= "\n";
210
            $content .= $code;
211
212
            if (false === file_put_contents($file, $content)) {
213
                $output->writeln(
214
                    $questionHelper->getHelperSet()->get('formatter')->formatBlock(
215
                        'Failed adding the content automatically',
216
                        'error'
217
                    )
218
                );
219
            } else {
220
                return;
221
            }
222
        }
223
224
        $output->writeln('Add the following to your routing.yml');
225
        $output->writeln('/*******************************/');
226
        $output->write($code);
227
        $output->writeln('/*******************************/');
228
    }
229
230
    /**
231
     * KunstmaanTestBundle_TestEntity:
232
     * resource: "@KunstmaanTestBundle/Controller/TestEntityAdminListController.php"
233
     * type:     annotation
234
     * prefix:   /{_locale}/%kunstmaan_admin.admin_prefix%/testentity/
235
     * requirements:
236
     * _locale: "%requiredlocales%"
237
     */
238
    protected function createGenerator()
239
    {
240
        return new AdminListGenerator(GeneratorUtils::getFullSkeletonPath('adminlist'));
241
    }
242
}
243