Completed
Push — master ( 550846...8c8483 )
by Anton
09:53
created

CrudCommand::configure()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 13
nc 1
nop 0
1
<?php
2
/**
3
 * @copyright Bluz PHP Team
4
 * @link https://github.com/bluzphp/bluzman
5
 */
6
7
namespace Bluzman\Command\Generate;
8
9
use Bluz\Validator\Validator as v;
10
use Bluzman\Input\InputArgument;
11
use Bluzman\Input\InputException;
12
use Bluzman\Generator;
13
use Symfony\Component\Console\Input\InputInterface;
14
use Symfony\Component\Console\Output\OutputInterface;
15
16
/**
17
 * ModelCommand
18
 *
19
 * @package  Bluzman\Command
20
 */
21
class CrudCommand extends AbstractGenerateCommand
22
{
23
    /**
24
     * Command configuration
25
     */
26
    protected function configure()
27
    {
28
        $this
29
            // the name of the command (the part after "bin/bluzman")
30
            ->setName('generate:crud')
31
            // the short description shown while running "php bin/bluzman list"
32
            ->setDescription('Generate a CRUD for model')
33
            // the full command description shown when running the command with
34
            // the "--help" option
35
            ->setHelp('This command allows you to generate CRUD files')
36
        ;
37
38
        $this->addModelArgument();
39
40
        $module = new InputArgument(
41
            'module',
42
            InputArgument::OPTIONAL,
43
            'Module name, if you need to generate `view` controller and view'
44
        );
45
46
        $module->setValidator(
47
            v::string()->alphaNumeric('-_')->noWhitespace()
48
        );
49
50
51
        $this->getDefinition()->addArgument($module);
52
    }
53
54
    /**
55
     * @param InputInterface $input
56
     * @param OutputInterface $output
57
     * @return void
58
     */
59
    protected function execute(InputInterface $input, OutputInterface $output)
60
    {
61
        try {
62
            $this->write("Running <info>generate:crud</info> command");
63
64
            $model = $input->getArgument('model');
65
            $this->getDefinition()->getArgument('model')->validate($model);
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\Input\InputArgument as the method validate() does only exist in the following sub-classes of Symfony\Component\Console\Input\InputArgument: Bluzman\Input\InputArgument. 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...
66
67
            if (!$this->getApplication()->isModelExists($model)) {
68
                throw new InputException(
69
                    "Model $model is not exist, ".
70
                    "run command <question>bluzman generate:model $model</question> before");
71
            }
72
73
            if ($module = $input->getArgument('module')) {
74
                $this->getDefinition()->getArgument('module')->validate($module);
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\Input\InputArgument as the method validate() does only exist in the following sub-classes of Symfony\Component\Console\Input\InputArgument: Bluzman\Input\InputArgument. 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...
75
76
                if (!$this->getApplication()->isModuleExists($module)) {
77
                    throw new InputException(
78
                        "Module $module is not exist, ".
79
                        "run command <question>bluzman generate:module $module</question> before");
80
                }
81
            }
82
83
            // generate directories and files
84
            $this->generate($input, $output);
85
86
            // verify it
87
            $this->verify($input, $output);
88
89
            $this->write("CRUD for <info>{$model}</info> has been successfully created.");
90
            if ($module = $input->getArgument('module')) {
91
                $this->write(
92
                    "Open page <info>/acl</info> in your browser and set permissions for <info>{$module}</info>"
93
                );
94
            }
95
        } catch (InputException $e) {
96
            $this->error("ERROR: {$e->getMessage()}");
97
        }
98
    }
99
100
    /**
101
     * @param InputInterface $input
102
     * @param OutputInterface $output
103
     * @return void
104
     * @throws InputException
105
     */
106
    protected function generate(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Unused Code introduced by
The parameter $output is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
107
    {
108
        $model = ucfirst($input->getArgument('model'));
109
110
        // generate CRUD
111
        $crudFile = $this->getApplication()->getModelPath($model) .DS. 'Crud.php';
112
113
        if (file_exists($crudFile)) {
114
            $this->comment("Crud file <info>$model/Crud.php</info> already exists");
115
        } else {
116
            $template = $this->getTemplate('CrudTemplate');
117
            $template->setFilePath($crudFile);
118
            $template->setTemplateData([
119
                'model' => $model
120
            ]);
121
122
            $generator = new Generator\Generator($template);
123
            $generator->make();
124
        }
125
126
        if ($module = $input->getArgument('module')) {
127
            $this->write("Generate <info>$module/controllers/crud.php</info>");
128
129
            $controllerFile = $this->getControllerPath($module, 'crud');
130
            if (file_exists($controllerFile)) {
131
                $this->comment("Controller file <info>$module/crud</info> already exists");
132
            } else {
133
                $template = new Generator\Template\CrudControllerTemplate();
134
                $template->setFilePath($controllerFile);
135
                $template->setTemplateData(['model' => $model]);
136
137
                $generator = new Generator\Generator($template);
138
                $generator->make();
139
            }
140
141
            $this->write("Generate <info>$module/views/crud.phtml</info>");
142
143
            $viewFile = $this->getViewPath($module, 'crud');
144
            if (file_exists($viewFile)) {
145
                $this->comment("View file <info>$module/crud</info> already exists");
146
            } else {
147
                $template = new Generator\Template\CrudViewTemplate();
148
                $template->setFilePath($viewFile);
149
                $template->setTemplateData([
150
                    'model' => $model,
151
                    'module' => $module
152
                ]);
153
154
                $generator = new Generator\Generator($template);
155
                $generator->make();
156
            }
157
        }
158
    }
159
160
    /**
161
     * @param InputInterface $input
162
     * @param OutputInterface $output
163
     * @return void
164
     * @throws \Bluzman\Generator\GeneratorException
165
     */
166
    public function verify(InputInterface $input, OutputInterface $output)
167
    {
168
        $modelPath = $this->getApplication()->getModelPath($input->getArgument('model'));
169
170
        $paths = [
171
            $modelPath . DS . 'Crud.php',
172
        ];
173
174
        foreach ($paths as $path) {
175
            if (!$this->getFs()->exists($path)) {
176
                throw new Generator\GeneratorException("File `$path` is not exists");
177
            }
178
        }
179
    }
180
}
181