Skip to content
This repository has been archived by the owner on Sep 6, 2021. It is now read-only.

Php Tooling Extensions Using LSP Framework #14671

Merged
merged 21 commits into from
Apr 3, 2019
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 205 additions & 0 deletions src/extensions/default/PhpTooling/CodeHintsProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/*
* Copyright (c) 2019 - present Adobe. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/

/* eslint-disable indent */
/* eslint max-len: ["error", { "code": 200 }]*/
define(function (require, exports, module) {
"use strict";

var _ = brackets.getModule("thirdparty/lodash");

var EditorManager = brackets.getModule('editor/EditorManager'),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
TokenUtils = brackets.getModule("utils/TokenUtils"),
StringMatch = brackets.getModule("utils/StringMatch"),
matcher = new StringMatch.StringMatcher({
preferPrefixMatches: true
});

ExtensionUtils.loadStyleSheet(module, "../../../languageTools/styles/default_provider_style.css");
var phpSuperGlobalVariables = JSON.parse(require("text!phpGlobals.json"));

function CodeHintsProvider(client) {
this.client = client;
this.query = "";
}

function formatTypeDataForToken($hintObj, token) {
$hintObj.addClass('brackets-hints-with-type-details');
if (token.detail) {
if (token.detail.trim() !== '?') {
if (token.detail.length < 30) {
$('<span>' + token.detail.split('->').join(':').toString().trim() + '</span>').appendTo($hintObj).addClass("brackets-hints-type-details");
}
$('<span>' + token.detail.split('->').join(':').toString().trim() + '</span>').appendTo($hintObj).addClass("hint-description");
}
} else {
if (token.keyword) {
$('<span>keyword</span>').appendTo($hintObj).addClass("brackets-hints-keyword");
}
}
if (token.documentation) {
$hintObj.attr('title', token.documentation);
$('<span></span>').text(token.documentation.trim()).appendTo($hintObj).addClass("hint-doc");
}
}

function filterWithQueryAndMatcher(hints, query) {
var matchResults = $.map(hints, function (hint) {
var searchResult = matcher.match(hint.label, query);
if (searchResult) {
for (var key in hint) {
searchResult[key] = hint[key];
}
}

return searchResult;
});

return matchResults;
}

CodeHintsProvider.prototype.hasHints = function (editor, implicitChar) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add the ability to add static hints in the Default Provider itself.

if (!this.client) {
return false;
}

return true;
};

CodeHintsProvider.prototype.getHints = function (implicitChar) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need this file. You can create override the getHInts function of the DefaultProvider object since that is the only place is where you need to change anything. See my comments below.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see my comment below

if (!this.client) {
return null;
}

var editor = EditorManager.getActiveEditor(),
pos = editor.getCursorPos(),
docPath = editor.document.file._path,
$deferredHints = $.Deferred(),
self = this;

this.client.requestHints({
filePath: docPath,
cursorPos: pos
}).done(function (msgObj) {
var context = TokenUtils.getInitialContext(editor._codeMirror, pos),
hints = [];

self.query = context.token.string.slice(0, context.pos.ch - context.token.start);
if (msgObj) {
var res = msgObj.items || [];
// There is a bug in Php Language Server, Php Language Server does not provide superGlobals
// Variables as completion. so these variables are being explicity put in response objects
// below code should be removed if php server fix this bug.
for(var key in phpSuperGlobalVariables) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should add the static hints here always, otherwise we'll show hints even when they are not required. It should only come when implicitChar is '$', or otherwise filtered by the current token's prefix in case the token starts with '$'.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it will shown only if prefix is '$'. in below code "filterWithQueryAndMatcher" will filter it.

res.push({
label: key,
documentation: phpSuperGlobalVariables[key].description,
detail: phpSuperGlobalVariables[key].type
});
}

var filteredHints = filterWithQueryAndMatcher(res, self.query);

StringMatch.basicMatchSort(filteredHints);
filteredHints.forEach(function (element) {
var $fHint = $("<span>")
.addClass("brackets-hints");

if (element.stringRanges) {
element.stringRanges.forEach(function (item) {
if (item.matched) {
$fHint.append($("<span>")
.append(_.escape(item.text))
.addClass("matched-hint"));
} else {
$fHint.append(_.escape(item.text));
}
});
} else {
$fHint.text(element.label);
}

$fHint.data("token", element);
formatTypeDataForToken($fHint, element);
hints.push($fHint);
});
}

$deferredHints.resolve({
"hints": hints
});
}).fail(function () {
$deferredHints.reject();
});

