Automattic\WooCommerce\Internal\Admin\Logging

PageController::format_line()privateWC 1.0

Format a log file line.

Method of the class: PageController{}

No Hooks.

Return

String.

Usage

// private - for code of main (parent) class only
$result = $this->format_line( $line, $line_number ): string;
$line(string) (required)
The unformatted log file line.
$line_number(int) (required)
The line number.

PageController::format_line() code WC 9.3.3

private function format_line( string $line, int $line_number ): string {
	$classes = array( 'line' );

	$line = esc_html( $line );
	if ( empty( $line ) ) {
		$line = ' ';
	}

	$segments      = explode( ' ', $line, 3 );
	$has_timestamp = false;
	$has_level     = false;

	if ( isset( $segments[0] ) && false !== strtotime( $segments[0] ) ) {
		$classes[]     = 'log-entry';
		$segments[0]   = sprintf(
			'<span class="log-timestamp">%s</span>',
			$segments[0]
		);
		$has_timestamp = true;
	}

	if ( isset( $segments[1] ) && WC_Log_Levels::is_valid_level( strtolower( $segments[1] ) ) ) {
		$segments[1] = sprintf(
			'<span class="%1$s">%2$s</span>',
			esc_attr( 'log-level log-level--' . strtolower( $segments[1] ) ),
			esc_html( WC_Log_Levels::get_level_label( strtolower( $segments[1] ) ) )
		);
		$has_level   = true;
	}

	if ( isset( $segments[2] ) && $has_timestamp && $has_level ) {
		$message_chunks = explode( 'CONTEXT:', $segments[2], 2 );
		if ( isset( $message_chunks[1] ) ) {
			try {
				$maybe_json = html_entity_decode( addslashes( trim( $message_chunks[1] ) ) );

				// Decode for validation.
				$context = json_decode( $maybe_json, false, 512, JSON_THROW_ON_ERROR );

				// Re-encode to make it pretty.
				$context = wp_json_encode( $context, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );

				$message_chunks[1] = sprintf(
					'<details><summary>%1$s</summary>%2$s</details>',
					esc_html__( 'Additional context', 'woocommerce' ),
					stripslashes( $context )
				);

				$segments[2] = implode( ' ', $message_chunks );
				$classes[]   = 'has-context';
			} catch ( \JsonException $exception ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
				// It's not valid JSON so don't do anything with it.
			}
		}
	}

	if ( count( $segments ) > 1 ) {
		$line = implode( ' ', $segments );
	}

	$classes = implode( ' ', $classes );

	return sprintf(
		'<span id="L%1$d" class="%2$s">%3$s%4$s</span>',
		absint( $line_number ),
		esc_attr( $classes ),
		sprintf(
			'<a href="#L%1$d" class="line-anchor"></a>',
			absint( $line_number )
		),
		sprintf(
			'<span class="line-content">%s</span>',
			wp_kses_post( $line )
		)
	);
}