Skip to content

Commit

Permalink
feat: generate fully indented, beautiful code
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Sep 25, 2019
1 parent 13a882f commit 2d45fd4
Show file tree
Hide file tree
Showing 3 changed files with 230 additions and 176 deletions.
10 changes: 9 additions & 1 deletion src/emitters/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,15 @@ export abstract class Emitter {
public writeNewLine () {
this.write('\n')
}
public writeLine (str) {
public nextLine (str: string) {
this.writeIndent()
this.write(str)
}
public feedLine (str: string) {
this.write(str)
this.writeNewLine()
}
public writeLine (str: string) {
this.writeIndent()
this.write(str)
this.writeNewLine()
Expand Down
70 changes: 68 additions & 2 deletions src/emitters/php-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,78 @@ export class PHPEmitter extends Emitter {
this.writeHTML(ExpressionEmitter.stringLiteralize(buffer))
}

public beginIf (expr) {
this.writeLine(`if (${expr}) {`)
/**
* function
*/
public writeFunction (name = '', args = [], use = [], body: Function = () => null) {
const nameStr = name ? `${name} ` : ''
const argsStr = args.join(', ')
const useStr = use.length ? `use (${use.join(', ')}) ` : ''
this.write(`function ${nameStr}(${argsStr}) ${useStr}{`)
this.writeNewLine()
this.indent()
body()
this.unindent()
this.writeIndent()
this.write('}')
}
public writeAnonymousFunction (args = [], use = [], body: Function = () => null) {
this.writeFunction('', args, use, body)
}
public writeFunctionCall (name: string, args: string[]) {
this.write(`${name}(${args.join(', ')})`)
}

/**
* if
*/
public writeIf (expr: string, cb: Function) {
this.beginIf(expr)
cb()
this.endIf()
}
public beginIf (expr: string) {
this.beginBlock(`if (${expr})`)
}
public beginElseIf (expr: string) {
this.beginBlock(`else if (${expr})`)
}
public beginElse () {
this.beginBlock(`else`)
}
public endIf () {
this.endBlock()
}

/**
* foreach
*/

public writeForeach (expr: string, cb: Function) {
this.beginForeach(expr)
cb()
this.endForeach()
}
public beginForeach (expr: string) {
this.beginBlock(`foreach (${expr})`)
}
public endForeach () {
this.endBlock()
}

/**
* block
*/
public writeBlock (expr: string, cb: Function) {
this.beginBlock(expr)
cb()
this.endBlock()
}
public beginBlock (expr: string) {
this.writeLine(`${expr} {`)
this.indent()
}
public endBlock () {
this.unindent()
this.writeLine(`}`)
}
Expand Down
Loading

0 comments on commit 2d45fd4

Please sign in to comment.