|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace EloquentJs\ScriptGenerator; |
|
4
|
|
|
|
|
5
|
|
|
use EloquentJs\ScriptGenerator\Model\Metadata; |
|
6
|
|
|
|
|
7
|
|
|
class Generator |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* @type string location of the base EloquentJs build |
|
11
|
|
|
*/ |
|
12
|
|
|
const BASE_BUILD = __DIR__.'/../../eloquent.js'; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Generate EloquentJs javascript for the given models. |
|
16
|
|
|
* |
|
17
|
|
|
* @param array $models |
|
18
|
|
|
* @return string |
|
19
|
|
|
*/ |
|
20
|
|
|
public function build(array $models) |
|
21
|
|
|
{ |
|
22
|
|
|
return $this->prefix().$this->models($models).$this->suffix(); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Get prefix for our javascript build. |
|
27
|
|
|
* |
|
28
|
|
|
* @return string |
|
29
|
|
|
*/ |
|
30
|
|
|
protected function prefix() |
|
31
|
|
|
{ |
|
32
|
|
|
return file_get_contents(static::BASE_BUILD) |
|
33
|
|
|
. '(function(E){'; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Get custom model definitions for build. |
|
38
|
|
|
* |
|
39
|
|
|
* @param array $models |
|
40
|
|
|
* @return string |
|
41
|
|
|
*/ |
|
42
|
|
|
protected function models(array $models) |
|
43
|
|
|
{ |
|
44
|
|
|
return implode(';', array_map([$this, 'model'], $models)); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Get suffix for our javascript build. |
|
49
|
|
|
* |
|
50
|
|
|
* @return string |
|
51
|
|
|
*/ |
|
52
|
|
|
protected function suffix() |
|
53
|
|
|
{ |
|
54
|
|
|
return '})(Eloquent)'; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Generate javascript to describe the given model. |
|
59
|
|
|
* |
|
60
|
|
|
* @param Metadata $model |
|
61
|
|
|
* @return string |
|
62
|
|
|
*/ |
|
63
|
|
|
protected function model(Metadata $model) |
|
64
|
|
|
{ |
|
65
|
|
|
$config = json_encode(array_filter([ |
|
66
|
|
|
'endpoint' => $model->endpoint, |
|
67
|
|
|
'dates' => $model->dates, |
|
68
|
|
|
'scopes' => $model->scopes, |
|
69
|
|
|
'relations' => $model->relations, |
|
70
|
|
|
]), JSON_UNESCAPED_SLASHES); |
|
71
|
|
|
|
|
72
|
|
|
return "E('{$model->name}', {$config})"; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|