Command::searchAppForModels()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
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 9
rs 9.6666
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
namespace EloquentJs\ScriptGenerator\Console;
4
5
use EloquentJs\ScriptGenerator\Generator;
6
use EloquentJs\ScriptGenerator\Model\Inspector;
7
use EloquentJs\ScriptGenerator\Model\Metadata;
8
use Illuminate\Console\Command as BaseCommand;
9
use Illuminate\Filesystem\ClassFinder;
10
11
class Command extends BaseCommand
12
{
13
    /**
14
     * The name and signature of the console command.
15
     *
16
     * @var string
17
     */
18
    protected $signature = 'eloquentjs:generate
19
                            {--models= : Models to include in the generated javascript}
20
                            {--namespace=App : Namespace prefix to use with the --models option}
21
                            {--output=public/eloquent.js : Where to save the generated javascript file}';
22
23
    /**
24
     * The console command description.
25
     *
26
     * @var string
27
     */
28
    protected $description = 'Generate a javascript file for an Eloquent-ish API in the browser';
29
30
    /**
31
     * @var InputParser
32
     */
33
    protected $inputParser;
34
35
    /**
36
     * @var Generator
37
     */
38
    protected $generator;
39
40
    /**
41
     * @var ClassFinder
42
     */
43
    protected $classFinder;
44
45
    /**
46
     * @var Inspector
47
     */
48
    protected $inspector;
49
50
    /**
51
     * Create a new command instance.
52
     *
53
     * @param InputParser $inputParser
54
     * @param ClassFinder $classFinder
55
     * @param Inspector $inspector
56
     * @param Generator $generator
57
     */
58
    public function __construct(InputParser $inputParser, ClassFinder $classFinder, Inspector $inspector, Generator $generator)
59
    {
60
        parent::__construct();
61
62
        $this->inputParser = $inputParser;
63
        $this->classFinder = $classFinder;
64
        $this->inspector = $inspector;
65
        $this->generator = $generator;
66
    }
67
68
    /**
69
     * Execute the console command.
70
     *
71
     * @return mixed
72
     */
73
    public function handle()
74
    {
75
        $models = $this->inspectRequestedModels();
76
77
        $this->printMapping($models);
78
79
        if ($this->isConfirmed()) {
80
            $this->writeJavascript($models);
81
82
            $this->info("Javascript written to {$this->option('output')}");
83
        }
84
    }
85
86
    /**
87
     * Get models to include in the eloquentjs build.
88
     *
89
     * @return array
90
     */
91
    protected function inspectRequestedModels()
92
    {
93
        return array_map([$this, 'inspectModel'], $this->getRequestedClassNames());
94
    }
95
96
    /**
97
     * Get the model classes requested by the user.
98
     *
99
     * @return array
100
     */
101
    protected function getRequestedClassNames()
102
    {
103
        if ($this->option('models')) {
104
            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...
105
        }
106
107
        if (config('eloquentjs.generator')) {
108
            return array_keys(config('eloquentjs.generator'));
109
        }
110
111
        return $this->searchAppForModels();
112
    }
113
114
    /**
115
     * Search the app path for any models that implement EloquentJs.
116
     *
117
     * @return array
118
     */
119
    protected function searchAppForModels()
120
    {
121
        return array_filter(
122
            $this->classFinder->findClasses(app_path()),
123
            function($className) {
124
                return $this->isEloquentJsModel($className);
125
            }
126
        );
127
    }
128
129
    /**
130
     * Test if the named model supports EloquentJs.
131
     *
132
     * @param string $className
133
     * @return bool
134
     */
135
    protected function isEloquentJsModel($className)
136
    {
137
        return method_exists($className, 'scopeEloquentJs');
138
    }
139
140
    /**
141
     * Get the metadata for the given model name.
142
     *
143
     * @param string $className
144
     * @return Metadata
145
     */
146
    protected function inspectModel($className)
147
    {
148
        $metadata = $this->inspector->inspect(new $className);
149
150
        if ( ! $metadata->endpoint) {
151
            $metadata->endpoint = $this->findMissingEndpoint($className);
152
        }
153
154
        return $metadata;
155
    }
156
157
    /**
158
     * Find endpoint for the named model, either from router or from user prompt.
159
     *
160
     * @param string $className
161
     * @return string
162
     */
163
    protected function findMissingEndpoint($className)
164
    {
165
        foreach ($this->laravel['router']->getRoutes() as $route) {
166
            $action = $route->getAction();
167
168
            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...
169
                return $route->getUri();
170
            }
171
        }
172
173
        return $this->ask("Enter the endpoint to use for the '{$className}' model");
174
    }
175
176
    /**
177
     * Print the model-endpoint mapping.
178
     *
179
     * @param array $models
180
     * @return void
181
     */
182
    protected function printMapping(array $models)
183
    {
184
        $this->table(
185
            ['Model', 'Endpoint'],
186
            array_map(function($metadata) {
187
                return [$metadata->name, $metadata->endpoint];
188
            }, $models)
189
        );
190
    }
191
192
    /**
193
     * Prompt user to confirm.
194
     *
195
     * @return string
196
     */
197
    protected function isConfirmed()
198
    {
199
        return $this->confirm('Generate javascript for these models and associated endpoints?', true);
200
    }
201
202
    /**
203
     * Save the generated javascript to the filesystem.
204
     *
205
     * @param array $models
206
     * @return bool
207
     */
208
    protected function writeJavascript($models)
209
    {
210
        return $this->laravel['files']->put($this->option('output'), $this->generator->build($models)) > 0;
211
    }
212
}
213