-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.js
788 lines (653 loc) · 22.3 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */
/**
* Return true while the string starts as search param
*
* str <==> search
* $ === $this-> (true)
* $t === $this-> (true)
* $th === $this-> (true)
* $thi === $this-> (true)
* $this === $this-> (true)
* $this- === $this-> (true)
* $this-> === $this-> (true)
* $this->anythingelse === $this-> (true)
* $otherstuff === $this-> (false)
*
* @param {[string]} search The therm you wanna search for
* @return {[bool]}
*/
String.prototype.startsWithAny = function(search) {
var len = (this.length > search.length) ? search.length : this.length
// console.log([search.substr(0, len), this.substr(0, len)])
return (search.substr(0, len) === this.substr(0, len))
}
/** Simple extension that adds a "File > Hello World" menu item */
define(function (require, exports, module) {
"use strict";
var AppInit = brackets.getModule("utils/AppInit"),
EditorManager = brackets.getModule("editor/EditorManager"),
CodeHintManager = brackets.getModule("editor/CodeHintManager"),
DocumentManager = brackets.getModule("document/DocumentManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
ExtensionUtils = brackets.getModule('utils/ExtensionUtils'),
phpParser = require('php-parser/dist/php-parser')
;
ExtensionUtils.loadStyleSheet(module, 'styles/fontawesome.css');
ExtensionUtils.loadStyleSheet(module, 'styles/thizer-phpcompletion.css');
/**
* The object
*/
function PhpCompletion() {
this.insertHintOnTab = true
this.phpFiles = []
this.hints = []
this.isThisRegexp = /^\$(this|thi|th|t)?(-\>)?/
this.AllPhpParsedFiles = []
this.insertIndex
this.editor
this.lastChar
this.cursor
this.whatIsIt
this.search
this.loadFiles()
}
/**
* Method called by constructor
*
* @return {[void]} [Nothing is returned here]
*/
PhpCompletion.prototype.loadFiles = function() {
var $this = this
var manager = ProjectManager.getAllFiles(function(file,index,result) {
var ext = file.name.replace(/.+\./, '')
if (ext === 'php') {
file.read(function(err, data) {
if (err) {
throw new err
}
var docParsed = $this.getDocParsed(data)
var namespace = ''
var usegroup = []
var theClass = ''
var fullClassName = ''
if (docParsed && docParsed.children) {
for (var i in docParsed.children) {
if (docParsed.children[i].kind === 'namespace') {
namespace = docParsed.children[i]
for (var it in docParsed.children[i].children) {
if (docParsed.children[i].children[it].kind === 'class') {
theClass = docParsed.children[i].children[it]
fullClassName = '\\'+namespace+'\\'+theClass
} else if (docParsed.children[i].children[it].kind === 'usegroup') {
var useItems = docParsed.children[i].children[it].items
for (var g in useItems) {
usegroup.push(useItems[g].name)
}
}
}
} else if (docParsed.children[i].kind === 'class') {
theClass = docParsed.children[i]
} else if (docParsed.children[i].kind === 'usegroup') {
var useItems = docParsed.children[i].items
for (var g in useItems) {
usegroup.push(useItems[g].name)
}
}
}
}
$this.AllPhpParsedFiles.push({
file: file,
contents: data,
docParsed: docParsed,
namespace: namespace,
theClass: theClass,
fullClassName: fullClassName,
usegroup: usegroup
})
})
$this.phpFiles.push(file)
}
})
manager.done(function(allFiles) {
console.log('We loaded all the '+$this.phpFiles.length+' PHP files found')
})
}
PhpCompletion.prototype.getDocParsed = function(doc) {
var content = doc
try {
// initialize a new parser instance
var parser = new phpParser({ parser: { extractDoc: true, php7: true }, ast: { withPositions: true } });
// Try to get content from text
if (typeof doc === 'object') {
// Is not saved yet
if (doc.isDirty) {
doc.file.read(function() { })
content = doc.file._contents
} else {
content = doc.getText()
}
}
var docParsed = parser.parseCode(content)
} catch (e) {
// console.log('Error parsing file, probally it is not saved yet')
// console.log(e)
}
return docParsed
}
/**
* Extract from a class document all content and turns it to hints
*
* @param {[type]} doc [description]
* @return {[type]} [description]
*/
PhpCompletion.prototype.extractClassObjs = function(doc) {
var $this = this
var hints = []
var docParsed = $this.getDocParsed(doc)
var bodyArray = $this.getBodyArray(docParsed)
for (var i in bodyArray) {
var prop = bodyArray[i].propObj
// If the hint doesnt match the search
if ((this.search !== '') && (prop.name.toLowerCase().indexOf(this.search) === -1)) {
continue;
}
hints.push(this.getHtmlHint(
prop.name,
((prop.kind === 'method') ? prop.arguments : false),
prop.leadingComments,
prop.visibility,
((bodyArray[i].inherited) ? bodyArray[i].className : false)
))
}
return hints
}
PhpCompletion.prototype.getHtmlHint = function(hintname, args, comment, visibility, inherited) {
var $this = this
if (!hintname) {
return false
}
if (undefined === args) {
args = false
}
if (undefined === comment) {
comment = false
}
if (undefined === visibility || !visibility) {
visibility = 'Unknown type'
}
if (undefined === inherited) {
inherited = false
}
var hint = $('<span>').attr({
"id": "thizer-"+hintname.toLowerCase(),
"class": "thizer-hint",
"data-content": hintname
})
/**
* Comments
*/
if (comment) {
var commentSpan = $("<span>").attr({
"class": "thizer-comment",
"style": "display: none;"
})
for (var c in comment) {
var com = comment[c].value.split('\n')
var commentText = ""
var commentAnn = ""
for (var cL in com) {
var comLine = com[cL].replace(/^[/*\s]+/gi, '').trim()
if (comLine === '') {
continue
}
if (comLine.indexOf('@return') !== -1) {
commentAnn = "<br/> * <b>"+comLine+"</b>"
} else if (commentText === '') {
commentText = comLine+" [more...]"
}
}
/** Comments must to be small (2 lines only) */
commentSpan.html("/** "+commentText+commentAnn+" */")
}
hint.append(commentSpan)
}
/** Hint itself **/
var def = $('<span>').attr({
'class': 'thizer-hint-def'
})
switch (visibility) {
case 'public':
def.append('<i class="fa fa-globe-americas thizer-type thizer-type-success" title="'+visibility+'"></i> ')
break;
case 'protected':
def.append('<i class="fa fa-lock-open thizer-type thizer-type-warning" title="'+visibility+'"></i> ')
break;
case 'private':
def.append('<i class="fa fa-lock thizer-type thizer-type-danger" title="'+visibility+'"></i> ')
break;
case 'Unknown type':
def.append('<i class="fa fa-question thizer-type thizer-type-unknown" title="'+visibility+'"></i> ')
break;
case 'Variable':
def.append('<span class="thizer-type thizer-type-var" title="'+visibility+'">$</span> ')
break;
default:
def.append('<span class="thizer-type thizer-type-other" title="'+visibility+'">'+visibility.substr(0,1)+'</span> ')
}
// Hint is a method
if (args) {
var argStr = ''
for (var a in args) {
argStr += ', $'+args[a].name
}
hintname += '('+(argStr.replace(', ', ''))+')'
// Must update $('.thizer-hint').data('hintname')
hint.data('content', hintname)
}
// if (prop.kind === 'classconstant') {
// hintname += ' = '+prop.value.raw
// }
def.append(hintname)
// Is inherited so we show the parent name (float right)
if (inherited) {
def.append(' <span class="thizer-hint-parent">'+inherited+'</span>')
}
hint.append(def)
return hint
}
/**
* An array with all document (file) class contents
*
* @param {[type]} docParsed [description]
* @param {[type]} visibity [description]
* @return {[type]} [description]
*/
PhpCompletion.prototype.getBodyArray = function(docParsed, visibity, inherited) {
var $this = this
var bodyArray = []
if (undefined === visibity) {
visibity = 'public|protected|private'
}
if (undefined === inherited) {
inherited = false
}
if ((undefined !== docParsed) && (!docParsed.errors.length)) {
for (var i in docParsed.children) {
var item = docParsed.children[i]
switch (item.kind) {
case 'class':
// Check for visibility
bodyArray = bodyArray.concat($this.getBodyArrayFromClass(item, visibity, inherited))
break
case 'namespace':
for (var c in item.children) {
if (item.children[c].kind === 'class') {
bodyArray = bodyArray.concat($this.getBodyArrayFromClass(item.children[c], visibity, inherited))
}
}
break
}
} // End of multiple elements on the file
} // End if errors
// Return a list of accessible properties from the file
return bodyArray
}
/**
* From a class we get the body content
*
* @param {[type]} theClass [description]
* @param {[type]} visibity [description]
* @return {[type]} [description]
*/
PhpCompletion.prototype.getBodyArrayFromClass = function(theClass, visibity, inherited) {
var $this = this
var result = []
for (var b in theClass.body) {
var prop = theClass.body[b]
if (visibity.indexOf(prop.visibility) !== -1) {
result.push({
"propObj": prop,
"inherited": (inherited ? true : false),
"className": theClass.name,
"loc": theClass.loc
})
}
}
// Class parent
if (theClass.extends) {
var parentName = theClass.extends.name
for (var f in $this.phpFiles) {
if ($this.phpFiles[f].name.indexOf(parentName) !== -1) {
result = result.concat($this.getBodyArray($this.getDocParsed($this.phpFiles[f]._contents), 'public|protected', true))
}
} // Endfor
} // End extends
// For while we are not able to find Interface methods =/
//
// if (theClass.implements) {
// for (var I in theClass.implements) {
// var Interface = theClass.implements[I]
// console.log(Interface.arguments())
// }
// }
return result
}
/**
* This method return the list of objects by the kind
* By default assign objects (either arguments)
*
* @param {[type]} objs [description]
* @param {[type]} kind [description]
* @return {[type]} [description]
*/
PhpCompletion.prototype.findBlocks = function(objs, kind) {
var $this = this
var result = []
// var scopeBlocks = "namespace|class|if|else|elseif|try|catch|finally|method|function|for|foreach|"
if (undefined === kind) {
kind = 'assign'
}
if (typeof objs === 'object') {
for (var i in objs) {
var item = objs[i]
if (null === item) {
continue
} else if (item.hasOwnProperty('loc')) {
// Already below the current line?
if (item.loc.start.line > $this.cursor.line) {
break
}
}
// Get arguments
if (item.hasOwnProperty('arguments')) {
for (var a in item.arguments) {
if (item.arguments[a].kind === 'parameter') {
result.push(item.arguments[a])
}
}
}
if (item.hasOwnProperty('kind') && kind.indexOf(item.kind) !== -1) {
result.push(item)
} else {
result = result.concat($this.findBlocks(item, kind))
}
}
}
return result
}
/**
* Php allow constructors to have parameters, when there's an extends class
* and this one theres no parameters, so that extended can provide instead
*
* @param {[object]} parsedFile result of this.getDocParsed() method
* @return {[array]} a list with arguments found
*/
PhpCompletion.prototype.findArgumentsByClassWithParents = function(parsedFile) {
var $this = this
var theClass = parsedFile.theClass
var className = theClass.name
var args = []
for (var i in theClass.body) {
if (theClass.body[i].kind === 'method' && (theClass.body[i].name === '__construct' || theClass.body[i].name === className)) {
args = theClass.body[i].arguments
// break
}
}
// Let's search for constructor in the parent
if (!args.length && theClass.extends) {
var classExtName = theClass.extends.name
// Fix class with use name
for (var i in parsedFile.usegroup) {
if (parsedFile.usegroup[i].indexOf(classExtName) !== -1) {
classExtName = '\\'+(parsedFile.usegroup[i].replace('^\\', ''))
}
}
// Search for this class and try to get its constructor arguments
// Recursive
for (var pf in $this.AllPhpParsedFiles) {
if ($this.AllPhpParsedFiles[pf].fullClassName.indexOf(classExtName) !== -1) {
args = $this.findArgumentsByClassWithParents($this.AllPhpParsedFiles[pf])
// break
}
}
}
return args
}
/**
* Return true if the cursor is after start loc and before end loc
*/
PhpCompletion.prototype.isCursorInside = function(loc) {
// console.log(loc.start.line+' < '+this.cursor.line+' > '+loc.end.line)
return ((loc.start.line < this.cursor.line) && (this.cursor.line < loc.end.line))
}
/**
* No matter what we do, the completion will be added from here.
* We must to provide in the 'this.whatIsIt' object the correct string
* to be prepended to the hintname
*
* @param {[type]} fromText [description]
*/
PhpCompletion.prototype.setInsertIndex = function(fromText) {
if (undefined === this.editor) {
return 0
}
var cursor = this.editor.getCursorPos()
var textBeforeCursor = this.editor.document.getRange({ line:cursor.line, ch: 0 }, cursor);
this.insertIndex = cursor.ch
if (fromText !== '') {
this.insertIndex = textBeforeCursor.lastIndexOf(fromText);
}
return this.insertIndex
}
/**
* Return a list of php predefined vars from php manual
* http://php.net/manual/en/reserved.variables.php
*/
PhpCompletion.prototype.getPredefinedVariables = function() {
return [
{name: 'this'},
{name: '_GET'},
{name: '_POST'},
{name: '_FILES'},
{name: '_SESSION'},
{name: '_COOKIE'},
{name: '_SERVER'},
{name: '_REQUEST'},
{name: '_ENV'},
{name: 'phperrormsg'},
{name: 'HTTP_RAW_POST_DATA'},
{name: 'http_response_header'},
{name: 'argc'},
{name: 'argv'}
]
}
PhpCompletion.prototype.hintExists = function(hintname) {
var exists = false
// It is a jquery object?
if (typeof hintname === 'object') {
hintname = hintname.data('content')
}
for(var i in this.hints) {
if (this.hints[i].data('content') === hintname) {
exists = true
break
}
}
return exists
}
/**
* Method called by HintProvider
*
* @param {[Editor]} editor [The Editor object]
* @param {[char]} implicitChar [Last typed char by user]
* @return {Boolean} [If there's hints to the current mouse position]
*/
PhpCompletion.prototype.hasHints = function (editor, implicitChar) {
// Reset result set
this.hints = []
// Document is not able to be edited
if (!editor.document.editable) {
return false
}
// Get needle information
this.editor = editor
this.lastChar = implicitChar
this.cursor = editor.getCursorPos()
var curCharPos = this.cursor.ch
var curLinePos = this.cursor.line
var lineStr = editor._codeMirror.getLine(curLinePos)
var textBeforeCursor = this.editor.document.getRange({line:curLinePos,ch:0}, this.cursor).trim()
// var totalLines = editor._codeMirror.doc.size
this.whatIsIt = lineStr.substr(0, curCharPos).replace(/.+(\s|\(|\,|\.)/, '')
this.search = lineStr.substr(0, curCharPos).replace(/.+(\s|\(|\,|\.)/, '')
// Get Variables
if (this.whatIsIt.indexOf('$') !== -1) {
// Remove everything before $
this.whatIsIt = '$'+(this.whatIsIt.replace(/(.+)?\$/gi, ''))
}
if (this.whatIsIt === '') {
return false
}
/**
* The found hint will be added from this word
*/
this.setInsertIndex(this.whatIsIt)
/**
* Depending on the type of element we'll get
* hints to complete the code
*/
if (this.whatIsIt.indexOf('$this->') !== -1) {
this.whatIsIt = '$this->'
// Redefine the search term and look for it into classes
this.search = this.search.replace(this.isThisRegexp, '')
var classHints = this.extractClassObjs(editor.document)
for (var i in classHints) {
if (!this.hintExists(classHints[i])) {
this.hints.push(classHints[i])
}
}
} else if (this.whatIsIt[0] === '$') {
if (this.whatIsIt.indexOf('>') !== -1) {
console.log('A class instance object')
} else {
var docParsed = this.getDocParsed(editor.document)
// Bug fix
if (!docParsed) {
return false
}
var scope = [].concat(this.findBlocks(docParsed.children), this.getPredefinedVariables())
this.whatIsIt = ''
for (var h in scope) {
var hint = scope[h]
var hintname = null
if (undefined !== hint.name) {
hintname = '$'+hint.name
} else if (undefined !== hint.left.name) {
hintname = '$'+hint.left.name
}
// The hint contains the search?
if (!hintname || hintname.toLowerCase().indexOf(this.search.toLowerCase()) === -1) {
continue
}
// Add if not exists yet
if (!this.hintExists(hintname)) {
this.hints.push(this.getHtmlHint(hintname, false, false, 'Variable', false))
}
}
}
} else {
// Here we search for 'new' word
var textBefore = textBeforeCursor.replace(this.whatIsIt, '').trim()
textBefore = textBefore.substr(textBefore.length -3) // 3 last letters
if (textBefore === 'new') {
this.setInsertIndex('new')
for (var f in this.AllPhpParsedFiles) {
var parsedFile = this.AllPhpParsedFiles[f]
// file: file,
// contents: data,
// docParsed: docParsed,
// namespace: namespace,
// theClass: theClass,
// usegroup: usegroup
// The name
if (!parsedFile.theClass) {
continue
}
var hintname = ''
hintname += (parsedFile.namespace ? '\\'+parsedFile.namespace.name+'\\' : '')
hintname += parsedFile.theClass.name
// Already added?
if (!this.hintExists(hintname) && hintname && hintname.indexOf(this.search) !== -1) {
// Args
var args = this.findArgumentsByClassWithParents(parsedFile)
// Comments
var comment = null
if (parsedFile.theClass.leadingComments && parsedFile.theClass.leadingComments.length) {
var comment = parsedFile.theClass.leadingComments
}
// Inherited
var inherited = (parsedFile.theClass.extends) ? parsedFile.theClass.extends.name : false
if (!inherited && !parsedFile.namespace) {
inherited = parsedFile.file.name
}
this.hints.push(this.getHtmlHint(
hintname,
args, // args
comment,
'Class', // Visibility is more like hintType @todo
inherited
))
}
}
this.whatIsIt = 'new '
} else {
console.log('anything')
}
}
// var token = TokenUtils.getInitialContext(editor._codeMirror, editor.getCursorPos());
return (this.hints.length !== 0)
}
/**
* Return the hints list
*
* @param {[char]} implicitChar [Last char typed by the user]
* @return {[Object]} The hints list
*/
PhpCompletion.prototype.getHints = function (implicitChar)
{
/** Fix type delay */
if (implicitChar !== this.lastChar) {
return false
}
return {
hints: this.hints,
match: null,
selectInitial: true,
handleWideResults: true
}
}
PhpCompletion.prototype.insertHint = function(hint) {
var $this = this
// console.log($this.whatIsIt)
// console.log(hint.data('content'))
var hinttext = String($this.whatIsIt + hint.data('content'))
// Replace in editor with hint content
$this.editor.document.replaceRange(
hinttext,
{ line: $this.cursor.line, ch: $this.insertIndex },
$this.cursor
);
return false
}
/**
* When app is ready to begin
* @param {PhpCompletion} ) { var phpCompletion [description]
* @return {[type]} [description]
*/
AppInit.appReady(function () {
var phpCompletion = new PhpCompletion()
// register the provider. Priority = 10 to be the provider of choice for php
CodeHintManager.registerHintProvider(phpCompletion, ["php"], 10);
})
});