Completed
Pull Request — master (#30)
by Anton
17:34
created

CrudCommand::verify()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 2
crap 3.0261
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 Bluzman\Input\InputArgument;
10
use Bluzman\Input\InputException;
11
use Bluzman\Generator;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Output\OutputInterface;
14
15
/**
16
 * ModelCommand
17
 *
18
 * @package  Bluzman\Command\Generate
19
 */
20
class CrudCommand extends AbstractGenerateCommand
21
{
22
    /**
23
     * Command configuration
24
     */
25 14
    protected function configure()
26
    {
27
        $this
28
            // the name of the command (the part after "bin/bluzman")
29 14
            ->setName('generate:crud')
30
            // the short description shown while running "php bin/bluzman list"
31 14
            ->setDescription('Generate a CRUD for model')
32
            // the full command description shown when running the command with
33
            // the "--help" option
34 14
            ->setHelp('This command allows you to generate CRUD files');
35
36
        $this
37 14
            ->addModelArgument()
38 14
            ->addModuleArgument(InputArgument::OPTIONAL)
39
        ;
40 14
    }
41
42
    /**
43
     * @param InputInterface $input
44
     * @param OutputInterface $output
45
     * @return void
46
     */
47 3
    protected function execute(InputInterface $input, OutputInterface $output)
48
    {
49
        try {
50 3
            $this->write("Running <info>generate:crud</info> command");
51
52 3
            $model = $input->getArgument('model');
53 3
            $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...
54
55 1
            if (!$this->getApplication()->isModelExists($model)) {
56
                throw new InputException(
57
                    "Model $model is not exist, " .
58
                    "run command <question>bluzman generate:model $model</question> before"
59
                );
60
            }
61
62 1 View Code Duplication
            if ($module = $input->getArgument('module')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
63
                $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...
64
65
                if (!$this->getApplication()->isModuleExists($module)) {
66
                    throw new InputException(
67
                        "Module $module is not exist, " .
68
                        "run command <question>bluzman generate:module $module</question> before"
69
                    );
70
                }
71
            }
72
73
            // generate directories and files
74 1
            $this->generate($input, $output);
75
76
            // verify it
77 1
            $this->verify($input, $output);
78
79 1
            $this->write("CRUD for <info>{$model}</info> has been successfully created.");
80 1
            if ($module = $input->getArgument('module')) {
81
                $this->write(
82
                    "Open page <info>/acl</info> in your browser and set permissions for <info>{$module}</info>"
83
                );
84
            }
85 2
        } catch (InputException $e) {
86 2
            $this->error("ERROR: {$e->getMessage()}");
87
        }
88 3
    }
89
90
    /**
91
     * @param InputInterface $input
92
     * @param OutputInterface $output
93
     * @return void
94
     * @throws InputException
95
     */
96 1
    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...
97
    {
98 1
        $model = ucfirst($input->getArgument('model'));
99
100
        // generate CRUD
101 1
        $crudFile = $this->getApplication()->getModelPath($model) . DS . 'Crud.php';
102
103 1
        if (file_exists($crudFile)) {
104
            $this->comment("Crud file <info>$model/Crud.php</info> already exists");
105
        } else {
106 1
            $template = $this->getTemplate('CrudTemplate');
107 1
            $template->setFilePath($crudFile);
108 1
            $template->setTemplateData(
109
                [
110 1
                    'model' => $model
111
                ]
112
            );
113
114 1
            $generator = new Generator\Generator($template);
115 1
            $generator->make();
116
        }
117
118 1
        if ($module = $input->getArgument('module')) {
119
            $this->write("Generate <info>$module/controllers/crud.php</info>");
120
121
            $controllerFile = $this->getControllerPath($module, 'crud');
122
            if (file_exists($controllerFile)) {
123
                $this->comment("Controller file <info>$module/crud</info> already exists");
124
            } else {
125
                $template = new Generator\Template\CrudControllerTemplate();
126
                $template->setFilePath($controllerFile);
127
                $template->setTemplateData(['model' => $model]);
128
129
                $generator = new Generator\Generator($template);
130
                $generator->make();
131
            }
132
133
            $this->write("Generate <info>$module/views/crud.phtml</info>");
134
135
            $viewFile = $this->getViewPath($module, 'crud');
136
            if (file_exists($viewFile)) {
137
                $this->comment("View file <info>$module/crud</info> already exists");
138
            } else {
139
                $template = new Generator\Template\CrudViewTemplate();
140
                $template->setFilePath($viewFile);
141
                $template->setTemplateData(
142
                    [
143
                        'model' => $model,
144
                        'module' => $module
145
                    ]
146
                );
147
148
                $generator = new Generator\Generator($template);
149
                $generator->make();
150
            }
151
        }
152 1
    }
153
154
    /**
155
     * @param InputInterface $input
156
     * @param OutputInterface $output
157
     * @return void
158
     * @throws \Bluzman\Generator\GeneratorException
159
     */
160 1
    public function verify(InputInterface $input, OutputInterface $output)
161
    {
162 1
        $modelPath = $this->getApplication()->getModelPath($input->getArgument('model'));
163
164
        $paths = [
165 1
            $modelPath . DS . 'Crud.php',
166
        ];
167
168 1
        foreach ($paths as $path) {
169 1
            if (!$this->getFs()->exists($path)) {
170
                throw new Generator\GeneratorException("File `$path` is not exists");
171
            }
172
        }
173 1
    }
174
}
175