Completed
Pull Request — master (#2094)
by Sander
50:34 queued 34:10
created

Command/GenerateFormPageCommand.php (4 issues)

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

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
            $this->assistant->writeLine(array(
87
                "To use this page you must first add the definition below to the <comment>getPossibleChildTypes</comment> funtion of the parent page:",
88
                "<comment>    array(</comment>",
89
                "<comment>        'name' => '".$this->pageName."',</comment>",
90
                "<comment>        'class'=> '".$this->bundle->getNamespace()."\\Entity\\Pages\\".$this->pageName."'</comment>",
91
                "<comment>    ),</comment>",
92
                ""
93
            ));
94
        }
95
96
        $this->assistant->writeLine(array(
97
            'Make sure you update your database first before you use the page:',
98
            '    Directly update your database:          <comment>bin/console doctrine:schema:update --force</comment>',
99
            '    Create a Doctrine migration and run it: <comment>bin/console doctrine:migrations:diff && bin/console doctrine:migrations:migrate</comment>',
100
            ''
101
        ));
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    protected function doInteract()
108
    {
109
        if (!$this->isBundleAvailable('KunstmaanPagePartBundle')) {
110
            $this->assistant->writeError('KunstmaanPagePartBundle not found', true);
111
        }
112
113
        $this->assistant->writeLine(array("This command helps you to generate a new formpage.\n"));
114
115
        /**
116
         * Ask for which bundle we need to create the pagepart
117
         */
118
        $this->bundle = $this->askForBundleName('page');
119
120
        /**
121
         * Ask the database table prefix
122
         */
123
        $this->prefix = $this->askForPrefix(null, $this->bundle->getNamespace());
124
125
        /**
126
         * Ask the name of the pagepart
127
         */
128
        $this->assistant->writeLine(array(
129
            '',
130
            'The name of your FormPage: For example: <comment>ContactPage</comment>, <comment>OrderPage</comment>',
131
            '',
132
        ));
133
        $generator = $this->getGenerator();
134
        $bundlePath = $this->bundle->getPath();
135
136
        $name = $this->assistant->askAndValidate(
137
            'FormPage name',
138 View Code Duplication
            function ($name) use ($generator, $bundlePath) {
139
                // Check reserved words
140
                if ($generator->isReservedKeyword($name)){
141
                    throw new \InvalidArgumentException(sprintf('"%s" is a reserved word', $name));
142
                }
143
144
                // Name should end on Page
145
                if (!preg_match('/Page$/', $name)) {
146
                    throw new \InvalidArgumentException('The page name must end with Page');
147
                }
148
149
                // Name should contain more characters than Page
150
                if (strlen($name) <= strlen('Page') || !preg_match('/^[a-zA-Z]+$/', $name)) {
151
                    throw new \InvalidArgumentException('Invalid page name');
152
                }
153
154
                // Check that entity does not already exist
155
                if (file_exists($bundlePath . '/Entity/Pages/' . $name . '.php')) {
156
                    throw new \InvalidArgumentException(sprintf('Page or entity "%s" already exists', $name));
157
                }
158
159
                return $name;
160
            }
161
        );
162
        $this->pageName = $name;
163
164
        /**
165
         * Ask which fields need to be present
166
         */
167
        $this->assistant->writeLine(array("\nInstead of starting with a blank page, you can add some fields now.\n"));
168
        $fields = $this->askEntityFields($this->bundle, array('title', 'pageTitle', 'parent', 'id', 'thanks', 'subject', 'fromEmail', 'toEmail'));
169
        $this->fields = array();
170
        foreach ($fields as $fieldInfo) {
171
            $this->fields[] = $this->getEntityFields($this->bundle, $this->pageName, $this->prefix, $fieldInfo['name'], $fieldInfo['type'], $fieldInfo['extra'], true);
172
        }
173
174
        /**
175
         * Ask the parent pages
176
         */
177
        $parentPages = $this->getAvailablePages($this->bundle);
178
        $pagesSelect = array_map(function ($item) { return $item['name']; }, $parentPages);
179 View Code Duplication
        if (count($pagesSelect) > 0) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
            $this->assistant->writeLine('');
181
            $parentPageIds = $this->assistant->askSelect('Which existing page(s) can have the new page as sub-page (multiple possible, separated by comma)', $pagesSelect, null, true);
182
            foreach ($parentPageIds as $id) {
0 ignored issues
show
The expression $parentPageIds of type array|false|integer|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
183
                $this->parentPages[] = $parentPages[$id]['path'];
184
            }
185
        }
186
    }
187
188
    /**
189
     * Get the generator.
190
     *
191
     * @return FormPageGenerator
192
     */
193
    protected function createGenerator()
194
    {
195
        $filesystem = $this->getContainer()->get('filesystem');
196
        $registry = $this->getContainer()->get('doctrine');
197
198
        return new FormPageGenerator($filesystem, $registry, '/page', $this->assistant);
199
    }
200
}
201