Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

GenerateDefaultSiteCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 18
cp 0
rs 9.584
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Kunstmaan\GeneratorBundle\Command;
4
5
use Kunstmaan\GeneratorBundle\Generator\DefaultSiteGenerator;
6
use Symfony\Component\Console\Input\ArrayInput;
7
use Symfony\Component\Console\Input\InputOption;
8
use Symfony\Component\Console\Output\ConsoleOutput;
9
10
/**
11
 * Generates a default website based on Kunstmaan bundles
12
 */
13
class GenerateDefaultSiteCommand extends KunstmaanGenerateCommand
14
{
15
    /**
16
     * @var BundleInterface
17
     */
18
    private $bundle;
19
20
    /**
21
     * @var string
22
     */
23
    private $prefix;
24
25
    /**
26
     * @var bool
27
     */
28
    private $demosite;
29
30
    /**
31
     * @see Command
32
     */
33
    protected function configure()
34
    {
35
        $this
36
            ->setHelp(<<<'EOT'
37
The <info>kuma:generate:site</info> command generates an website using the Kunstmaan bundles
38
39
<info>php bin/console kuma:generate:default-site --namespace=Namespace/NamedBundle</info>
40
41
Use the <info>--prefix</info> option to add a prefix to the table names of the generated entities
42
43
<info>php bin/console kuma:generate:default-site --namespace=Namespace/NamedBundle --prefix=demo_</info>
44
EOT
45
            )
46
            ->setDescription('Generates a basic website based on Kunstmaan bundles with default templates')
47
            ->addOption('namespace', '', InputOption::VALUE_OPTIONAL, 'The namespace to generate the default website in')
48
            ->addOption('prefix', '', InputOption::VALUE_OPTIONAL, 'The prefix to be used in the table names of the generated entities')
49
            ->addOption('demosite', '', InputOption::VALUE_NONE, 'Whether to generate a website with demo contents or a basic website')
50
            ->addOption('browsersync', '', InputOption::VALUE_OPTIONAL, 'The URI that will be used for browsersync to connect')
51
            ->addOption('articleoverviewpageparent', '', InputOption::VALUE_OPTIONAL, 'Shortnames of the pages that can have the article overview page as a child (comma separated)')
52
            ->setName('kuma:generate:default-site');
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    protected function getWelcomeText()
59
    {
60
        return 'Welcome to the Kunstmaan default site generator';
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function doExecute()
67
    {
68
        $this->assistant->writeSection('Site generation');
69
        $this->assistant->writeLine(array("This command helps you to generate a default site setup.\n"));
70
71
        /**
72
         * Ask for which bundle we need to create the layout
73
         */
74
        $bundleNamespace = $this->assistant->getOptionOrDefault('namespace', null);
75
        $this->bundle = $this->askForBundleName('layout', $bundleNamespace);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->askForBundleName(...out', $bundleNamespace) of type object<Symfony\Component...Bundle\BundleInterface> is incompatible with the declared type object<Kunstmaan\Generat...ommand\BundleInterface> of property $bundle.

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...
76
77
        /*
78
         * Ask the database table prefix
79
         */
80
        $this->prefix = $this->askForPrefix(null, $this->bundle->getNamespace());
81
82
        /*
83
         * If we need to generate a full site, or only the basic structure
84
         */
85
        $this->demosite = $this->assistant->getOption('demosite');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->assistant->getOption('demosite') can also be of type string or array<integer,string>. However, the property $demosite is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
86
87
        $browserSyncUrl = $this->assistant->getOptionOrDefault('browsersync', null);
88
89
        // First we generate the layout if it is not yet generated
90
        $command = $this->getApplication()->find('kuma:generate:layout');
91
        $arguments = array(
92
            'command' => 'kuma:generate:layout',
93
            '--namespace' => str_replace('\\', '/', $this->bundle->getNamespace()),
94
            '--demosite' => $this->demosite,
95
            '--browsersync' => $browserSyncUrl,
96
            '--subcommand' => true,
97
        );
98
        $input = new ArrayInput($arguments);
99
        $command->run($input, $this->assistant->getOutput());
100
101
        $rootDir = $this->getApplication()->getKernel()->getProjectDir().'/';
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
102
        $this->createGenerator()->generate($this->bundle, $this->prefix, $rootDir, $this->demosite);
103
104
        // Generate the default pageparts
105
        $command = $this->getApplication()->find('kuma:generate:default-pageparts');
106
        $arguments = array(
107
            'command' => 'kuma:generate:default-pageparts',
108
            '--namespace' => str_replace('\\', '/', $this->bundle->getNamespace()),
109
            '--prefix' => $this->prefix,
110
            '--contexts' => 'main',
111
            '--quiet' => true,
112
        );
113
        $output = new ConsoleOutput(ConsoleOutput::VERBOSITY_QUIET);
114
        $input = new ArrayInput($arguments);
115
        $command->run($input, $output);
116
        $this->assistant->writeLine('Generating default pageparts : <info>OK</info>');
117
118
        if ($this->demosite) {
119
            // Generate a blog
120
            $command = $this->getApplication()->find('kuma:generate:article');
121
            $pages = $this->assistant->getOptionOrDefault('articleoverviewpageparent', null);
122
            $arguments = array(
123
                'command' => 'kuma:generate:article',
124
                '--namespace' => str_replace('\\', '/', $this->bundle->getNamespace()),
125
                '--prefix' => $this->prefix,
126
                '--entity' => 'Blog',
127
                '--with-author' => true,
128
                '--with-category' => true,
129
                '--with-tag' => true,
130
                '--dummydata' => true,
131
                '--articleoverviewpageparent' => $pages,
132
            );
133
            $output = new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL);
134
            $input = new ArrayInput($arguments);
135
            $command->run($input, $output);
136
137
            $this->assistant->writeLine('Generating blog : <info>OK</info>');
138
        }
139
140
        $this->assistant->writeSection('Site successfully created', 'bg=green;fg=black');
141
142
        return 0;
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148
    protected function doInteract()
149
    {
150
    }
151
152
    /**
153
     * Get the generator.
154
     *
155
     * @return DefaultSiteGenerator
156
     */
157 View Code Duplication
    protected function createGenerator()
0 ignored issues
show
Duplication introduced by
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...
158
    {
159
        $filesystem = $this->getContainer()->get('filesystem');
160
        $registry = $this->getContainer()->get('doctrine');
161
162
        return new DefaultSiteGenerator($filesystem, $registry, '/defaultsite', $this->assistant, $this->getContainer());
0 ignored issues
show
Documentation introduced by
$filesystem is of type object|null, but the function expects a object<Symfony\Component\Filesystem\Filesystem>.

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...
Documentation introduced by
$registry is of type object|null, but the function expects a object<Symfony\Bridge\Doctrine\RegistryInterface>.

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...
163
    }
164
}
165