Skip to content

Commit

Permalink
feat: 🎸 --no-single-quote option
Browse files Browse the repository at this point in the history
  • Loading branch information
shufo committed Jul 16, 2023
1 parent 717e834 commit c0505c2
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 33 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ $ blade-formatter -c -d resources/**/*.blade.php
--tailwindcss-config-path Specify path of tailwind config [string] [default: null]
--sort-html-attributes Sort HTML attributes. [string] [choices: "none", "alphabetical", "code-guide", "idiomatic", "vuejs", "custom"] [default: none]
--custom-html-attributes-order Comma separated custom HTML attributes order. To enable this you must specify sort html attributes option as `custom`. You can use regex for attribute names. [string] [default: null]
--no-single-quote Use double quotes instead of single quotes for php expression. [boolean] [default: false]
--no-multiple-empty-lines Merge multiple blank lines into a single blank line [boolean] [default: false]
--no-php-syntax-check Disable PHP sytnax checking [boolean] [default: false]
-p, --progress Print progress [boolean] [default: false]
Expand Down
12 changes: 12 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,17 @@ export default async function cli() {
'Comma separated custom HTML attributes order. To enable this you must specify sort html attributes option as `custom`. You can use regex for attribute names.',
default: null,
})
.option('no-single-quote', {
type: 'boolean',
description: 'Use double quotes instead of single quotes for php expression.',
default: false,
})
.option('single-quote', {
type: 'boolean',
description: 'this is a workaround for combine strict && boolean option',
hidden: true,
default: true,
})
.option('no-multiple-empty-lines', {
type: 'boolean',
description: 'Merge multiple blank lines into a single blank line',
Expand Down Expand Up @@ -159,6 +170,7 @@ export default async function cli() {
const options = _.chain(parsed.argv)
.set('noMultipleEmptyLines', !parsed.argv.multipleEmptyLines)
.set('noPhpSyntaxCheck', !parsed.argv.phpSyntaxCheck)
.set('noSingleQuote', !parsed.argv.singleQuote)
.value();

if (parsed.argv.stdin) {
Expand Down
5 changes: 5 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const constants = {
defaultPrintWidth: 120,
};

export default constants;
43 changes: 21 additions & 22 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { nestedParenthesisRegex } from './regex';
import { SortHtmlAttributes } from './runtimeConfig';
import { formatPhpComment } from './comment';
import { adjustSpaces } from './space';
import constants from './constants';

export default class Formatter {
argumentCheck: any;
Expand Down Expand Up @@ -128,6 +129,7 @@ export default class Formatter {
this.options = {
...{
noPhpSyntaxCheck: false,
printWidth: constants.defaultPrintWidth,
},
...options,
};
Expand Down Expand Up @@ -182,7 +184,7 @@ export default class Formatter {
.then((target) => this.preserveCurlyBraceForJS(target))
.then((target) => this.preserveRawPhpTags(target))
.then((target) => this.preserveEscapedBladeDirective(target))
.then((target) => util.formatAsPhp(target))
.then((target) => util.formatAsPhp(target, this.options))
.then((target) => this.preserveBladeComment(target))
.then((target) => this.preserveBladeBrace(target))
.then((target) => this.preserveRawBladeBrace(target))
Expand Down Expand Up @@ -484,7 +486,7 @@ export default class Formatter {

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

Expand Down Expand Up @@ -1268,9 +1270,9 @@ export default class Formatter {
const indent = detectIndent(matchedLine[0]);

if (this.isInline(rawBlock) && this.isMultilineStatement(rawBlock)) {
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`, this.defaultPhpFormatOption).trim();
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`, this.options).trim();
} else if (rawBlock.split('\n').length > 1) {
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`, this.defaultPhpFormatOption).trimRight('\n');
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`, this.options).trimRight('\n');
} else {
rawBlock = `<?php${rawBlock}?>`;
}
Expand Down Expand Up @@ -1299,7 +1301,7 @@ export default class Formatter {
(_match: any, p1: any) =>
`@props(${util
.formatRawStringAsPhp(this.rawPropsBlocks[p1], {
...this.defaultPhpFormatOption,
...this.options,
printWidth: util.printWidthForInline,
})
.trimRight()})`,
Expand All @@ -1311,7 +1313,7 @@ export default class Formatter {
}

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

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

if (this.isInline(rawBlock) && this.isMultilineStatement(rawBlock)) {
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`, this.defaultPhpFormatOption).trim();
rawBlock = util.formatStringAsPhp(`<?php\n${rawBlock}\n?>`, this.options).trim();
} else if (rawBlock.split('\n').length > 1) {
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`, this.defaultPhpFormatOption).trim();
rawBlock = util.formatStringAsPhp(`<?php${rawBlock}?>`, this.options).trim();
} else {
rawBlock = `<?php${rawBlock}?>`;
}
Expand Down Expand Up @@ -1715,7 +1717,7 @@ export default class Formatter {
if (this.isInline(bladeBrace)) {
return `{{ ${util
.formatRawStringAsPhp(bladeBrace, {
...this.defaultPhpFormatOption,
...this.options,
trailingCommaPHP: false,
printWidth: util.printWidthForInline,
})
Expand All @@ -1730,7 +1732,7 @@ export default class Formatter {
return `{{ ${this.indentRawPhpBlock(
indent,
util
.formatRawStringAsPhp(bladeBrace, this.defaultPhpFormatOption)
.formatRawStringAsPhp(bladeBrace, this.options)
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 1.
Expand Down Expand Up @@ -1759,7 +1761,7 @@ export default class Formatter {
return this.indentRawPhpBlock(
indent,
`{!! ${util
.formatRawStringAsPhp(bladeBrace, this.defaultPhpFormatOption)
.formatRawStringAsPhp(bladeBrace, this.options)
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()} !!}`,
);
Expand Down Expand Up @@ -1819,7 +1821,7 @@ export default class Formatter {

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

return `${util
.formatRawStringAsPhp(matched, { ...this.defaultPhpFormatOption, printWidth: util.printWidthForInline })
.formatRawStringAsPhp(matched, { ...this.options, printWidth: util.printWidthForInline })
.trimEnd()}`;
},
),
Expand All @@ -1879,10 +1881,7 @@ export default class Formatter {
return matched;
}

const result = util
.formatStringAsPhp(this.rawPhpTags[p1], this.defaultPhpFormatOption)
.trim()
.trimRight('\n');
const result = util.formatStringAsPhp(this.rawPhpTags[p1], this.options).trim().trimRight('\n');

if (this.isInline(result)) {
return result;
Expand Down Expand Up @@ -1972,7 +1971,7 @@ export default class Formatter {
try {
const formatted = util
.formatRawStringAsPhp(`func${p3}`, {
...this.defaultPhpFormatOption,
...this.options,
printWidth: util.printWidthForInline,
})
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
Expand Down Expand Up @@ -2002,7 +2001,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.defaultPhpFormatOption, trailingCommaPHP: false })
.formatRawStringAsPhp(`func${p4}`, { ...this.options, trailingCommaPHP: false })
.replace(/([\n\s]*)->([\n\s]*)/gs, '->')
.trim()
.substring(4);
Expand Down Expand Up @@ -2150,7 +2149,7 @@ export default class Formatter {
try {
return `${p2}${p3}${util
.formatRawStringAsPhp(p4, {
...this.defaultPhpFormatOption,
...this.options,
printWidth: this.wrapLineLength - indent.amount,
})
.trimEnd()}`;
Expand All @@ -2161,7 +2160,7 @@ export default class Formatter {

return `${p2}${p3}${util
.formatRawStringAsPhp(p4, {
...this.defaultPhpFormatOption,
...this.options,
printWidth: this.wrapLineLength - indent.amount,
})
.trimEnd()}`;
Expand Down Expand Up @@ -2436,7 +2435,7 @@ export default class Formatter {
) {
const formatTarget = `func(${matchedExpression})`;
const formattedExpression = util.formatRawStringAsPhp(formatTarget, {
...this.defaultPhpFormatOption,
...this.options,
printWidth: wrapLength ?? this.defaultPhpFormatOption.printWidth,
});

Expand Down
1 change: 1 addition & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export type FormatterOption = {
customHtmlAttributesOrder?: string[] | string;
noMultipleEmptyLines?: boolean;
noPhpSyntaxCheck?: boolean;
noSingleQuote?: 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 @@ -31,6 +31,7 @@ export interface RuntimeConfig {
customHtmlAttributesOrder?: string[] | string;
noMultipleEmptyLines?: boolean;
noPhpSyntaxCheck?: boolean;
noSingleQuote?: boolean;
}

const defaultConfigNames = ['.bladeformatterrc.json', '.bladeformatterrc'];
Expand Down Expand Up @@ -88,6 +89,7 @@ export async function readRuntimeConfig(filePath: string | null): Promise<Runtim
customHtmlAttributesOrder: { type: 'array', nullable: true, items: { type: 'string' }, default: [] },
noMultipleEmptyLines: { type: 'boolean', nullable: true },
noPhpSyntaxCheck: { type: 'boolean', nullable: true },
noSingleQuote: { type: 'boolean', nullable: true },
},
additionalProperties: true,
};
Expand Down
22 changes: 11 additions & 11 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export type FormatPhpOption = {
printWidth?: number;
trailingCommaPHP?: boolean;
phpVersion?: string;
singleQuote?: boolean;
noSingleQuote?: boolean;
};

export const printWidthForInline = 1000;
Expand All @@ -55,7 +55,7 @@ const defaultFormatPhpOption = {
printWidth: printWidthForInline,
trailingCommaPHP: true,
phpVersion: '8.1',
singleQuote: true,
noSingleQuote: false,
};

export function formatStringAsPhp(content: any, params: FormatPhpOption = {}) {
Expand All @@ -68,7 +68,7 @@ export function formatStringAsPhp(content: any, params: FormatPhpOption = {}) {
return prettier.format(content.replace(/\n$/, ''), {
parser: 'php',
printWidth: 1000,
singleQuote: options.singleQuote,
singleQuote: !options.noSingleQuote,
// @ts-ignore
phpVersion: options.phpVersion,
trailingCommaPHP: options.trailingCommaPHP,
Expand All @@ -93,7 +93,7 @@ export function formatRawStringAsPhp(content: string, params: FormatPhpOption =
.format(`<?php echo ${content} ?>`, {
parser: 'php',
printWidth: options.printWidth,
singleQuote: options.singleQuote,
singleQuote: !options.noSingleQuote,
// @ts-ignore
phpVersion: options.phpVersion,
trailingCommaPHP: options.trailingCommaPHP,
Expand Down Expand Up @@ -164,7 +164,7 @@ export function generateDiff(path: any, originalLines: any, formattedLines: any)
return _.without(diff, null);
}

export async function prettifyPhpContentWithUnescapedTags(content: any) {
export async function prettifyPhpContentWithUnescapedTags(content: string, options: FormatPhpOption) {
const directives = _.without(indentStartTokens, '@switch', '@forelse', '@php').join('|');

const directiveRegexes = new RegExp(
Expand All @@ -176,7 +176,7 @@ export async function prettifyPhpContentWithUnescapedTags(content: any) {
return new Promise((resolve) => resolve(content))
.then((res: any) =>
_.replace(res, directiveRegexes, (match: any, p1: any, p2: any, p3: any) =>
formatStringAsPhp(`<?php ${p1.substr('1')}${p2}(${p3}) ?>`)
formatStringAsPhp(`<?php ${p1.substr('1')}${p2}(${p3}) ?>`, options)
.replace(
/<\?php\s(.*?)(\s*?)\((.*?)\);*\s\?>\n/gs,
(match2: any, j1: any, j2: any, j3: any) => `@${j1.trim()}${j2}(${j3.trim()})`,
Expand All @@ -186,14 +186,14 @@ export async function prettifyPhpContentWithUnescapedTags(content: any) {
.replace(/(?:\n\s*)* as(?= (?:&{0,1}\$[\w]+|list|\[\$[\w]+))/g, ' as'),
),
)
.then((res) => formatStringAsPhp(res));
.then((res) => formatStringAsPhp(res, options));
}

export async function prettifyPhpContentWithEscapedTags(content: any) {
export async function prettifyPhpContentWithEscapedTags(content: string, options: FormatPhpOption) {
return new Promise((resolve) => resolve(content))
.then((res: any) => _.replace(res, /{!!/g, '<?php /*escaped*/'))
.then((res) => _.replace(res, /!!}/g, '/*escaped*/ ?>\n'))
.then((res) => formatStringAsPhp(res))
.then((res) => formatStringAsPhp(res, options))
.then((res) => _.replace(res, /<\?php\s\/\*escaped\*\//g, '{!! '))
.then((res) => _.replace(res, /\/\*escaped\*\/\s\?>\n/g, ' !!}'));
}
Expand All @@ -209,8 +209,8 @@ export async function removeSemicolon(content: any) {
.then((res) => _.replace(res, /; --}}/g, ' --}}'));
}

export async function formatAsPhp(content: any) {
return prettifyPhpContentWithUnescapedTags(content);
export async function formatAsPhp(content: string, options: FormatPhpOption) {
return prettifyPhpContentWithUnescapedTags(content, options);
}

export async function preserveOriginalPhpTagInHtml(content: any) {
Expand Down

0 comments on commit c0505c2

Please sign in to comment.