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

GeneratorBundle/Command/GenerateEntityCommand.php (5 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\DefaultEntityGenerator;
6
use Symfony\Component\Console\Input\InputOption;
7
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
8
9
/**
10
 * GenerateEntityCommand
11
 */
12
class GenerateEntityCommand 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 $entityName;
28
29
    /**
30
     * @var array
31
     */
32
    private $fields;
33
34
    /**
35
     * @var bool
36
     */
37
    private $withRepository;
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    protected function configure()
43
    {
44
        $this
45
            ->setName('kuma:generate:entity')
46
            ->setDescription('Generates a new Doctrine entity inside a bundle')
47
            ->addOption('prefix', '', InputOption::VALUE_OPTIONAL, 'The prefix to be used in the table names of the generated entities')
48
            ->addOption('with-repository', null, InputOption::VALUE_NONE, 'Whether to generate the entity repository or not (y/n)')
49
            ->setHelp(<<<'EOT'
50
The <info>kuma:generate:entity</info> task generates a new entity inside a bundle:
51
52
<info>php bin/console kuma:generate:entity</info>
53
54
The command can also generate the corresponding entity repository class with the
55
<comment>--with-repository</comment> option:
56
57
<info>php bin/console kuma:generate:entity --with-repository</info>
58
59
Use the <info>--prefix</info> option to add a prefix to the table names of the generated entities
60
61
<info>php bin/console kuma:generate:entity --prefix=demo_</info>
62
EOT
63
            );
64
    }
65
66
    /**
67
     * @return DefaultEntityGenerator
68
     */
69 View Code Duplication
    protected function createGenerator()
0 ignored issues
show
This method seems to be duplicated in 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...
70
    {
71
        $filesystem = $this->getContainer()->get('filesystem');
72
        $registry = $this->getContainer()->get('doctrine');
73
74
        return new DefaultEntityGenerator($filesystem, $registry, '/entity', $this->assistant, $this->getContainer());
75
    }
76
77
    /**
78
     * The text to be displayed on top of the generator.
79
     *
80
     * @return string|array
81
     */
82
    protected function getWelcomeText()
83
    {
84
        return 'Welcome to the Kunstmaan entity generator';
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    protected function doExecute()
91
    {
92
        $this->assistant->writeSection('Entity generation');
93
94
        $this->createGenerator()->generate($this->bundle, $this->entityName, $this->prefix, $this->fields, $this->withRepository);
95
96
        $this->assistant->writeSection('Entity successfully created', 'bg=green;fg=black');
97
        $this->assistant->writeLine(array(
98
            'Make sure you update your database first before you test the entity:',
99
            '    Directly update your database:          <comment>bin/console doctrine:schema:update --force</comment>',
100
            '    Create a Doctrine migration and run it: <comment>bin/console doctrine:migrations:diff && app/console doctrine:migrations:migrate</comment>',
101
        ));
102
    }
103
104
    /**
105
     * Do the interaction with the end user.
106
     */
107
    protected function doInteract()
108
    {
109
        $this->assistant->writeLine(array("This command helps you to generate a new entity.\n"));
110
111
        /*
112
         * Ask for which bundle we need to create the pagepart
113
         */
114
        $this->bundle = $this->askForBundleName('entity');
115
116
        /*
117
         * Ask the database table prefix
118
         */
119
        $this->prefix = $this->askForPrefix(null, $this->bundle->getNamespace());
120
121
        /*
122
         * Ask the name of the pagepart
123
         */
124
        $this->assistant->writeLine(array(
125
            '',
126
            'The name of your Entity: For example: <comment>Address</comment>',
127
            '',
128
        ));
129
        $generator = $this->getGenerator();
130
        $bundlePath = $this->bundle->getPath();
131
        $name = $this->assistant->askAndValidate(
132
            'Entity name',
133
            function ($name) use ($generator, $bundlePath) {
134
                // Check reserved words
135
                if ($generator->isReservedKeyword($name)) {
136
                    throw new \InvalidArgumentException(sprintf('"%s" is a reserved word', $name));
137
                }
138
139
                if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name)) {
140
                    throw new \InvalidArgumentException(sprintf('Invalid entity name: %s', $name));
141
                }
142
143
                // Check that entity does not already exist
144
                if (file_exists($bundlePath.'/Entity/'.$name.'.php')) {
145
                    throw new \InvalidArgumentException(sprintf('Entity "%s" already exists', $name));
146
                }
147
148
                return $name;
149
            }
150
        );
151
        $this->entityName = $name;
152
153
        /*
154
         * Ask which fields need to be present
155
         */
156
        $this->assistant->writeLine(array("\nInstead of starting with a blank entity, you can add some fields now.\n"));
157
        $fields = $this->askEntityFields($this->bundle);
158
        $this->fields = array_map(function ($fieldInfo) {
159
            switch ($fieldInfo['type']) {
160
                case 'image':
161
                    return $this->getEntityFields($this->bundle, $this->entityName, $this->prefix, $fieldInfo['name'], $fieldInfo['type'],
162
                        $fieldInfo['extra'], true, $fieldInfo['minHeight'], $fieldInfo['maxHeight'], $fieldInfo['minWidth'], $fieldInfo['maxWidth'], $fieldInfo['mimeTypes']);
163
164
                    break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
165
166
                case 'media':
167
                    return $this->getEntityFields($this->bundle, $this->entityName, $this->prefix, $fieldInfo['name'], $fieldInfo['type'],
168
                        $fieldInfo['extra'], true, null, null, null, null, $fieldInfo['mimeTypes']);
169
170
                    break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
171
172
                default:
173
                    return $this->getEntityFields($this->bundle, $this->entityName, $this->prefix, $fieldInfo['name'], $fieldInfo['type'], $fieldInfo['extra'], true);
174
175
                    break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
176
            }
177
        }, $fields);
178
179
        /*
180
         * Ask if a repository class needs to be generated
181
         */
182
        $this->withRepository = $this->askForWithRepository();
183
    }
184
185
    /**
186
     * @return bool
187
     */
188 View Code Duplication
    protected function askForWithRepository()
0 ignored issues
show
This method seems to be duplicated in 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...
189
    {
190
        $withRepositoryOption = $this->assistant->getOption('with-repository');
191
        if ($withRepositoryOption != 'y' && $withRepositoryOption != 'n') {
192
            /** @var $question */
193
            $withRepositoryOption = $this->assistant->askConfirmation("\nDo you want to generate a repository class for the entity ? (y/n)\n", '', '?', false);
194
        }
195
196
        return $withRepositoryOption == 'y';
197
    }
198
}
199