Yoast\WP\SEO\Dashboard\Infrastructure\Analytics_4

Site_Kit_Analytics_4_Adapter::parse_comparison_response()privateYoast 1.0

Parses a response for a Site Kit API request for Analytics 4 that compares data ranges.

Метод класса: Site_Kit_Analytics_4_Adapter{}

Хуков нет.

Возвращает

Data_Container. The parsed response.

Использование

// private - только в коде основоного (родительского) класса
$result = $this->parse_comparison_response( $response ): Data_Container;
$response(RunReportResponse) (обязательный)
The response to parse.

Код Site_Kit_Analytics_4_Adapter::parse_comparison_response() Yoast 25.1

private function parse_comparison_response( RunReportResponse $response ): Data_Container {
	if ( ! $this->is_comparison_request( $response ) ) {
		throw new Invalid_Request_Exception( 'Unexpected parameters for the request' );
	}

	$data_container          = new Data_Container();
	$comparison_traffic_data = new Comparison_Traffic_Data();

	// First row is the current date range's data, second row is the previous date range's data.
	foreach ( $response->getRows() as $date_range_row ) {
		$traffic_data = new Traffic_Data();

		// Loop through all the metrics of the date range.
		foreach ( $response->getMetricHeaders() as $key => $metric ) {

			// As per https://developers.google.com/analytics/devguides/reporting/data/v1/basics#read_the_response,
			// the order of the columns is consistent in the request, header, and rows.
			// So we can use the key of the header to get the correct metric value from the row.
			$metric_value = $date_range_row->getMetricValues()[ $key ]->getValue();

			if ( $metric->getName() === 'sessions' ) {
				$traffic_data->set_sessions( (int) $metric_value );
			}
			elseif ( $metric->getName() === 'totalUsers' ) {
				$traffic_data->set_total_users( (int) $metric_value );
			}
		}

		$period = $this->get_period( $date_range_row );

		if ( $period === Comparison_Traffic_Data::CURRENT_PERIOD_KEY ) {
			$comparison_traffic_data->set_current_traffic_data( $traffic_data );
		}
		elseif ( $period === Comparison_Traffic_Data::PREVIOUS_PERIOD_KEY ) {
			$comparison_traffic_data->set_previous_traffic_data( $traffic_data );
		}
	}

	$data_container->add_data( $comparison_traffic_data );

	return $data_container;
}