TransformerMakeCommand::getStub()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace lasselehtinen\Cybertron\Commands;
4
5
use DB;
6
use Illuminate\Console\GeneratorCommand;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Facades\Schema;
9
use Symfony\Component\Console\Input\InputOption;
10
11
class TransformerMakeCommand extends GeneratorCommand
12
{
13
    /**
14
     * The console command name.
15
     *
16
     * @var string
17
     */
18
    protected $name = 'make:transformer';
19
20
    /**
21
     * The console command description.
22
     *
23
     * @var string
24
     */
25
    protected $description = 'Create a new Fractal Transformer';
26
27
    /**
28
     * The type of class being generated.
29
     *
30
     * @var string
31
     */
32
    protected $type = 'Transformer';
33
34
    /**
35
     * Execute the console command.
36
     *
37
     * @return void
38
     */
39
    public function fire()
40
    {
41
        if (!class_exists($this->option('model'))) {
42
            $this->error('Model does not exist.');
43
            exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method fire() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
44
        }
45
46
        if (parent::fire() === false) {
47
            return;
48
        }
49
    }
50
51
    /**
52
     * Get the stub file for the generator.
53
     *
54
     * @return string
55
     */
56
    protected function getStub()
57
    {
58
    }
59
60
    /**
61
     * Build the class with the given name.
62
     *
63
     * @param  string  $name
64
     * @return string
65
     */
66
    protected function buildClass($name)
67
    {
68
        // Create new model from the parameter
69
        $modelName = $this->option('model');
70
        $model = new $modelName;
71
72
        // Get column types, namespaces etc. needed for the generation of the Transformer
73
        $columnTypes = $this->getColumnTypes($model);
74
        $namespace = $this->getNamespace($name);
75
        $class = str_replace($this->getNamespace($name) . '\\', '', $name);
76
        $name = (new \ReflectionClass($modelName))->getShortName();
77
        $relationships = $this->getRelationships($model);
78
79
        // Generate the stub using the Blade view
80
        $stub = view('cybertron::transformer', compact('columnTypes', 'namespace', 'class', 'modelName', 'name', 'relationships'))->render();
0 ignored issues
show
Bug introduced by
The method render does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
81
82
        // Replace short tag
83
        $stub = str_replace('<?', '<?php', $stub);
84
85
        return $stub;
86
    }
87
88
    /**
89
     * Get columns types for the models table and if type casting is needed
90
     * @param  mixed $model
91
     * @return Illuminate\Support\Collection
92
     */
93
    public function getColumnTypes($model)
94
    {
95
        // Generate new Collection for column types
96
        $columnTypes = new Collection;
97
98
        // Go through all the columns in the models table
99
        foreach (Schema::getColumnListing($model->getTable()) as $columnName) {
100
            // Get the column type
101
            $type = DB::connection()->getDoctrineColumn($model->getTable(), $columnName)->getType()->getName();
102
103
            // Determine if type casting is required
104
            switch ($type) {
105
                case 'integer':
106
                case 'boolean':
107
                    $cast = true;
108
                    break;
109
                default:
110
                    $cast = false;
111
                    break;
112
            }
113
114
            // Push to Collection
115
            $columnTypes->push([
116
                'name' => $columnName,
117
                'type' => $type,
118
                'cast' => $cast,
119
            ]);
120
        }
121
122
        return $columnTypes;
123
    }
124
125
    /**
126
     * Get the relationships for the given model
127
     * @param  mixed $model
128
     * @return Illuminate\Support\Collection
129
     */
130
    public function getRelationships($model)
131
    {
132
        // Define the relationship types that we want to automatically include in the Transformer
133
        $relations = [
134
            'hasMany',
135
            'hasManyThrough',
136
            //'belongsToMany',
137
            'hasOne',
138
            //'belongsTo',
139
            //'morphOne',
140
            'morphTo',
141
            'morphMany',
142
            //'morphToMany',
143
        ];
144
145
        // Generate new collection for relationships
146
        $relationships = new Collection();
147
148
        // Go through all the methods and relations and pick those that match the type
149
        foreach (get_class_methods($model) as $method) {
150
            // Get the contents of the method
151
            $methodContents = $this->getMethodContents($model, $method);
152
153
            foreach ($relations as $relation) {
154
                if (str_contains($methodContents, '$this->' . $relation) && $method !== 'morphedByMany') {
155
                    // Determine if the relation has one or many (item and collection in Fractal)
156
                    $relationCountType = (str_contains($relation, 'Many')) ? 'collection' : 'item';
157
158
                    // Add to collection
159
                    $relationships->push([
160
                        'method' => $method,
161
                        'relationType' => $relation,
162
                        'relationCountType' => $relationCountType,
163
                        'relatedClass' => $this->getRelationshipClassName($model, $method),
164
                    ]);
165
                }
166
            }
167
        }
168
169
        return $relationships;
170
    }
171
172
    /**
173
     * Return the methods contents as a string
174
     * @param  mixed  $model
175
     * @param  string $method
176
     * @return string
177
     */
178
    public function getMethodContents($model, $method)
179
    {
180
        // Use reflection to inspect the code, based on Illuminate/Support/SerializableClosure.php
181
        $reflection = new \ReflectionMethod($model, $method);
182
        $file = new \SplFileObject($reflection->getFileName());
183
        $file->seek($reflection->getStartLine() - 1);
184
185
        $code = '';
186
187
        while ($file->key() < $reflection->getEndLine()) {
188
            $code .= $file->current();
189
            $file->next();
190
        }
191
192
        $code = trim(preg_replace('/\s\s+/', '', $code));
193
        $begin = strpos($code, 'function(');
194
        $code = substr($code, $begin, strrpos($code, '}') - $begin + 1);
195
196
        return $code;
197
    }
198
199
    /**
200
     * The shortname of the class that the relationship is referring to
201
     * @param  mixed  $model
202
     * @param  string $method
203
     * @return string
204
     */
205
    public function getRelationshipClassName($model, $method)
206
    {
207
        // Create new model
208
        $model = new $model;
209
        $className = get_class($model->{$method}()->getRelated());
210
211
        $reflection = new \ReflectionClass($className);
212
        return $reflection->getShortName();
213
    }
214
215
    /**
216
     * Get the console command options.
217
     *
218
     * @return array
219
     */
220
    protected function getOptions()
221
    {
222
        return [
223
            ['model', 'm', InputOption::VALUE_REQUIRED, 'Name of the model we want to create the Transformer from'],
224
        ];
225
    }
226
}
227