Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
created

GeneratorBundle/Helper/InputAssistant.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\Helper;
4
5
use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper;
6
use Sensio\Bundle\GeneratorBundle\Command\Validators;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Symfony\Component\Console\Question\Question;
10
use Symfony\Component\DependencyInjection\ContainerInterface;
11
use Symfony\Component\HttpKernel\Kernel;
12
13
/**
14
 * @deprecated the functions in this class should be moved to the KunstmaanGenerateCommand class
15
 */
16
class InputAssistant
17
{
18
    /** @var InputInterface */
19
    private $input;
20
21
    /** @var OutputInterface */
22
    private $output;
23
24
    /** @var QuestionHelper */
25
    private $questionHelper;
26
27
    /** @var Kernel */
28
    private $kernel;
29
30
    /** @var ContainerInterface */
31
    private $container;
32
33
    public function __construct(InputInterface &$input, OutputInterface $output, QuestionHelper $questionHelper, Kernel $kernel, ContainerInterface $container)
34
    {
35
        $this->input = $input;
36
        $this->output = $output;
37
        $this->questionHelper = $questionHelper;
38
        $this->kernel = $kernel;
39
        $this->container = $container;
40
    }
41
42
    /**
43
     * Asks for the namespace and sets it on the InputInterface as the 'namespace' option, if this option is not set yet.
44
     *
45
     * @param array $text what you want printed before the namespace is asked
0 ignored issues
show
Should the type for parameter $text not be null|array? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
46
     *
47
     * @return string The namespace. But it's also been set on the InputInterface.
48
     */
49
    public function askForNamespace(array $text = null)
50
    {
51
        $namespace = $this->input->hasOption('namespace') ? $this->input->getOption('namespace') : null;
52
53
        // When the Namespace is filled in return it immediately if valid.
54
        try {
55
            if (!is_null($namespace) && !empty($namespace)) {
56
                Validators::validateBundleNamespace($namespace);
57
58
                return $namespace;
59
            }
60
        } catch (\Exception $error) {
61
            $this->writeError(["Namespace '$namespace' is incorrect. Please provide a correct value.", $error->getMessage()]);
62
            exit;
63
        }
64
65
        $ownBundles = $this->getOwnBundles();
66
        if (count($ownBundles) <= 0) {
67
            $this->writeError("Looks like you don't have created a bundle for your project, create one first.", true);
68
        }
69
70
        $namespace = '';
71
72
        // If we only have 1 or more bundles, we can prefill it.
73
        if (count($ownBundles) > 0) {
74
            $namespace = $ownBundles[1]['namespace'] . '/' . $ownBundles[1]['name'];
75
        }
76
77
        $namespaces = $this->getNamespaceAutoComplete($this->kernel);
78
79
        if (!is_null($text) && (count($text) > 0)) {
80
            $this->output->writeln($text);
81
        }
82
83
        $question = new Question($this->questionHelper->getQuestion('Bundle Namespace', $namespace), $namespace);
84
        $question->setValidator(['Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateBundleNamespace']);
85
        $question->setAutocompleterValues($namespaces);
86
        $namespace = $this->questionHelper->ask($this->input, $this->output, $question);
87
88
        if ($this->input->hasOption('namespace')) {
89
            $this->input->setOption('namespace', $namespace);
90
        }
91
92
        return $namespace;
93
    }
94
95
    /**
96
     * Helper function to display errors in the console.
97
     *
98
     * @param $message
99
     * @param bool $exit
100
     */
101 View Code Duplication
    private function writeError($message, $exit = false)
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...
102
    {
103
        $this->output->writeln($this->questionHelper->getHelperSet()->get('formatter')->formatBlock($message, 'error'));
104
        if ($exit) {
105
            exit;
106
        }
107
    }
108
109
    /**
110
     * Get an array with all the bundles the user has created.
111
     *
112
     * @return array
113
     */
114
    public function getOwnBundles()
115
    {
116
        $bundles = [];
117
        $counter = 1;
118
119
        $dir = dirname($this->container->getParameter('kernel.root_dir') . '/') . '/src/';
120
        $files = scandir($dir);
121
        foreach ($files as $file) {
122
            if (is_dir($dir . $file) && !in_array($file, ['.', '..'])) {
123
                $bundleFiles = scandir($dir . $file);
124
                foreach ($bundleFiles as $bundleFile) {
125
                    if (is_dir($dir . $file . '/' . $bundleFile) && !in_array($bundleFile, ['.', '..'])) {
126
                        $bundles[$counter++] = [
127
                            'name' => $bundleFile,
128
                            'namespace' => $file,
129
                            'dir' => $dir . $file . '/' . $bundleFile,
130
                        ];
131
                    }
132
                }
133
            }
134
        }
135
136
        return $bundles;
137
    }
138
139
    /**
140
     * Returns a list of namespaces as array with a forward slash to split the namespace & bundle.
141
     *
142
     * @return array
143
     */
144
    private function getNamespaceAutoComplete(Kernel $kernel)
145
    {
146
        $ret = [];
147
        foreach ($kernel->getBundles() as $k => $v) {
148
            $ret[] = $this->fixNamespace($v->getNamespace());
149
        }
150
151
        return $ret;
152
    }
153
154
    /**
155
     * Replaces '\' with '/'.
156
     *
157
     * @param $namespace
158
     *
159
     * @return mixed
0 ignored issues
show
Consider making the return type a bit more specific; maybe use string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
160
     */
161
    private function fixNamespace($namespace)
162
    {
163
        return strtr($namespace, ['\\Bundle\\' => '/', '\\' => '/']);
164
    }
165
166
    /**
167
     * Asks for the prefix and sets it on the InputInterface as the 'prefix' option, if this option is not set yet.
168
     * Will set the default to a snake_cased namespace when the namespace has been set on the InputInterface.
169
     *
170
     * @param array  $text      What you want printed before the prefix is asked. If null is provided it'll write a default text.
0 ignored issues
show
Should the type for parameter $text not be null|array? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
171
     * @param string $namespace An optional namespace. If this is set it'll create the default based on this prefix.
172
     *                          If it's not provided it'll check if the InputInterface already has the namespace option.
173
     *
174
     * @return string The prefix. But it's also been set on the InputInterface.
175
     */
176
    public function askForPrefix(array $text = null, $namespace = null)
177
    {
178
        $prefix = $this->input->hasOption('prefix') ? $this->input->getOption('prefix') : null;
179
180
        if (is_null($text)) {
181
            $text = [
182
                '',
183
                'You can add a prefix to the table names of the generated entities for example: <comment>projectname_bundlename_</comment>',
184
                'Enter an underscore \'_\' if you don\'t want a prefix.',
185
                '',
186
            ];
187
        }
188
189
        while (is_null($prefix)) {
190
            if (count($text) > 0) {
191
                $this->output->writeln($text);
192
            }
193
194
            if (is_null($namespace) || empty($namespace)) {
195
                $namespace = $this->input->hasOption('namespace') ? $this->input->getOption('namespace') : null;
196
            } else {
197
                $namespace = $this->fixNamespace($namespace);
198
            }
199
            $defaultPrefix = GeneratorUtils::cleanPrefix($this->convertNamespaceToSnakeCase($namespace));
200
            $question = new Question($this->questionHelper->getQuestion('Tablename prefix', $defaultPrefix), $defaultPrefix);
201
            $prefix = $this->questionHelper->ask($this->input, $this->output, $question);
202
            $prefix = GeneratorUtils::cleanPrefix($prefix);
203
            if ($this->input->hasOption('prefix')) {
204
                $this->input->setOption('prefix', $prefix);
205
            }
206
207
            if ($prefix == '') {
208
                break;
209
            }
210
211 View Code Duplication
            if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $prefix)) {
212
                $this->output->writeln(sprintf('<bg=red> "%s" contains invalid characters</>', $prefix));
213
                $prefix = $text = null;
214
215
                continue;
216
            }
217
        }
218
219
        return $prefix;
220
    }
221
222
    /**
223
     * Converts something like Namespace\BundleNameBundle to namspace_bundlenamebundle.
224
     *
225
     * @param string $namespace
226
     *
227
     * @return string
228
     */
229 View Code Duplication
    private function convertNamespaceToSnakeCase($namespace)
230
    {
231
        if (is_null($namespace)) {
232
            return null;
233
        }
234
235
        return str_replace('/', '_', strtolower($this->fixNamespace($namespace)));
236
    }
237
}
238