Completed
Push — master ( 040cb4...81c4b0 )
by Fumio
02:35
created

AddonMakeCommand::handle()   C

Complexity

Conditions 9
Paths 28

Size

Total Lines 68
Code Lines 39

Duplication

Lines 4
Ratio 5.88 %

Code Coverage

Tests 35
CRAP Score 9.1582

Importance

Changes 4
Bugs 0 Features 1
Metric Value
cc 9
eloc 39
c 4
b 0
f 1
nc 28
nop 3
dl 4
loc 68
ccs 35
cts 40
cp 0.875
crap 9.1582
rs 6.2813

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
namespace Jumilla\Addomnipot\Laravel\Console;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Filesystem\Filesystem;
7
use Jumilla\Addomnipot\Laravel\Environment as AddonEnvironment;
8
use Jumilla\Addomnipot\Laravel\Generator as AddonGenerator;
9
use UnexpectedValueException;
10
use Exception;
11
12
/**
13
 * Modules console commands.
14
 *
15
 * @author Fumio Furukawa <[email protected]>
16
 */
17
class AddonMakeCommand extends Command
18
{
19
    use MakeCommandTrait;
20
21
    /**
22
     * The console command signature.
23
     *
24
     * @var string
25
     */
26
    protected $signature = 'make:addon
27
        {name : The name of the addon.}
28
        {skeleton? : Skeleton of addon.}
29
        {--namespace= : PHP namespace of addon. Slash OK.}
30
        {--no-namespace : No PHP namespace.}
31
        {--language= : Languages, comma separated.}
32
        {--yes : No confirm.}
33
    ';
34
35
    /**
36
     * The console command description.
37
     *
38
     * @var string
39
     */
40
    protected $description = 'Create a new addon directory';
41
42
    /**
43
     * @var array
44
     */
45
    protected $skeletons = [
46
        1 => 'minimum',
47
        2 => 'simple',
48
        3 => 'asset',
49
        4 => 'library',
50
        5 => 'api',
51
        6 => 'ui',
52
        11 => 'ui-sample',
53
        12 => 'debug',
54
        13 => 'generator',
55
        14 => 'laravel5',
56
        15 => 'laravel5-auth',
57
    ];
58
59
    /**
60
     * @var string
61
     */
62
    protected $default_skeleton = 'ui-sample';
63
64
    /**
65
     * Execute the console command.
66
     *
67
     * @param \Jumilla\Addomnipot\Laravel\Addons\AddonGenerator $generator
68
     *
69
     * @return mixed
70
     */
71 3
    public function handle(Filesystem $filesystem, AddonEnvironment $env, AddonGenerator $generator)
72
    {
73 3
        $addon_name = preg_replace('#(/+)#', '-', $this->argument('name'));
74
75 3
        $output_path = $env->path($addon_name);
0 ignored issues
show
Bug introduced by
It seems like $addon_name defined by preg_replace('#(/+)#', '...this->argument('name')) on line 73 can also be of type array<integer,string>; however, Jumilla\Addomnipot\Laravel\Environment::path() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
76
77
        // Check addon-directory
78 3
        if ($filesystem->exists($output_path)) {
79
            throw new UnexpectedValueException("addon directory '{$addon_name}' is already exists.");
80
        }
81
82
        // Adjust addon_name
83 3
        $addon_name = preg_replace('/[^\w_\-]/', '', $addon_name);
84
85 3
        $addon_class = preg_replace(
86 3
            ['/[^\w_]/', '/^(\d)/'],
87 3
            ['', '_$1'],
88 3
            studly_case($addon_name)
0 ignored issues
show
Bug introduced by
It seems like $addon_name defined by preg_replace('/[^\\w_\\-]/', '', $addon_name) on line 83 can also be of type array<integer,string>; however, studly_case() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
89 3
        );
90
91
        // namespace
92 3
        if ($this->option('no-namespace')) {
93 1
            $namespace = '';
94 1
        } else {
95 2
            if ($this->option('namespace')) {
96 1
                $namespace = str_replace('/', '\\', $this->option('namespace'));
97 1
            } else {
98 1
                $namespace = 'App\\'.$addon_class;
99
            }
100
        }
101
102 3
        if (! $this->validPhpNamespace($namespace)) {
103 1
            throw new UnexpectedValueException("PHP namespace '{$namespace}' is invalid.");
104
        }
105
106
        // languages
107 2
        $languages = $this->option('language') ? explode($this->option('language')) : [];
108
109
        // Show select prompt if not specified
110 2
        $skeleton = $this->chooseSkeleton($this->argument('skeleton'));
0 ignored issues
show
Bug introduced by
It seems like $this->argument('skeleton') targeting Illuminate\Console\Command::argument() can also be of type array; however, Jumilla\Addomnipot\Larav...Trait::chooseSkeleton() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
111
112
        $properties = [
113 2
            'addon_name' => $addon_name,
114 2
            'addon_class' => $addon_class,
115 2
            'namespace' => $namespace,
116 2
            'languages' => array_unique(array_merge(['en', $this->laravel['config']->get('app.locale')], $languages)),
117 2
        ];
118
119
        // confirm
120 2
        $this->line('Addon name: '.$properties['addon_name']);
121 2
        $this->line('PHP namespace: '.$properties['namespace']);
122 2
        $this->line('Skeleton: '.$skeleton);
123 2
        $this->line('Languages: '.implode(', ', $properties['languages']));
124
125 2 View Code Duplication
        if (!$this->option('yes') && !$this->confirm('generate ready? [Y/n]', true)) {
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...
126
            $this->comment('canceled');
127
            return;
128
        }
129
130
        try {
131 2
            $generator->generateAddon($output_path, str_replace(':', '-', $skeleton), $properties);
132 2
            $this->info('Addon Generated.');
133 2
        } catch (Exception $ex) {
134
            $filesystem->deleteDirectory($output_path);
135
136
            throw $ex;
137
        }
138 2
    }
139
140 3
    protected function validPhpNamespace($namespace)
141
    {
142 3
        foreach (explode('\\', $namespace) as $part) {
143 3
            if (! preg_match('/^[0-9a-zA-Z_]+$/', $part)) {
144 1
                return false;
145
            }
146
147 2
            if (! preg_match('/^[^\d]/', $part)) {
148
                return false;
149
            }
150 2
        }
151
152 2
        return true;
153
    }
154
}
155