GenerateCommand::generate()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 8.6488
c 0
b 0
f 0
cc 5
nc 5
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\EasyExtendsBundle\Command;
15
16
use Sonata\EasyExtendsBundle\Bundle\BundleMetadata;
17
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
18
use Symfony\Component\Console\Input\InputArgument;
19
use Symfony\Component\Console\Input\InputInterface;
20
use Symfony\Component\Console\Input\InputOption;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
23
24
/**
25
 * Generate Application entities from bundle entities.
26
 *
27
 * @author Thomas Rabaix <[email protected]>
28
 */
29
class GenerateCommand extends ContainerAwareCommand
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...d\ContainerAwareCommand has been deprecated with message: since Symfony 4.2, use {@see Command} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
30
{
31
    /**
32
     * {@inheritdoc}
33
     */
34
    protected function configure(): void
35
    {
36
        $this
37
            ->setName('sonata:easy-extends:generate')
38
            ->setHelp(
39
                <<<'EOT'
40
The <info>easy-extends:generate:entities</info> command generating a valid bundle structure from a Vendor Bundle.
41
42
  <info>ie: ./app/console sonata:easy-extends:generate SonataUserBundle</info>
43
EOT
44
            );
45
46
        $this->setDescription('Create entities used by Sonata\'s bundles');
47
48
        $this->addArgument('bundle', InputArgument::IS_ARRAY, 'The bundle name to "easy-extends"');
49
        $this->addOption(
50
            'dest',
51
            'd',
52
            InputOption::VALUE_OPTIONAL,
53
            'The base folder where the Application will be created',
54
            false
55
        );
56
        $this->addOption('namespace', 'ns', InputOption::VALUE_OPTIONAL, 'The namespace for the classes', false);
57
        $this->addOption('namespace_prefix', 'nsp', InputOption::VALUE_OPTIONAL, 'The namespace prefix for the classes', false);
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    protected function execute(InputInterface $input, OutputInterface $output): int
64
    {
65
        $destOption = $input->getOption('dest');
66
        if ($destOption) {
67
            $dest = realpath($destOption);
68
            if (false === $dest) {
69
                throw new \RuntimeException(sprintf(
70
                    'The provided destination folder \'%s\' does not exist!',
71
                    $destOption
72
                ));
73
            }
74
        } else {
75
            $dest = $this->getContainer()->get('kernel')->getRootDir();
76
        }
77
78
        $namespace = $input->getOption('namespace');
79
        if ($namespace) {
80
            if (!preg_match('/^(?:(?:[[:alnum:]]+|:vendor)\\\\?)+$/', $namespace)) {
81
                throw new \InvalidArgumentException(sprintf(
82
                    'The provided namespace "%s" is not a valid namespace!',
83
                    $namespace
84
                ));
85
            }
86
        } else {
87
            $namespace = 'Application\:vendor';
88
        }
89
90
        $configuration = [
91
            'application_dir' => sprintf(
92
                '%s%s%s',
93
                $dest,
94
                \DIRECTORY_SEPARATOR,
95
                str_replace('\\', \DIRECTORY_SEPARATOR, $namespace)
96
            ),
97
            'namespace' => $namespace,
98
            'namespace_prefix' => '',
99
        ];
100
101
        if ($namespacePrefix = $input->getOption('namespace_prefix')) {
102
            $configuration['namespace_prefix'] = rtrim($namespacePrefix, '\\').'\\';
103
        }
104
105
        $bundleNames = $input->getArgument('bundle');
106
107
        if (empty($bundleNames)) {
108
            $output->writeln('');
109
            $output->writeln('<error>You must provide a bundle name!</error>');
110
            $output->writeln('');
111
            $output->writeln('  Bundles availables :');
112
            /** @var BundleInterface $bundle */
113
            foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
114
                $bundleMetadata = new BundleMetadata($bundle, $configuration);
115
116
                if (!$bundleMetadata->isExtendable()) {
117
                    continue;
118
                }
119
120
                $output->writeln(sprintf('     - %s', $bundle->getName()));
121
            }
122
123
            $output->writeln('');
124
        } else {
125
            foreach ($bundleNames as $bundleName) {
0 ignored issues
show
Bug introduced by
The expression $bundleNames of type string|array<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...
126
                $processed = $this->generate($bundleName, $configuration, $output);
127
128
                if (!$processed) {
129
                    throw new \RuntimeException(sprintf(
130
                        '<error>The bundle \'%s\' does not exist or is not registered in the kernel!</error>',
131
                        $bundleName
132
                    ));
133
                }
134
            }
135
        }
136
137
        $output->writeln('done!');
138
139
        return 0;
140
    }
141
142
    /**
143
     * Generates a bundle entities from a bundle name.
144
     */
145
    protected function generate(string $bundleName, array $configuration, OutputInterface $output): bool
146
    {
147
        $processed = false;
148
149
        /** @var BundleInterface $bundle */
150
        foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
151
            if ($bundle->getName() !== $bundleName) {
152
                continue;
153
            }
154
155
            $processed = true;
156
            $bundleMetadata = new BundleMetadata($bundle, $configuration);
157
158
            // generate the bundle file.
159
            if (!$bundleMetadata->isExtendable()) {
160
                $output->writeln(sprintf('Ignoring bundle : "<comment>%s</comment>"', $bundleMetadata->getClass()));
161
162
                continue;
163
            }
164
165
            // generate the bundle file
166
            if (!$bundleMetadata->isValid()) {
167
                $output->writeln(sprintf(
168
                    '%s : <comment>wrong directory structure</comment>',
169
                    $bundleMetadata->getClass()
170
                ));
171
172
                continue;
173
            }
174
175
            $output->writeln(sprintf('Processing bundle : "<info>%s</info>"', $bundleMetadata->getName()));
176
177
            $this->getContainer()->get('sonata.easy_extends.generator.bundle')
178
                ->generate($output, $bundleMetadata);
179
180
            $output->writeln(sprintf('Processing Doctrine ORM : "<info>%s</info>"', $bundleMetadata->getName()));
181
            $this->getContainer()->get('sonata.easy_extends.generator.orm')
182
                ->generate($output, $bundleMetadata);
183
184
            $output->writeln(sprintf('Processing Doctrine ODM : "<info>%s</info>"', $bundleMetadata->getName()));
185
            $this->getContainer()->get('sonata.easy_extends.generator.odm')
186
                ->generate($output, $bundleMetadata);
187
188
            $output->writeln(sprintf('Processing Doctrine PHPCR : "<info>%s</info>"', $bundleMetadata->getName()));
189
            $this->getContainer()->get('sonata.easy_extends.generator.phpcr')
190
                ->generate($output, $bundleMetadata);
191
192
            $output->writeln(sprintf('Processing Serializer config : "<info>%s</info>"', $bundleMetadata->getName()));
193
            $this->getContainer()->get('sonata.easy_extends.generator.serializer')
194
                ->generate($output, $bundleMetadata);
195
196
            $output->writeln('');
197
        }
198
199
        return $processed;
200
    }
201
}
202