1
+ "use strict" ;
2
+
3
+ const htmlparser = require ( 'htmlparser2' ) ,
4
+ fs = require ( 'fs' ) ,
5
+ path = require ( 'path' ) ;
6
+
7
+ class LaravelBladeParser
8
+ {
9
+ /**
10
+ * @param options
11
+ */
12
+ constructor ( options )
13
+ {
14
+ this . html = "" ;
15
+ this . defaultOptions = {
16
+ folder : './resources/views' ,
17
+ path : './resources/views/welcome.blade.php' ,
18
+ regex : {
19
+ include : / @ i n c l u d e \( \s * [ \' \" ] ( [ ^ \[ \] ] * ) [ \' \" ] \s * (?: (?: .* [ ^ \s \) ] ) \s * ) * \s * \) / gi,
20
+ extends : / @ e x t e n d s \( (?: [ \' \" ] ) ( .* ) (?: [ \' \" ] ) \) / gi,
21
+ yield : / @ y i e l d \( [ \' \" ] ? ( [ ^ \' \" ] * ) [ \' \" ] ? \) / gi,
22
+ multiLineSection : / @ s e c t i o n \( \s * [ \' \" ] ? ( [ ^ \' \" ] * ) [ \' \" ] ? \s * \) ( (? ! \@ s t o p ) .* \s * ) * \@ s t o p / gi,
23
+ oneLineSection : / @ s e c t i o n \( [ \' \" ] ( [ ^ \' \" ] * ) [ \' \" ] ? \s * \, \s * [ \' \" ] ? ( [ ^ \" \' ] * ) [ \' \" ] ? \) / gi
24
+ } ,
25
+ encoding : 'utf8'
26
+ } ;
27
+ this . options = Object . assign ( this . defaultOptions , options ? options : { } ) ;
28
+
29
+ this . _init ( ) ;
30
+ }
31
+
32
+ /**
33
+ * @returns {string|XML|string|void|*|* }
34
+ */
35
+ getHTML ( )
36
+ {
37
+ return this . html ;
38
+ }
39
+
40
+ /**
41
+ * @private
42
+ */
43
+ _init ( )
44
+ {
45
+ this . html = this . _parse ( this . _getFileContent ( this . options . path ) ) ;
46
+ }
47
+
48
+ /**
49
+ * @param content
50
+ *
51
+ * @private
52
+ */
53
+ _parse ( content )
54
+ {
55
+ var template = content ,
56
+ items = { } ;
57
+
58
+ template . replace ( this . options . regex . extends , ( match , value ) => {
59
+ let filePath = path . join ( this . options . folder , value . replace ( / \. / gi, "/" ) + '.blade.php' ) ;
60
+
61
+ return this . _getFileContent ( filePath ) ;
62
+ } ) . replace ( this . options . regex . oneLineSection , ( match , key , value ) => {
63
+ items [ key ] = value ;
64
+
65
+ return "" ;
66
+ } ) . replace ( this . options . regex . multiLineSection , ( match , key , value ) => {
67
+ items [ key ] = value ;
68
+
69
+ return "" ;
70
+ } ) . replace ( this . options . regex . yield , ( match , key ) => {
71
+ return typeof items [ key ] == "undefined" ? "" : items [ key ] ;
72
+ } ) . replace ( this . options . regex . include , ( match , value ) => {
73
+ let filePath = path . join ( this . options . folder , value . replace ( / \. / gi, "/" ) + '.blade.php' ) ,
74
+ html = this . _getFileContent ( filePath ) ;
75
+
76
+ return this . _parse ( html ) ;
77
+ } ) ;
78
+
79
+ return template ;
80
+ }
81
+
82
+ /**
83
+ * @param filePath
84
+ *
85
+ * @returns {* }
86
+ * @private
87
+ */
88
+ _getFileContent ( filePath )
89
+ {
90
+ return fs . readFileSync ( filePath , this . options . encoding ) ;
91
+ }
92
+ }
93
+
94
+ module . exports = options => new LaravelBladeParser ( options ) . getHTML ( ) ;
0 commit comments