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

GeneratorBundle/Helper/InputAssistant.php (6 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
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);
0 ignored issues
show
$text is of type array, 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...
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)
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
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.
171
     * @param string $namespace An optional namespace. If this is set it'll create the default based on this prefix.
0 ignored issues
show
Should the type for parameter $namespace not be string|null?

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.

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

Loading history...
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.
0 ignored issues
show
Should the return type not be null|string|string[]|boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
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);
0 ignored issues
show
$text is of type null|array, 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...
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
0 ignored issues
show
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
228
     */
229 View Code Duplication
    private function convertNamespaceToSnakeCase($namespace)
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...
230
    {
231
        if (is_null($namespace)) {
232
            return null;
233
        }
234
235
        return str_replace('/', '_', strtolower($this->fixNamespace($namespace)));
236
    }
237
}
238