Automattic\WooCommerce\Internal\Admin\Reports

HposLegacyOrderReportQueryBuilder::translate_legacy_sql_fragment │ private │ WC 1.0

Translate legacy posts.<col> and bare <col> references in an arbitrary SQL fragment.

Both passes cover every column in {@see self::legacy_to_hpos_column_map()}: legacy callers often leave these unqualified (e.g. WooCommerce Subscriptions before 7.8.0 passed a bare post_status and an untranslated bare token names a column wc_orders lacks.

Tokens inside longer identifiers (product_ID, posts.post_date_gmt), qualified by another table alias (p.post_type, joined via a query filter), or quoted are left untouched.

Method of the class: HposLegacyOrderReportQueryBuilder{}

No Hooks.

Returns

string. Translated fragment safe to drop into an HPOS query.

Usage

// private - for code of main (parent) class only
$result = $this->translate_legacy_sql_fragment( $fragment ): string;
$fragment(string) (required)
Caller-supplied SQL fragment.

HposLegacyOrderReportQueryBuilder::translate_legacy_sql_fragment() code WC 11.3.0

private function translate_legacy_sql_fragment( string $fragment ): string {
	$map         = $this->legacy_to_hpos_column_map();
	$alternation = implode( '|', array_keys( $map ) );

	// Qualified `posts.<col>` references first, then the bare tokens legacy
	// callers use unqualified. The callback avoids `$`/`\` replacement-string pitfalls.
	$replace = static function ( $matches ) use ( $map ) {
		return $map[ $matches[1] ];
	};

	// `\b` alone matches after `.` or a quote, which would rewrite `p.post_type`,
	// a quoted alias like `post_status` or a string literal.
	$fragment = (string) preg_replace_callback( '/(?<![\w.`\'"])posts\.(' . $alternation . ')\b/', $replace, $fragment );

	return (string) preg_replace_callback( '/(?<![\w.`\'"])(' . $alternation . ')\b/', $replace, $fragment );
}