Completed
Push — master ( d0572a...56be9e )
by Pásztor
03:28 queued 01:34
created

CreateApi::makeStub()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Autumn\Api\Console;
4
5
use Str;
6
use Route;
7
use Exception;
8
use October\Rain\Scaffold\GeneratorCommand;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Input\InputArgument;
11
12
class CreateApi extends GeneratorCommand
13
{
14
    /**
15
     * The console command name.
16
     *
17
     * @var string
18
     */
19
    protected $name = 'create:api';
20
21
    /**
22
     * The console command description.
23
     *
24
     * @var string
25
     */
26
    protected $description = 'Create api controller and transformer for a given model.';
27
28
    /**
29
     * The type of class being generated.
30
     *
31
     * @var string
32
     */
33
    protected $type = 'API';
34
35
    /**
36
     * A mapping of stub to generated file.
37
     *
38
     * @var array
39
     */
40
    protected $stubs = [
41
        'api/controller.stub' => 'http/controllers/{{studly_controller}}.php',
42
        'api/transformer.stub' => 'http/transformers/{{studly_transformer}}.php',
43
        'api/routes.stub' => 'routes.php',
44
    ];
45
46
    /**
47
     * Execute the console command.
48
     *
49
     * @return bool|null
50
     */
51
    public function fire()
52
    {
53
        parent::fire();
54
55
        $routeExists = Route::has(
56
            'api.v1.'.$this->vars['lower_controller'].'.index'
57
        );
58
59
        if (! $routeExists) {
60
            $this->addRoute();
61
        }
62
    }
63
64
    /**
65
     * Make a single stub.
66
     *
67
     * @param string $stubName The source filename for the stub.
68
     */
69
    public function makeStub($stubName)
70
    {
71
        try {
72
            parent::makeStub($stubName);
73
        } catch (Exception $e) {
74
            return;
75
        }
76
    }
77
78
    /**
79
     *  Add routes to routes file.
80
     */
81
    protected function addRoute()
82
    {
83
        $stubName = 'api/route.stub';
84
85
        $sourceFile = $this->getSourcePath().'/'.$stubName;
86
        $destinationFile = $this->getDestinationPath().'/routes.php';
87
        $destinationContent = $this->files->get($sourceFile);
88
89
        /*
90
         * Parse each variable in to the destination content and path
91
         */
92
        foreach ($this->vars as $key => $var) {
93
            $destinationContent = str_replace('{{'.$key.'}}', $var, $destinationContent);
94
            $destinationFile = str_replace('{{'.$key.'}}', $var, $destinationFile);
95
        }
96
97
        $this->saveResource($destinationFile, $destinationContent);
98
    }
99
100
    /**
101
     * Prepare variables for stubs.
102
     *
103
     * return @array
104
     */
105
    protected function prepareVars()
106
    {
107
        $pluginCode = $this->argument('plugin');
108
109
        $parts = explode('.', $pluginCode);
110
        $plugin = array_pop($parts);
111
        $author = array_pop($parts);
112
113
        $model = $this->argument('model');
114
        $transformer = $model.'Transformer';
115
116
        /*
117
         * Determine the controller name to use.
118
         */
119
        $controller = $this->option('controller');
120
        if (! $controller) {
121
            $controller = Str::plural($model);
122
        }
123
124
        return [
125
            'model' => $model,
126
            'author' => $author,
127
            'plugin' => $plugin,
128
            'controller' => $controller,
129
            'transformer' => $transformer,
130
        ];
131
    }
132
133
    /**
134
     * Get the console command arguments.
135
     *
136
     * @return array
137
     */
138
    protected function getArguments()
139
    {
140
        return [
141
            ['plugin', InputArgument::REQUIRED, 'The name of the plugin to create. Eg: RainLab.Blog'],
142
            ['model', InputArgument::REQUIRED, 'The name of the model. Eg: Post'],
143
        ];
144
    }
145
146
    /**
147
     * Get the console command options.
148
     *
149
     * @return array
150
     */
151
    protected function getOptions()
152
    {
153
        return [
154
            ['force', null, InputOption::VALUE_NONE, 'Overwrite existing files with generated ones.'],
155
            ['controller', null, InputOption::VALUE_OPTIONAL, 'The name of the controller. Eg: Posts'],
156
        ];
157
    }
158
159
    /**
160
     * Save the given resource to the given routes file.
161
     *
162
     * @param string $destinationFile
163
     * @param string $destinationContent
164
     */
165
    protected function saveResource($destinationFile, $destinationContent)
166
    {
167
        // read file
168
        $lines = file($destinationFile);
169
        $lastLine = trim($lines[count($lines) - 1]);
170
171
        // modify file
172
        if (strcmp($lastLine, '});') === 0) {
173
            $lines[count($lines) - 1] = '    '.$destinationContent;
174
            $lines[] = "\r\n});\r\n";
175
        } else {
176
            $lines[] = "$destinationContent\r\n";
177
        }
178
179
        // save file
180
        $fp = fopen($destinationFile, 'w');
181
182
        fwrite($fp, implode('', $lines));
183
        fclose($fp);
184
    }
185
}
186