# xspeed/1.2.0/includes/class-optimizer.php

xSpeed Cache: AI-Powered Performance Hub with MCP, Caching &amp; CDN, version 1.2.0. 143 lines.

- Page: https://pluginprobe.com/plugins/xspeed/1.2.0/code/includes/class-optimizer.php
- Raw: https://pluginprobe.com/plugins/xspeed/1.2.0/raw/includes/class-optimizer.php
- Modified: 2026-08-24T06:22:30+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/xspeed/1.2.0/code/includes/class-optimizer.php#L10-L20`.

```php
<?php
/**
 * Optimizer — the autopilot loop.
 *
 * @package XSpeed
 */

namespace XSpeed;

defined( 'ABSPATH' ) || exit;

/**
 * Apply an optimization plan one step at a time, verifying after each.
 *
 * The loop is deliberately boring, because the interesting part is what it
 * refuses to do:
 *
 *  - **One change at a time.** A batch that fails tells you nothing about
 *    which setting did it, and leaves you reverting work that was fine.
 *  - **Purge before verifying.** No settings change purges the page cache on
 *    its own (#205), so a check run against an unpurged site verifies the page
 *    as it was BEFORE the change and passes anything.
 *  - **Revert only the failing step.** A break at step 9 must not discard the
 *    eight verified wins before it, and must not abort the four steps after.
 *  - **Never leave a step applied-but-unverified.** If sampling itself fails,
 *    that is not permission to assume success.
 *
 * Every side effect is injected rather than called directly, so the whole loop
 * is unit-testable without a WordPress install or a live site: the tests drive
 * it with an applier that records, and a sampler that breaks on cue.
 *
 * @since 1.2.0
 */
final class Optimizer {

	/**
	 * Run a plan.
	 *
	 * @param array<int,array<string,mixed>> $steps    Ordered steps from Optimize_Plan::build().
	 * @param array<string,mixed>            $baseline Sample taken before anything changed.
	 * @param array{
	 *     apply:callable,
	 *     revert:callable,
	 *     purge:callable,
	 *     sample:callable,
	 *     now?:callable
	 * }                                     $io       Injected side effects.
	 * @param int                            $budget_seconds Wall-clock cap; 0 = uncapped.
	 * @return array{applied:array<int,array<string,mixed>>,reverted:array<int,array<string,mixed>>,skipped:array<int,array<string,string>>}
	 */
	public static function run( array $steps, array $baseline, array $io, int $budget_seconds = 0 ): array {
		$apply  = $io['apply'];
		$revert = $io['revert'];
		$purge  = $io['purge'];
		$sample = $io['sample'];
		$now    = $io['now'] ?? static function () {
			return time();
		};

		$started  = (int) $now();
		$applied  = array();
		$reverted = array();
		$skipped  = array();

		foreach ( $steps as $i => $step ) {
			// Budget check BEFORE applying, never mid-step: stopping between
			// "wrote the setting" and "verified it" is the one state this
			// loop must never end in.
			if ( $budget_seconds > 0 && ( (int) $now() - $started ) >= $budget_seconds ) {
				foreach ( array_slice( $steps, $i ) as $rest ) {
					$skipped[] = array(
						'id'  => (string) $rest['id'],
						'why' => __( 'Ran out of time before this step.', 'xspeed' ),
					);
				}
				break;
			}

			$before = self::snapshot_of( $step );

			$apply( $step );
			$purge();

			$current = $sample();

			// A sample we could not take is NOT a pass. Treating an
			// unreachable site as "probably fine" is how an autopilot leaves
			// a site broken and reports success.
			if ( ! is_array( $current ) ) {
				$revert( $step, $before );
				$purge();
				$reverted[] = array(
					'id'  => (string) $step['id'],
					'why' => __( 'Could not load the page to check it, so the change was undone.', 'xspeed' ),
				);
				continue;
			}

			$check = Optimize_Verifier::compare( $baseline, $current );
			if ( ! $check['ok'] ) {
				$revert( $step, $before );
				$purge();
				$reverted[] = array(
					'id'  => (string) $step['id'],
					'why' => implode( ' ', $check['failures'] ),
				);
				continue;
			}

			$applied[] = array(
				'id'       => (string) $step['id'],
				'change'   => (string) $step['label'],
				'verified' => true,
			);
		}

		return array(
			'applied'  => $applied,
			'reverted' => $reverted,
			'skipped'  => $skipped,
		);
	}

	/**
	 * The values to put back if this step has to be undone.
	 *
	 * Every step in the catalog turns something ON, so the inverse is the
	 * same keys set to false. Kept as its own method so a future step whose
	 * inverse is not simply `false` has one obvious place to say so, rather
	 * than the revert path quietly writing the wrong thing.
	 *
	 * @param array<string,mixed> $step Step definition.
	 * @return array<string,mixed>
	 */
	private static function snapshot_of( array $step ): array {
		$out = array();
		foreach ( (array) $step['values'] as $key => $value ) {
			$out[ $key ] = is_bool( $value ) ? ! $value : false;
		}
		return $out;
	}
}

```
