@rightcapital/php-parser
Version:
TypeScript types for PHP Parser JSON representation
53 lines (52 loc) • 2.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PhpDocHelpers = void 0;
const node_path_1 = require("node:path");
const phpdoc_parser_1 = require("@rightcapital/phpdoc-parser");
const extended_php_doc_transpiler_1 = require("./extended-php-doc-transpiler");
const file_path_helpers_1 = require("./file-path-helpers");
const type_generation_helpers_1 = require("./type-generation-helpers");
class PhpDocHelpers {
static parseCommentTextToTagValueNode(commentText) {
const lexer = new phpdoc_parser_1.Lexer();
const constExprParser = new phpdoc_parser_1.ConstExprParser();
const typeParser = new phpdoc_parser_1.TypeParser(constExprParser);
const phpDocParser = new phpdoc_parser_1.PhpDocParser(typeParser, constExprParser);
const tokens = new phpdoc_parser_1.TokenIterator(lexer.tokenize(commentText));
const astRootNode = phpDocParser.parse(tokens);
const varTagValueNode = PhpDocHelpers.getTagValueNodeFromAstRootNode(astRootNode);
return varTagValueNode;
}
static getTypescriptTypeFromTypeNode(typeNode, filePathParts, fileRelativePath, uses) {
const nameNodePathResolver = (nodeParts) => {
const targetTypeFilePath = file_path_helpers_1.FilePathHelpers.getFilePathFromNameNodeParts(nodeParts, 'Name', filePathParts, uses);
const name = type_generation_helpers_1.TypeGenerationHelpers.getGroupedTypeNameForNode(file_path_helpers_1.FilePathHelpers.getFullyQualifiedParentNodeNameByFilePath(fileRelativePath, targetTypeFilePath, nodeParts.at(-1)));
const path = (0, node_path_1.join)(file_path_helpers_1.FilePathHelpers.getRelativePathToTypesRootPathByPhpFileParts(filePathParts), 'types');
return {
name,
path,
isTypeOnly: true,
};
};
const transpiler = new extended_php_doc_transpiler_1.ExtendedTranspiler(nameNodePathResolver);
transpiler.beforeTranspile();
const transpiledTypeNode = transpiler.transpile(typeNode);
const importDeclarations = transpiler.getImportDeclarations();
const outputTsTypeGeneratedString = (0, phpdoc_parser_1.renderTsNodeToString)(transpiledTypeNode);
const importDeclarationGeneratedStrings = importDeclarations.map((importDeclaration) => (0, phpdoc_parser_1.renderTsNodeToString)(importDeclaration));
return {
transpiledTypeNode,
importDeclarations,
outputTsTypeGeneratedString,
importDeclarationGeneratedStrings,
};
}
static getTagValueNodeFromAstRootNode(astRootNode) {
const varTagValueNode = astRootNode.getVarTagValues()[0];
if (!varTagValueNode) {
throw Error('It should have at least one var tag in the comment section');
}
return varTagValueNode;
}
}
exports.PhpDocHelpers = PhpDocHelpers;