GeneratorCommand::getNameInput()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace BeyondCode\LaravelPackageTools\Commands;
4
5
use Illuminate\Support\Str;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Output\OutputInterface;
8
9
abstract class GeneratorCommand
10
{
11
    /**
12
     * The type of class being generated.
13
     *
14
     * @var string
15
     */
16
    protected $type;
17
18
    /** @var OutputInterface */
19
    protected $output;
20
21
    /** @var InputInterface */
22
    protected $input;
23
24
    /** @var Composer */
25
    protected $composer;
26
27
    /** @var string|null */
28
    public $outputPath;
29
30
    public function __construct()
31
    {
32
        $this->composer = new Composer();
33
    }
34
35
    /**
36
     * Get the stub file for the generator.
37
     *
38
     * @return string
39
     */
40
    abstract protected function getStub();
41
42
    /**
43
     * Execute the console command.
44
     *
45
     * @param InputInterface $input
46
     * @param OutputInterface $output
47
     * @return bool|null
48
     */
49
    public function __invoke(InputInterface $input, OutputInterface $output)
50
    {
51
        $this->input = $input;
52
        $this->output = $output;
53
54
        $name = $this->qualifyClass($this->getNameInput());
55
56
        $path = $this->getPath($name);
57
58
        // First we will check to see if the class already exists. If it does, we don't want
59
        // to create the class and overwrite the user's code. So, we will bail out so the
60
        // code is untouched. Otherwise, we will continue generating this class' files.
61
        if (! $this->input->getOption('force') && $this->alreadyExists($this->getNameInput())) {
62
            $this->error($this->type.' already exists!');
63
64
            return false;
65
        }
66
67
        // Next, we will generate the path to the location where this class' file should get
68
        // written. Then, we will build the class and make the proper replacements on the
69
        // stub files so that it gets the correctly formatted namespace and class name.
70
        $this->makeDirectory(Str::before($path, basename($path)));
71
72
        file_put_contents($path, $this->buildClass($name));
73
74
        $this->info($this->type.' created successfully.');
75
    }
76
77
    /**
78
     * Parse the class name and format according to the root namespace.
79
     *
80
     * @param  string  $name
81
     * @return string
82
     */
83
    protected function qualifyClass($name)
84
    {
85
        $name = ltrim($name, '\\/');
86
87
        $rootNamespace = $this->rootNamespace();
88
89
        if (Str::startsWith($name, $rootNamespace)) {
90
            return $name;
91
        }
92
93
        $name = str_replace('/', '\\', $name);
94
95
        return $this->qualifyClass(
96
            $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
97
        );
98
    }
99
100
    /**
101
     * Determine if the class already exists.
102
     *
103
     * @param  string  $rawName
104
     * @return bool
105
     */
106
    protected function alreadyExists($rawName)
107
    {
108
        return file_exists($this->getPath($this->qualifyClass($rawName)));
109
    }
110
111
    public function info($text)
112
    {
113
        $this->output->write('<info>'.$text.'</info>');
114
    }
115
116
    public function error($text)
117
    {
118
        $this->output->write('<error>'.$text.'</error>');
119
    }
120
121
    protected function getPath($name)
122
    {
123
        $name = Str::replaceFirst($this->rootNamespace(), '', $name);
124
125
        return $this->getOutputPath().str_replace('\\', '/', $name).'.php';
126
    }
127
128
    protected function getOutputPath(): string
129
    {
130
        return $this->outputPath ?? getcwd().'/src/';
131
    }
132
133
    protected function getNameInput(): string
134
    {
135
        return trim($this->input->getArgument('name'));
136
    }
137
138
    protected function rootNamespace()
139
    {
140
        $autoload = $this->composer->get('autoload.psr-4');
141
142
        return array_keys($autoload)[0];
143
    }
144
145
    protected function buildClass($name)
146
    {
147
        $stub = file_get_contents($this->getStub());
148
149
        return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
150
    }
151
152
    protected function replaceNamespace(&$stub, $name)
153
    {
154
        $stub = str_replace(
155
            ['DummyNamespace', 'DummyRootNamespace'],
156
            [$this->getNamespace($name), $this->rootNamespace()],
157
            $stub
158
        );
159
160
        return $this;
161
    }
162
163
    protected function getNamespace($name)
164
    {
165
        return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
166
    }
167
168
    protected function replaceClass($stub, $name)
169
    {
170
        $class = str_replace($this->getNamespace($name).'\\', '', $name);
171
172
        return str_replace('DummyClass', $class, $stub);
173
    }
174
175
    protected function getDefaultNamespace(string $rootNamespace)
176
    {
177
        return $rootNamespace;
178
    }
179
180
    protected function makeDirectory(string $path)
181
    {
182
        @mkdir($path, 0777, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
183
    }
184
185
    public function option($name, $default = null)
186
    {
187
        if ($this->input->hasOption($name)) {
188
            return $this->input->getOption($name) ?? $default;
189
        }
190
191
        return $default;
192
    }
193
}
194