Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

De-duplicate logic between REST API and URL Metrics post type #1867

Open
wants to merge 6 commits into
base: trunk
Choose a base branch
from

Conversation

ShyamGadde
Copy link
Contributor

Summary

Fixes #1858

Relevant technical choices

  • Introduced OD_URL_Metrics_Post_Type::update_post( string $slug, string $post_title, OD_URL_Metric_Group_Collection $url_metric_group_collection ) to replace store_url_metric(), eliminating redundant logic.
  • Updated REST API to use update_post() instead of store_url_metric(), ensuring the existing OD_URL_Metric_Group_Collection is passed directly.
  • Moved store_url_metric() to Optimization_Detective_Test_Helpers for test compatibility.
  • Refactored affected tests to align with the new method structure.

@ShyamGadde ShyamGadde added [Type] Enhancement A suggestion for improvement of an existing feature [Plugin] Optimization Detective Issues for the Optimization Detective plugin labels Feb 12, 2025
Copy link

codecov bot commented Feb 12, 2025

Codecov Report

Attention: Patch coverage is 93.75000% with 1 line in your changes missing coverage. Please review.

Project coverage is 66.63%. Comparing base (d21b74d) to head (010f621).

Files with missing lines Patch % Lines
...lugins/optimization-detective/storage/rest-api.php 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            trunk    #1867      +/-   ##
==========================================
- Coverage   66.64%   66.63%   -0.01%     
==========================================
  Files          88       88              
  Lines        7015     7011       -4     
==========================================
- Hits         4675     4672       -3     
+ Misses       2340     2339       -1     
Flag Coverage Δ
multisite 66.63% <93.75%> (-0.01%) ⬇️
single 37.29% <0.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Signed-off-by: Shyamsundar Gadde <[email protected]>
@ShyamGadde ShyamGadde marked this pull request as ready for review February 12, 2025 08:18
Copy link

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: ShyamGadde <[email protected]>
Co-authored-by: westonruter <[email protected]>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

public static function store_url_metric( string $slug, OD_URL_Metric $new_url_metric ) {
$post_data = array(
public static function update_post( string $slug, OD_URL_Metric_Group_Collection $url_metric_group_collection ) {
$url_metrics = $url_metric_group_collection->get_flattened_url_metrics();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if there are no URL Metrics in the collection? Shouldn't this method short-circuit with a WP_Error?

Alternatively, should we allow updating a post with zero URL Metrics (i.e. to empty it out)? We don't have a use case for that in the plugin and this method is not intended to be public, so probably not.

Ensuring there is at least one URL Metric will prevent a possible error below when accessing $url_metrics[0].

Comment on lines +177 to +235
$post_data = array(
'post_title' => $new_url_metric->get_url(),
);

$post = OD_URL_Metrics_Post_Type::get_post( $slug );
if ( $post instanceof WP_Post ) {
$post_data['ID'] = $post->ID;
$post_data['post_name'] = $post->post_name;
$url_metrics = OD_URL_Metrics_Post_Type::get_url_metrics_from_post( $post );
} else {
$post_data['post_name'] = $slug;
$url_metrics = array();
}

$etag = $new_url_metric->get_etag();

$group_collection = new OD_URL_Metric_Group_Collection(
$url_metrics,
$etag,
od_get_breakpoint_max_widths(),
od_get_url_metrics_breakpoint_sample_size(),
od_get_url_metric_freshness_ttl()
);

try {
$group = $group_collection->get_group_for_viewport_width( $new_url_metric->get_viewport_width() );
$group->add_url_metric( $new_url_metric );
} catch ( InvalidArgumentException $e ) {
return new WP_Error( 'invalid_url_metric', $e->getMessage() );
}

$post_data['post_content'] = wp_json_encode(
$group_collection->get_flattened_url_metrics(),
JSON_UNESCAPED_SLASHES // No need for escaping slashes since this JSON is not embedded in HTML.
);
if ( ! is_string( $post_data['post_content'] ) ) {
return new WP_Error( 'json_encode_error', json_last_error_msg() );
}

$has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );
if ( $has_kses ) {
// Prevent KSES from corrupting JSON in post_content.
kses_remove_filters();
}

$post_data['post_type'] = OD_URL_Metrics_Post_Type::SLUG;
$post_data['post_status'] = 'publish';
$slashed_post_data = wp_slash( $post_data );
if ( isset( $post_data['ID'] ) ) {
$result = wp_update_post( $slashed_post_data, true );
} else {
$result = wp_insert_post( $slashed_post_data, true );
}

if ( $has_kses ) {
kses_init_filters();
}

return $result;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't this be simplified now to just construct the OD_URL_Metric_Group_Collection, add the URL Metric to it, and then pass it to OD_URL_Metrics_Post_Type::update_post()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Plugin] Optimization Detective Issues for the Optimization Detective plugin [Type] Enhancement A suggestion for improvement of an existing feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Logic should be de-duplicated between REST API and URL Metrics post type class
2 participants