return $deferredHints;
};

CodeHintsProvider.prototype.insertHint = function ($hint) {
var start = {
line: -1,
ch: -1
},
end = {
line: -1,
ch: -1
},
editor = EditorManager.getActiveEditor(),
cursor = editor.getCursorPos(),
token = $hint.data("token"),
txt = null,
query = this.query;

start = {
line: cursor.line,
ch: cursor.ch - query.length
};

end = {
line: cursor.line,
ch: cursor.ch
};

txt = token.label;
if (token.textEdit && token.textEdit.newText) {
txt = token.textEdit.newText;
start = {
line: token.textEdit.range.start.line,
ch: token.textEdit.range.start.character
};
end = {
line: token.textEdit.range.end.line,
ch: token.textEdit.range.end.character
};
}

if (editor) {
editor.document.replaceRange(txt, start, end);
}
// Return false to indicate that another hinting session is not needed
return false;
};

exports.CodeHintsProvider = CodeHintsProvider;
});
120 changes: 120 additions & 0 deletions src/extensions/default/PhpTooling/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright (c) 2019 - present Adobe. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global exports */
/*global process */
/*eslint-env es6, node*/
/*eslint max-len: ["error", { "code": 200 }]*/
"use strict";

var LanguageClient = require(global.LanguageClientInfo.languageClientPath).LanguageClient,
net = require("net"),
cp = require("child_process"),
execa = require("execa"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you introducing a new node_module? (execa)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes execa and semver

semver = require('semver'),
clientName = "PhpClient",
executablePath = "",
memoryLimit = "";

function validatePhpExecutable(confParams) {
executablePath = confParams["executablePath"] ||
(process.platform === 'win32' ? 'php.exe' : 'php');

memoryLimit = confParams["memoryLimit"] || '4095M';

return new Promise(function (resolve, reject) {
if (memoryLimit !== '-1' && !/^\d+[KMG]?$/.exec(memoryLimit)) {
reject("PHP_SERVER_MEMORY_LIMIT_INVALID");
return;
}

execa.stdout(executablePath, ['--version']).then(function (output) {
var matchStr = output.match(/^PHP ([^\s]+)/m);
if (!matchStr) {
reject("PHP_VERSION_INVALID");
return;
}
var version = matchStr[1].split('-')[0];
if (!/^\d+.\d+.\d+$/.test(version)) {
version = version.replace(/(\d+.\d+.\d+)/, '$1-');
}
if (semver.lt(version, '7.0.0')) {
reject(["PHP_UNSUPPORTED_VERSION", version]);
return;
}
resolve();
}).catch(function (err) {
if (err.code === 'ENOENT') {
reject("PHP_EXECUTABLE_NOT_FOUND");
} else {
reject(["PHP_PROCESS_SPAWN_ERROR", err.code]);
console.error(err);
}
return;
});
});
}

var serverOptions = function () {
return new Promise(function (resolve, reject) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: The indentation seems off here.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indentation is correct

var server = net.createServer(function (socket) {
console.log('PHP process connected');
socket.on('end', function () {
console.log('PHP process disconnected');
});
server.close();
resolve({
reader: socket,
writer: socket
});
});
server.listen(0, '127.0.0.1', function () {
var pathToPHP = __dirname + "/vendor/felixfbecker/language-server/bin/php-language-server.php";
var childProcess = cp.spawn(executablePath, [
pathToPHP,
'--tcp=127.0.0.1:' + server.address().port,
'--memory-limit=' + memoryLimit
]);
childProcess.stderr.on('data', function (chunk) {
var str = chunk.toString();
console.log('PHP Language Server:', str);
});
childProcess.on('exit', function (code, signal) {
console.log(
"Language server exited " + (signal ? "from signal " + signal : "with exit code " + code)
);
});
return childProcess;
});
});
},
options = {
serverOptions: serverOptions
};


function init(domainManager) {
var client = new LanguageClient(clientName, domainManager, options);
client.addOnRequestHandler('validatePhpExecutable', validatePhpExecutable);
}

exports.init = init;
7 changes: 7 additions & 0 deletions src/extensions/default/PhpTooling/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"felixfbecker/language-server": "^5.4"
}
}
Loading