Completed
Push — master ( be02a5...a1ec95 )
by Nick
22:04 queued 02:39
created

Command::inspectModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace EloquentJs\ScriptGenerator\Console;
4
5
use EloquentJs\Model\AcceptsEloquentJsQueries;
6
use EloquentJs\ScriptGenerator\Generator;
7
use EloquentJs\ScriptGenerator\Model\Inspector;
8
use EloquentJs\ScriptGenerator\Model\Metadata;
9
use Illuminate\Console\Command as BaseCommand;
10
use Illuminate\Filesystem\ClassFinder;
11
12
class Command extends BaseCommand
13
{
14
    /**
15
     * The name and signature of the console command.
16
     *
17
     * @var string
18
     */
19
    protected $signature = 'eloquentjs:generate
20
                            {--models= : Models to include in the generated javascript}
21
                            {--namespace=App : Namespace prefix to use with the --models option}
22
                            {--output=public/eloquent.js : Where to save the generated javascript file}';
23
24
    /**
25
     * The console command description.
26
     *
27
     * @var string
28
     */
29
    protected $description = 'Generate a javascript file for an Eloquent-ish API in the browser';
30
31
    /**
32
     * @var InputParser
33
     */
34
    protected $inputParser;
35
36
    /**
37
     * @var Generator
38
     */
39
    protected $generator;
40
41
    /**
42
     * @var ClassFinder
43
     */
44
    protected $classFinder;
45
46
    /**
47
     * @var Inspector
48
     */
49
    protected $inspector;
50
51
    /**
52
     * Create a new command instance.
53
     *
54
     * @param InputParser $inputParser
55
     * @param ClassFinder $classFinder
56
     * @param Inspector $inspector
57
     * @param Generator $generator
58
     */
59
    public function __construct(InputParser $inputParser, ClassFinder $classFinder, Inspector $inspector, Generator $generator)
60
    {
61
        parent::__construct();
62
63
        $this->inputParser = $inputParser;
64
        $this->classFinder = $classFinder;
65
        $this->inspector = $inspector;
66
        $this->generator = $generator;
67
    }
68
69
    /**
70
     * Execute the console command.
71
     *
72
     * @return mixed
73
     */
74
    public function handle()
75
    {
76
        $models = $this->inspectRequestedModels();
77
78
        $this->printMapping($models);
79
80
        if ($this->isConfirmed()) {
81
            $this->writeJavascript($models);
82
83
            $this->info("Javascript written to {$this->option('output')}");
84
        }
85
    }
86
87
    /**
88
     * Get models to include in the eloquentjs build.
89
     *
90
     * @return array
91
     */
92
    protected function inspectRequestedModels()
93
    {
94
        return array_map([$this, 'inspectModel'], $this->getRequestedClassNames());
95
    }
96
97
    /**
98
     * Get the model classes requested by the user.
99
     *
100
     * @return array
101
     */
102
    protected function getRequestedClassNames()
103
    {
104
        if ($this->option('models')) {
105
            return $this->inputParser->parse($this->option('models'), $this->option('namespace'));
0 ignored issues
show
Bug introduced by
It seems like $this->option('models') targeting Illuminate\Console\Command::option() can also be of type array; however, EloquentJs\ScriptGenerat...le\InputParser::parse() 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...
Bug introduced by
It seems like $this->option('namespace') targeting Illuminate\Console\Command::option() can also be of type array; however, EloquentJs\ScriptGenerat...le\InputParser::parse() 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...
106
        }
107
108
        return $this->searchAppForModels();
109
    }
110
111
    /**
112
     * Search the app path for any models that implement EloquentJs.
113
     *
114
     * @return array
115
     */
116
    protected function searchAppForModels()
117
    {
118
        return array_filter(
119
            $this->classFinder->findClasses(app_path()),
120
            function ($className) {
121
                return is_subclass_of($className, AcceptsEloquentJsQueries::class);
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \EloquentJs\Model\AcceptsEloquentJsQueries::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
122
            }
123
        );
124
    }
125
126
    /**
127
     * Get the metadata for the given model name.
128
     *
129
     * @param string $className
130
     * @return Metadata
131
     */
132
    protected function inspectModel($className)
133
    {
134
        $metadata = $this->inspector->inspect(new $className);
135
136
        if (!$metadata->endpoint) {
137
            $metadata->endpoint = $this->findMissingEndpoint($className);
138
        }
139
140
        return $metadata;
141
    }
142
143
    /**
144
     * Find endpoint for the named model, either from router or from user prompt.
145
     *
146
     * @param string $className
147
     * @return string
148
     */
149
    protected function findMissingEndpoint($className)
150
    {
151
        foreach ($this->laravel['router']->getRoutes() as $route) {
152
            $action = $route->getAction();
153
154
            if (isset($action['resource']) and $action['resource'] == $className) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
155
                return $route->getUri();
156
            }
157
        }
158
159
        return $this->ask("Enter the endpoint to use for the '{$className}' model");
160
    }
161
162
    /**
163
     * Print the model-endpoint mapping.
164
     *
165
     * @param array $models
166
     * @return void
167
     */
168
    protected function printMapping(array $models)
169
    {
170
        $this->table(
171
            ['Model', 'Endpoint'],
172
            array_map(function ($metadata) {
173
                return [$metadata->name, $metadata->endpoint];
174
            }, $models)
175
        );
176
    }
177
178
    /**
179
     * Prompt user to confirm.
180
     *
181
     * @return bool
182
     */
183
    protected function isConfirmed()
184
    {
185
        return $this->confirm('Generate javascript for these models and associated endpoints?', true);
186
    }
187
188
    /**
189
     * Save the generated javascript to the filesystem.
190
     *
191
     * @param array $models
192
     * @return bool
193
     */
194
    protected function writeJavascript($models)
195
    {
196
        return $this->laravel['files']->put($this->option('output'), $this->generator->build($models)) > 0;
197
    }
198
}
199