Filter uncanny-automator

automator_compression_level

Filters the compression level used for asset optimization.

add_filter( 'automator_compression_level', $callback, 10, 1 );

Description

Allows developers to adjust the compression level for data processed by the Automator plugin. The default level is 4. This filter is applied before data compression occurs, enabling customization of the trade-off between compression speed and file size based on specific hosting or performance needs.


Usage

add_filter( 'automator_compression_level', 'your_function_name', 10, 1 );

Return Value

The filtered value.


Examples

<?php

/**
 * Custom function to modify the compression level for Automator.
 *
 * This example demonstrates how to increase the default compression level
 * to 9 (maximum compression) for specific scenarios, potentially to achieve
 * smaller payload sizes at the cost of CPU time.
 *
 * @param int $level The current compression level. Defaults to 4.
 * @return int The modified compression level.
 */
function my_custom_automator_compression_level( $level ) {
    // Let's increase the compression level to maximum (9) if the original level is low.
    // This might be useful for data that needs to be transferred quickly and has
    // significant compressible content.
    if ( $level < 5 ) {
        return 9; // Use maximum compression
    }

    // Otherwise, return the original level.
    return $level;
}
add_filter( 'automator_compression_level', 'my_custom_automator_compression_level', 10, 1 );

?>

Placement

This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.


Source Code

src/core/lib/utilities/class-automator-compression.php:40

public static function maybe_compress_string( $payload ) {

		if ( ! is_string( $payload ) ) {
			return $payload;
		}

		// Allow hosts to tune thresholds without code changes.
		$min_bytes = absint( apply_filters( 'automator_compression_min_bytes', 2048 ) );
		$level     = absint( apply_filters( 'automator_compression_level', 4 ) );

		if ( $min_bytes <= 0 ) {
			$min_bytes = 2048;
		}

		// Do nothing if zlib is unavailable or payload is too small.
		if ( ! function_exists( 'gzcompress' ) || strlen( $payload ) < $min_bytes ) {
			return $payload;
		}

		// Compress with a moderate level to reduce CPU on shared hosting.
		$compressed = @gzcompress( $payload, $level ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged

		if ( false === $compressed ) {
			return $payload;
		}

		$wrapped = self::PREFIX . base64_encode( $compressed );

		// Avoid expanding small payloads due to base64 overhead.
		if ( strlen( $wrapped ) >= strlen( $payload ) ) {
			return $payload;
		}

		return $wrapped;
	}


Scroll to Top