UNPKG

@cedx/php-minifier

Version:

Minify PHP source code by removing comments and whitespace.

51 lines (50 loc) 1.97 kB
import log from "fancy-log"; import { Buffer } from "node:buffer"; import { Transform } from "node:stream"; import PluginError from "plugin-error"; import { FastTransformer } from "./FastTransformer.js"; import { SafeTransformer } from "./SafeTransformer.js"; /** * Minifies PHP source code by removing comments and whitespace. */ export class GulpPlugin extends Transform { /** * Value indicating whether to silence the plugin output. */ #silent; /** * The instance used to process the PHP code. */ #transformer; /** * Creates a new plugin. * @param options An object providing values to initialize this instance. */ constructor(options = {}) { super({ objectMode: true }); const binary = options.binary ?? "php"; this.#silent = options.silent ?? false; this.#transformer = (options.mode ?? "safe") == "fast" ? new FastTransformer(binary) : new SafeTransformer(binary); const close = async () => { await this.#transformer.close(); }; this.on("end", close).on("error", close); // eslint-disable-line @typescript-eslint/no-misused-promises } /** * Transforms input and produces output. * @param file The chunk to transform. * @param encoding The encoding type if the chunk is a string. * @param done The function to invoke when the supplied chunk has been processed. * @returns Resolves when the specified chunk has been transformed. */ async _transform(file, encoding, done) { try { if (!this.#silent) log(`Minifying: ${file.relative}`); file.contents = Buffer.from(await this.#transformer.transform(file.path), encoding); done(null, file); } catch (error) { const failure = error instanceof Error ? error : String(error); done(new PluginError("@cedx/php-minifier", failure, { fileName: file.path })); } } }