Skip to content

Commit

Permalink
feat: 🎸 add option --no-php-syntax-check
Browse files Browse the repository at this point in the history
  • Loading branch information
shufo committed Oct 9, 2022
1 parent e1e0dac commit b7c29bd
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 46 deletions.
16 changes: 15 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,17 @@ export default async function cli() {
hidden: true,
default: true,
})
.option('no-php-syntax-check', {
type: 'boolean',
description: 'Disable PHP sytnax check',
default: false,
})
.option('php-syntax-check', {
type: 'boolean',
description: 'this is a workaround for combine strict && boolean option',
hidden: true,
default: true,
})
.option('progress', {
alias: 'p',
type: 'boolean',
Expand Down Expand Up @@ -132,7 +143,10 @@ export default async function cli() {
const wasm = await fs.readFile(require.resolve('vscode-oniguruma/release/onig.wasm'));
await loadWASM(wasm.buffer);

const options = _.set(parsed.argv, 'noMultipleEmptyLines', !parsed.argv.multipleEmptyLines);
const options = _.chain(parsed.argv)
.set('noMultipleEmptyLines', !parsed.argv.multipleEmptyLines)
.set('noPhpSyntaxCheck', !parsed.argv.phpSyntaxCheck)
.value();

if (parsed.argv.stdin) {
await process.stdin.pipe(
Expand Down
83 changes: 57 additions & 26 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Aigle from 'aigle';
import xregexp from 'xregexp';
import { sortClasses } from '@shufo/tailwindcss-class-sorter';
import { sortAttributes } from 'html-attribute-sorter';
import { FormatterOption, CLIOption } from './main';
import { FormatterOption, CLIOption, BladeFormatterOption } from './main';
import * as vsctm from './vsctm';
import * as util from './util';
import {
Expand Down Expand Up @@ -115,8 +115,15 @@ export default class Formatter {

wrapLineLength: any;

constructor(options: any) {
this.options = options;
defaultPhpFormatOption: util.FormatPhpOption;

constructor(options: BladeFormatterOption) {
this.options = {
...{
noPhpSyntaxCheck: false,
},
...options,
};
this.vsctm = util.optional(this.options).vsctm || vscodeTmModule;
this.oniguruma = util.optional(this.options).oniguruma;
this.indentCharacter = util.optional(this.options).useTabs ? '\t' : ' ';
Expand Down Expand Up @@ -155,6 +162,7 @@ export default class Formatter {
this.escapedBladeDirectives = [];
this.result = [];
this.diffs = [];
this.defaultPhpFormatOption = { noPhpSyntaxCheck: this.options.noPhpSyntaxCheck, printWidth: this.wrapLineLength };
}

formatContent(content: any) {
Expand Down Expand Up @@ -458,7 +466,9 @@ export default class Formatter {
let formatted: string = match;

formatted = _.replace(formatted, inlineFunctionRegex, (matched: any) =>
this.storeBladeDirective(util.formatRawStringAsPhp(matched)),
this.storeBladeDirective(
util.formatRawStringAsPhp(matched, { ...this.defaultPhpFormatOption, printWidth: util.printWidthForInline }),
),
);

formatted = _.replace(
Expand Down Expand Up @@ -1163,12 +1173,9 @@ export default class Formatter {
const indent = detectIndent(matchedLine[0]);

if (this.isInline(rawBlock) && this.isMultilineStatement(rawBlock)) {
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`).trim();
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`, this.defaultPhpFormatOption).trim();
} else if (rawBlock.split('\n').length > 1) {
rawBlock = util
.formatStringAsPhp(`<?php${rawBlock}?>`)
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 1.
.trimRight('\n');
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`, this.defaultPhpFormatOption).trimRight('\n');
} else {
rawBlock = `<?php${rawBlock}?>`;
}
Expand All @@ -1192,7 +1199,13 @@ export default class Formatter {
return _.replace(
content,
new RegExp(regex, 'gms'),
(_match: any, p1: any) => `@props(${util.formatRawStringAsPhp(this.rawPropsBlocks[p1]).trimRight()})`,
(_match: any, p1: any) =>
`@props(${util
.formatRawStringAsPhp(this.rawPropsBlocks[p1], {
...this.defaultPhpFormatOption,
printWidth: util.printWidthForInline,
})
.trimRight()})`,
);
}

Expand All @@ -1201,7 +1214,7 @@ export default class Formatter {
}

isMultilineStatement(rawBlock: any) {
return util.formatStringAsPhp(`<?php${rawBlock}?>`).trimRight().split('\n').length > 1;
return util.formatStringAsPhp(`<?php${rawBlock}?>`, this.defaultPhpFormatOption).trimRight().split('\n').length > 1;
}

indentRawBlock(indent: detectIndent.Indent, content: any) {
Expand Down Expand Up @@ -1427,9 +1440,9 @@ export default class Formatter {
const indent = detectIndent(matchedLine[0]);

if (this.isInline(rawBlock) && this.isMultilineStatement(rawBlock)) {
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`).trim();
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`, this.defaultPhpFormatOption).trim();
} else if (rawBlock.split('\n').length > 1) {
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`).trim();
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`, this.defaultPhpFormatOption).trim();
} else {
rawBlock = `<?php${rawBlock}?>`;
}
Expand Down Expand Up @@ -1507,7 +1520,11 @@ export default class Formatter {

if (this.isInline(bladeBrace)) {
return `{{ ${util
.formatRawStringAsPhp(bladeBrace, 1000, false)
.formatRawStringAsPhp(bladeBrace, {
...this.defaultPhpFormatOption,
trailingCommaPHP: false,
printWidth: util.printWidthForInline,
})
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.split('\n')
.map((line) => line.trim())
Expand All @@ -1519,7 +1536,7 @@ export default class Formatter {
return `{{ ${this.indentRawPhpBlock(
indent,
util
.formatRawStringAsPhp(bladeBrace, this.wrapLineLength, true)
.formatRawStringAsPhp(bladeBrace, this.defaultPhpFormatOption)
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 1.
Expand Down Expand Up @@ -1548,7 +1565,7 @@ export default class Formatter {
return this.indentRawPhpBlock(
indent,
`{!! ${util
.formatRawStringAsPhp(bladeBrace, this.wrapLineLength)
.formatRawStringAsPhp(bladeBrace, this.defaultPhpFormatOption)
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()} !!}`,
);
Expand Down Expand Up @@ -1583,7 +1600,7 @@ export default class Formatter {
return this.indentComponentAttribute(
indent.indent,
util
.formatRawStringAsPhp(matched, this.wrapLineLength, true)
.formatRawStringAsPhp(matched, this.defaultPhpFormatOption)
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.replace(/(?<!(['"]).*)(?<=\()[\n\s]+?(?=\w)/gms, '')
.replace(/,[\n\s]*?\)/gs, ')')
Expand Down Expand Up @@ -1616,7 +1633,7 @@ export default class Formatter {

if (matched.includes('@php')) {
return `${util
.formatRawStringAsPhp(matched)
.formatRawStringAsPhp(matched, { ...this.defaultPhpFormatOption, printWidth: util.printWidthForInline })
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 1.
Expand All @@ -1642,7 +1659,7 @@ export default class Formatter {
}

let inside = util
.formatRawStringAsPhp(`func(${p4})`, wrapLength, true)
.formatRawStringAsPhp(`func(${p4})`, { ...this.defaultPhpFormatOption, printWidth: wrapLength })
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.replace(/,(\s*?\))/gis, (_match5, p5) => p5)
.trim();
Expand All @@ -1666,7 +1683,9 @@ export default class Formatter {
return formatted;
}

return `${util.formatRawStringAsPhp(matched).trimEnd()}`;
return `${util
.formatRawStringAsPhp(matched, { ...this.defaultPhpFormatOption, printWidth: util.printWidthForInline })
.trimEnd()}`;
},
),
);
Expand All @@ -1693,9 +1712,8 @@ export default class Formatter {
}

const result = util
.formatStringAsPhp(this.rawPhpTags[p1])
.formatStringAsPhp(this.rawPhpTags[p1], this.defaultPhpFormatOption)
.trim()
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 1.
.trimRight('\n');

if (this.isInline(result)) {
Expand Down Expand Up @@ -1781,7 +1799,10 @@ export default class Formatter {
return _.replace(matched, /(@[a-zA-z0-9\-_]+)(.*)/gis, (match2: string, p2: string, p3: string) => {
try {
const formatted = util
.formatRawStringAsPhp(`func${p3}`)
.formatRawStringAsPhp(`func${p3}`, {
...this.defaultPhpFormatOption,
printWidth: util.printWidthForInline,
})
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()
.substring(4);
Expand All @@ -1808,7 +1829,7 @@ export default class Formatter {
return _.replace(matched, /(@[a-zA-z0-9\-_]+)(.*)/gis, (match2: string, p3: string, p4: string) => {
try {
const formatted = util
.formatRawStringAsPhp(`func${p4}`, this.wrapLineLength, false)
.formatRawStringAsPhp(`func${p4}`, { ...this.defaultPhpFormatOption, trailingCommaPHP: false })
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()
.substring(4);
Expand Down Expand Up @@ -1954,13 +1975,23 @@ export default class Formatter {

if (this.isInline(p4)) {
try {
return `${p2}${p3}${util.formatRawStringAsPhp(p4, this.wrapLineLength - indent.amount).trimEnd()}`;
return `${p2}${p3}${util
.formatRawStringAsPhp(p4, {
...this.defaultPhpFormatOption,
printWidth: this.wrapLineLength - indent.amount,
})
.trimEnd()}`;
} catch (error) {
return `${p2}${p3}${p4}`;
}
}

return `${p2}${p3}${util.formatRawStringAsPhp(p4, this.wrapLineLength - indent.amount).trimEnd()}`;
return `${p2}${p3}${util
.formatRawStringAsPhp(p4, {
...this.defaultPhpFormatOption,
printWidth: this.wrapLineLength - indent.amount,
})
.trimEnd()}`;
},
);

Expand Down
1 change: 1 addition & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type FormatterOption = {
tailwindcssConfig?: TailwindConfig;
sortHtmlAttributes?: SortHtmlAttributes;
noMultipleEmptyLines?: boolean;
noPhpSyntaxCheck?: boolean;
};

export type BladeFormatterOption = CLIOption & FormatterOption;
Expand Down
2 changes: 2 additions & 0 deletions src/runtimeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface RuntimeConfig {
tailwindcssConfigPath?: string;
sortHtmlAttributes?: SortHtmlAttributes;
noMultipleEmptyLines?: boolean;
noPhpSyntaxCheck?: boolean;
}

const defaultConfigNames = ['.bladeformatterrc.json', '.bladeformatterrc'];
Expand Down Expand Up @@ -80,6 +81,7 @@ export async function readRuntimeConfig(filePath: string | null): Promise<Runtim
nullable: true,
},
noMultipleEmptyLines: { type: 'boolean', nullable: true },
noPhpSyntaxCheck: { type: 'boolean', nullable: true },
},
additionalProperties: true,
};
Expand Down
82 changes: 63 additions & 19 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,73 @@ export function splitByLines(content: any) {
return content.split(/\r\n|\n|\r/);
}

export function formatStringAsPhp(content: any) {
return prettier.format(content.replace(/\n$/, ''), {
parser: 'php',
printWidth: 1000,
singleQuote: true,
// @ts-ignore
phpVersion: '8.0',
plugins: [phpPlugin],
});
}
export type FormatPhpOption = {
noPhpSyntaxCheck?: boolean;
printWidth?: number;
trailingCommaPHP?: boolean;
phpVersion?: string;
singleQuote?: boolean;
};

export function formatRawStringAsPhp(content: any, printWidth = 1000, trailingCommaPHP = true) {
return prettier
.format(`<?php echo ${content} ?>`, {
export const printWidthForInline = 1000;

const defaultFormatPhpOption = {
noPhpSyntaxCheck: false,
printWidth: printWidthForInline,
trailingCommaPHP: true,
phpVersion: '8.1',
singleQuote: true,
};

export function formatStringAsPhp(content: any, options: FormatPhpOption = {}) {
options = {
...defaultFormatPhpOption,
...options,
};

try {
return prettier.format(content.replace(/\n$/, ''), {
parser: 'php',
printWidth,
singleQuote: true,
printWidth: 1000,
singleQuote: options.singleQuote,
// @ts-ignore
phpVersion: '8.0',
trailingCommaPHP,
phpVersion: options.phpVersion,
trailingCommaPHP: options.trailingCommaPHP,
plugins: [phpPlugin],
})
.replace(/<\?php echo (.*)?\?>/gs, (match: any, p1: any) => p1.trim().replace(/;\s*$/, ''));
});
} catch (error) {
if (options.noPhpSyntaxCheck === false) {
throw error;
}
return content;
}
}

export function formatRawStringAsPhp(content: string, options: FormatPhpOption = {}) {
options = {
...defaultFormatPhpOption,
...options,
};

try {
return prettier
.format(`<?php echo ${content} ?>`, {
parser: 'php',
printWidth: options.printWidth,
singleQuote: options.singleQuote,
// @ts-ignore
phpVersion: options.phpVersion,
trailingCommaPHP: options.trailingCommaPHP,
plugins: [phpPlugin],
})
.replace(/<\?php echo (.*)?\?>/gs, (match: any, p1: any) => p1.trim().replace(/;\s*$/, ''));
} catch (error) {
if (options.noPhpSyntaxCheck === false) {
throw error;
}

return content;
}
}

export function getArgumentsCount(expression: any) {
Expand Down

0 comments on commit b7c29bd

Please sign in to comment.