Completed
Push — master ( 1de9b7...830752 )
by Kristof
38:46 queued 24:09
created

Command/GenerateFormPageCommand.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\FormPageGenerator;
6
use Symfony\Component\Console\Input\ArrayInput;
7
use Symfony\Component\Console\Input\InputOption;
8
use Symfony\Component\Console\Output\ConsoleOutput;
9
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
10
11
/**
12
 * Generates a new formPage
13
 */
14
class GenerateFormPageCommand extends KunstmaanGenerateCommand
15
{
16
    /**
17
     * @var BundleInterface
18
     */
19
    private $bundle;
20
21
    /**
22
     * @var string
23
     */
24
    private $prefix;
25
26
    /**
27
     * @var string
28
     */
29
    private $pageName;
30
31
    /**
32
     * @var array
33
     */
34
    private $fields;
35
36
    /**
37
     * @var array
38
     */
39
    private $template;
40
41
    /**
42
     * @var array
43
     */
44
    private $sections = [];
45
46
    /**
47
     * @var array
48
     */
49
    private $parentPages = [];
50
51
    /**
52
     * @var bool
53
     */
54
    private $generateFormPageParts;
55
56
    /**
57
     * @see Command
58
     */
59
    protected function configure()
60
    {
61
        $this->setDescription('Generates a new formpage')
62
            ->setHelp(<<<'EOT'
63
The <info>kuma:generate:formpage</info> command generates a new formpage and its configuration.
64
65
<info>php bin/console kuma:generate:formpage</info>
66
EOT
67
            )
68
            ->addOption('prefix', '', InputOption::VALUE_OPTIONAL, 'The prefix to be used in the table name of the generated entity')
69
            ->setName('kuma:generate:formpage');
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    protected function getWelcomeText()
76
    {
77
        return 'Welcome to the Kunstmaan formpage generator';
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    protected function doExecute()
84
    {
85
        $this->assistant->writeSection('FormPage generation');
86
        $this->template = strtolower($this->pageName);
0 ignored issues
show
Documentation Bug introduced by
It seems like strtolower($this->pageName) of type string is incompatible with the declared type array of property $template.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
87
        $this->sections = array(strtolower($this->pageName));
88
89
        // Generate the default form pageparts if requested.
90
        if ($this->generateFormPageParts) {
91
            $command = $this->getApplication()->find('kuma:generate:form-pageparts');
92
            $arguments = [
93
                'command' => 'kuma:generate:form-pageparts',
94
                '--namespace' => str_replace('\\', '/', $this->bundle->getNamespace()),
95
                '--prefix' => $this->prefix,
96
                '--quiet' => false,
97
            ];
98
99
            $output = new ConsoleOutput(ConsoleOutput::VERBOSITY_DEBUG);
100
            $input = new ArrayInput($arguments);
101
            $command->run($input, $output);
102
            $this->assistant->writeLine('Generating default form pageparts : <info>OK</info>');
103
        }
104
105
        $this->createGenerator()->generate($this->bundle, $this->pageName, $this->prefix, $this->fields, $this->template, $this->sections, $this->parentPages, $this->generateFormPageParts);
106
107
        $this->assistant->writeSection('FormPage successfully created', 'bg=green;fg=black');
108
109 View Code Duplication
        if (count($this->parentPages) == 0) {
110
            $this->assistant->writeLine(array(
111
                'To use this page you must first add the definition below to the <comment>getPossibleChildTypes</comment> funtion of the parent page:',
112
                '<comment>    array(</comment>',
113
                "<comment>        'name' => '".$this->pageName."',</comment>",
114
                "<comment>        'class'=> '".$this->bundle->getNamespace().'\\Entity\\Pages\\'.$this->pageName."'</comment>",
115
                '<comment>    ),</comment>',
116
                '',
117
            ));
118
        }
119
120
        $this->assistant->writeLine(array(
121
            'Make sure you update your database first before you use the page:',
122
            '    Directly update your database:          <comment>bin/console doctrine:schema:update --force</comment>',
123
            '    Create a Doctrine migration and run it: <comment>bin/console doctrine:migrations:diff && bin/console doctrine:migrations:migrate</comment>',
124
            '',
125
        ));
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    protected function doInteract()
132
    {
133
        if (!$this->isBundleAvailable('KunstmaanPagePartBundle')) {
134
            $this->assistant->writeError('KunstmaanPagePartBundle not found', true);
135
        }
136
137
        $this->assistant->writeLine(array("This command helps you to generate a new formpage.\n"));
138
139
        /*
140
         * Ask for which bundle we need to create the pagepart
141
         */
142
        $this->bundle = $this->askForBundleName('page');
143
144
        /*
145
         * Ask the database table prefix
146
         */
147
        $this->prefix = $this->askForPrefix(null, $this->bundle->getNamespace());
148
149
        /*
150
         * Ask the name of the pagepart
151
         */
152
        $this->assistant->writeLine(array(
153
            '',
154
            'The name of your FormPage: For example: <comment>ContactPage</comment>, <comment>OrderPage</comment>',
155
            '',
156
        ));
157
        $generator = $this->getGenerator();
158
        $bundlePath = $this->bundle->getPath();
159
160
        $name = $this->assistant->askAndValidate(
161
            'FormPage name',
162 View Code Duplication
            function ($name) use ($generator, $bundlePath) {
163
                // Check reserved words
164
                if ($generator->isReservedKeyword($name)) {
165
                    throw new \InvalidArgumentException(sprintf('"%s" is a reserved word', $name));
166
                }
167
168
                // Name should end on Page
169
                if (!preg_match('/Page$/', $name)) {
170
                    throw new \InvalidArgumentException('The page name must end with Page');
171
                }
172
173
                // Name should contain more characters than Page
174
                if (strlen($name) <= strlen('Page') || !preg_match('/^[a-zA-Z]+$/', $name)) {
175
                    throw new \InvalidArgumentException('Invalid page name');
176
                }
177
178
                // Check that entity does not already exist
179
                if (file_exists($bundlePath . '/Entity/Pages/' . $name . '.php')) {
180
                    throw new \InvalidArgumentException(sprintf('Page or entity "%s" already exists', $name));
181
                }
182
183
                return $name;
184
            }
185
        );
186
        $this->pageName = $name;
187
188
        /*
189
         * Ask which fields need to be present
190
         */
191
        $this->assistant->writeLine(array("\nInstead of starting with a blank page, you can add some fields now.\n"));
192
        $fields = $this->askEntityFields($this->bundle, array('title', 'pageTitle', 'parent', 'id', 'thanks', 'subject', 'fromEmail', 'toEmail'));
193
        $this->fields = array();
194
        foreach ($fields as $fieldInfo) {
195
            $this->fields[] = $this->getEntityFields($this->bundle, $this->pageName, $this->prefix, $fieldInfo['name'], $fieldInfo['type'], $fieldInfo['extra'], true);
196
        }
197
198
        /**
199
         * Ask the parent pages
200
         */
201
        $parentPages = $this->getAvailablePages($this->bundle);
202
        $pagesSelect = array_map(function ($item) {
203
            return $item['name'];
204
        }, $parentPages);
205 View Code Duplication
        if (count($pagesSelect) > 0) {
206
            $this->assistant->writeLine('');
207
            $parentPageIds = $this->assistant->askSelect('Which existing page(s) can have the new page as sub-page (multiple possible, separated by comma)', $pagesSelect, null, true);
208
            foreach ($parentPageIds as $id) {
209
                $this->parentPages[] = $parentPages[$id]['path'];
210
            }
211
        }
212
213
        // Ask if you want to generate form pageparts.
214
        $this->generateFormPageParts = $this->assistant->askConfirmation('Do you want to generate default form pageparts in your bundle? (y/n)', 'y');
215
    }
216
217
    /**
218
     * Get the generator.
219
     *
220
     * @return FormPageGenerator
221
     */
222 View Code Duplication
    protected function createGenerator()
223
    {
224
        $filesystem = $this->getContainer()->get('filesystem');
225
        $registry = $this->getContainer()->get('doctrine');
226
227
        return new FormPageGenerator($filesystem, $registry, '/page', $this->assistant, $this->getContainer());
228
    }
229
}
230