Compare commits
14 Commits
claude/ima
...
refactor/s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d31d378ec1 | ||
|
|
fcc61c0cb8 | ||
|
|
e7d498574f | ||
|
|
49d094b4f8 | ||
|
|
7197249cab | ||
|
|
364d246863 | ||
|
|
941fc96c53 | ||
|
|
e60cb83770 | ||
|
|
5e7fd882bc | ||
|
|
4f13afbb77 | ||
|
|
38157f0b41 | ||
|
|
76b258bcc3 | ||
|
|
f88d752a79 | ||
|
|
2e41c3f2f6 |
@@ -5,7 +5,7 @@ declare(strict_types=1);
|
|||||||
* Displays admin notices for onboarding, errors, and budget warnings.
|
* Displays admin notices for onboarding, errors, and budget warnings.
|
||||||
*
|
*
|
||||||
* Triggered by: PRAutoBlogger::register_admin_hooks() on `admin_notices`.
|
* Triggered by: PRAutoBlogger::register_admin_hooks() on `admin_notices`.
|
||||||
* Dependencies: PRAutoBlogger_Cost_Tracker (for budget warnings).
|
* Dependencies: PRAutoBlogger_Cost_Reporter (for budget warnings).
|
||||||
*
|
*
|
||||||
* @see class-prautoblogger.php — Registers the hook.
|
* @see class-prautoblogger.php — Registers the hook.
|
||||||
*/
|
*/
|
||||||
@@ -51,8 +51,8 @@ class PRAutoBlogger_Admin_Notices {
|
|||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
private function check_budget_notice(): void {
|
private function check_budget_notice(): void {
|
||||||
$cost_tracker = new PRAutoBlogger_Cost_Tracker();
|
$cost_reporter = new PRAutoBlogger_Cost_Reporter();
|
||||||
$utilization = $cost_tracker->get_budget_utilization();
|
$utilization = $cost_reporter->get_budget_utilization();
|
||||||
|
|
||||||
if ( $utilization >= 100.0 ) {
|
if ( $utilization >= 100.0 ) {
|
||||||
printf(
|
printf(
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ declare(strict_types=1);
|
|||||||
* and budget utilization.
|
* and budget utilization.
|
||||||
*
|
*
|
||||||
* Triggered by: Could be registered via wp_dashboard_setup hook.
|
* Triggered by: Could be registered via wp_dashboard_setup hook.
|
||||||
* Dependencies: PRAutoBlogger_Cost_Tracker.
|
* Dependencies: PRAutoBlogger_Cost_Reporter.
|
||||||
*
|
*
|
||||||
* @see class-prautoblogger.php — Can register this on wp_dashboard_setup.
|
* @see class-prautoblogger.php — Can register this on wp_dashboard_setup.
|
||||||
*/
|
*/
|
||||||
@@ -37,10 +37,10 @@ class PRAutoBlogger_Dashboard_Widget {
|
|||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function render_widget(): void {
|
public function render_widget(): void {
|
||||||
$cost_tracker = new PRAutoBlogger_Cost_Tracker();
|
$cost_reporter = new PRAutoBlogger_Cost_Reporter();
|
||||||
$monthly_spend = $cost_tracker->get_monthly_spend();
|
$monthly_spend = $cost_reporter->get_monthly_spend();
|
||||||
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
||||||
$utilization = $cost_tracker->get_budget_utilization();
|
$utilization = $cost_reporter->get_budget_utilization();
|
||||||
|
|
||||||
$next_run = wp_next_scheduled( 'prautoblogger_daily_generation' );
|
$next_run = wp_next_scheduled( 'prautoblogger_daily_generation' );
|
||||||
|
|
||||||
|
|||||||
141
includes/core/class-cost-reporter.php
Normal file
141
includes/core/class-cost-reporter.php
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provides historical cost reporting and analysis methods.
|
||||||
|
*
|
||||||
|
* Extracted from PRAutoBlogger_Cost_Tracker, this class handles all read-only
|
||||||
|
* reporting queries: monthly spend, daily spend trends, spend-by-stage breakdowns,
|
||||||
|
* and budget utilization percentage.
|
||||||
|
*
|
||||||
|
* Called by: Metrics dashboard, admin notices, and dashboard widget.
|
||||||
|
* Dependencies: WordPress $wpdb, get_option() for budget configuration.
|
||||||
|
*
|
||||||
|
* @see core/class-cost-tracker.php — Complementary class for logging and budget enforcement.
|
||||||
|
* @see admin/class-metrics-page.php — Displays cost reports.
|
||||||
|
* @see admin/class-admin-notices.php — Shows budget warnings via get_budget_utilization().
|
||||||
|
* @see admin/class-dashboard-widget.php — Displays current month costs.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_Cost_Reporter {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get total estimated spend for the current calendar month.
|
||||||
|
*
|
||||||
|
* @return float Total USD spend this month.
|
||||||
|
*/
|
||||||
|
public function get_monthly_spend(): float {
|
||||||
|
global $wpdb;
|
||||||
|
if ( null === $wpdb ) {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
||||||
|
|
||||||
|
$first_of_month = gmdate( 'Y-m-01 00:00:00' );
|
||||||
|
|
||||||
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||||
|
$result = $wpdb->get_var(
|
||||||
|
$wpdb->prepare(
|
||||||
|
"SELECT COALESCE(SUM(estimated_cost), 0) FROM {$table} WHERE created_at >= %s AND response_status = 'success'",
|
||||||
|
$first_of_month
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
return (float) $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get daily spend for the last N days (for the metrics dashboard chart).
|
||||||
|
*
|
||||||
|
* @param int $days Number of days to look back.
|
||||||
|
*
|
||||||
|
* @return array<string, float> Associative array of date => total_cost.
|
||||||
|
*/
|
||||||
|
public function get_daily_spend( int $days = 30 ): array {
|
||||||
|
global $wpdb;
|
||||||
|
if ( null === $wpdb ) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
||||||
|
|
||||||
|
$start_date = gmdate( 'Y-m-d', time() - ( $days * DAY_IN_SECONDS ) );
|
||||||
|
|
||||||
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||||
|
$results = $wpdb->get_results(
|
||||||
|
$wpdb->prepare(
|
||||||
|
"SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost
|
||||||
|
FROM {$table}
|
||||||
|
WHERE created_at >= %s AND response_status = 'success'
|
||||||
|
GROUP BY DATE(created_at)
|
||||||
|
ORDER BY day ASC",
|
||||||
|
$start_date . ' 00:00:00'
|
||||||
|
),
|
||||||
|
ARRAY_A
|
||||||
|
);
|
||||||
|
|
||||||
|
$daily = [];
|
||||||
|
foreach ( ( $results ?: [] ) as $row ) {
|
||||||
|
$daily[ $row['day'] ] = (float) $row['total_cost'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $daily;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get spend breakdown by pipeline stage for a given period.
|
||||||
|
*
|
||||||
|
* @param string $start_date Start date (Y-m-d).
|
||||||
|
* @param string $end_date End date (Y-m-d).
|
||||||
|
*
|
||||||
|
* @return array<string, array{cost: float, tokens: int, calls: int}> Breakdown by stage.
|
||||||
|
*/
|
||||||
|
public function get_spend_by_stage( string $start_date, string $end_date ): array {
|
||||||
|
global $wpdb;
|
||||||
|
if ( null === $wpdb ) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
||||||
|
|
||||||
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||||
|
$results = $wpdb->get_results(
|
||||||
|
$wpdb->prepare(
|
||||||
|
"SELECT stage,
|
||||||
|
SUM(estimated_cost) as total_cost,
|
||||||
|
SUM(prompt_tokens + completion_tokens) as total_tokens,
|
||||||
|
COUNT(*) as call_count
|
||||||
|
FROM {$table}
|
||||||
|
WHERE created_at BETWEEN %s AND %s AND response_status = 'success'
|
||||||
|
GROUP BY stage",
|
||||||
|
$start_date . ' 00:00:00',
|
||||||
|
$end_date . ' 23:59:59'
|
||||||
|
),
|
||||||
|
ARRAY_A
|
||||||
|
);
|
||||||
|
|
||||||
|
$breakdown = [];
|
||||||
|
foreach ( ( $results ?: [] ) as $row ) {
|
||||||
|
$breakdown[ $row['stage'] ] = [
|
||||||
|
'cost' => (float) $row['total_cost'],
|
||||||
|
'tokens' => (int) $row['total_tokens'],
|
||||||
|
'calls' => (int) $row['call_count'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $breakdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get budget utilization percentage for the current month.
|
||||||
|
*
|
||||||
|
* @return float Percentage (0-100+). Can exceed 100 if overspent.
|
||||||
|
*/
|
||||||
|
public function get_budget_utilization(): float {
|
||||||
|
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
||||||
|
if ( $budget <= 0 ) {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
return ( $this->get_monthly_spend() / $budget ) * 100.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,7 @@
|
|||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tracks all API costs, enforces monthly budget limits, and provides
|
* Tracks all API costs and enforces monthly budget limits.
|
||||||
* cost reporting data for the admin dashboard.
|
|
||||||
*
|
*
|
||||||
* Every LLM API call in the plugin is logged through this class. The budget
|
* Every LLM API call in the plugin is logged through this class. The budget
|
||||||
* enforcement is a hard stop — if the monthly budget is exceeded, no further
|
* enforcement is a hard stop — if the monthly budget is exceeded, no further
|
||||||
@@ -16,7 +15,8 @@ declare(strict_types=1);
|
|||||||
* @see core/class-content-analyzer.php — Calls log_api_call() after analysis.
|
* @see core/class-content-analyzer.php — Calls log_api_call() after analysis.
|
||||||
* @see core/class-content-generator.php — Calls log_api_call() after each stage.
|
* @see core/class-content-generator.php — Calls log_api_call() after each stage.
|
||||||
* @see core/class-chief-editor.php — Calls log_api_call() after review.
|
* @see core/class-chief-editor.php — Calls log_api_call() after review.
|
||||||
* @see admin/class-metrics-page.php — Displays cost data from this class.
|
* @see core/class-cost-reporter.php — Extracted reporting methods (read-only queries).
|
||||||
|
* @see admin/class-metrics-page.php — Displays cost data via Cost_Reporter.
|
||||||
* @see ARCHITECTURE.md — prab_generation_log table schema.
|
* @see ARCHITECTURE.md — prab_generation_log table schema.
|
||||||
*/
|
*/
|
||||||
class PRAutoBlogger_Cost_Tracker {
|
class PRAutoBlogger_Cost_Tracker {
|
||||||
@@ -127,7 +127,8 @@ class PRAutoBlogger_Cost_Tracker {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$monthly_spend = $this->get_monthly_spend();
|
$reporter = new PRAutoBlogger_Cost_Reporter();
|
||||||
|
$monthly_spend = $reporter->get_monthly_spend();
|
||||||
|
|
||||||
// Round to 4 decimal places (0.01 cent precision) to avoid
|
// Round to 4 decimal places (0.01 cent precision) to avoid
|
||||||
// floating-point representation artifacts triggering false positives.
|
// floating-point representation artifacts triggering false positives.
|
||||||
@@ -135,25 +136,63 @@ class PRAutoBlogger_Cost_Tracker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get total estimated spend for the current calendar month.
|
* Log an image generation API call with a known cost.
|
||||||
*
|
*
|
||||||
* @return float Total USD spend this month.
|
* Unlike log_api_call() which calculates cost from token counts, image
|
||||||
|
* generation uses per-megapixel pricing that the image provider already
|
||||||
|
* computed. This method accepts the pre-calculated cost directly.
|
||||||
|
*
|
||||||
|
* @param float $cost_usd Estimated cost in USD (from image provider pricing).
|
||||||
|
* @param string $model Image model alias (e.g. 'flux-1-schnell').
|
||||||
|
* @param int $post_id WordPress post ID the image is attached to.
|
||||||
|
* @param string $stage Pipeline stage ('image_a' or 'image_b').
|
||||||
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function get_monthly_spend(): float {
|
public function log_image_generation( float $cost_usd, string $model, int $post_id, string $stage ): void {
|
||||||
|
$this->current_run_cost += $cost_usd;
|
||||||
|
|
||||||
global $wpdb;
|
global $wpdb;
|
||||||
|
if ( null === $wpdb ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
||||||
|
|
||||||
$first_of_month = gmdate( 'Y-m-01 00:00:00' );
|
|
||||||
|
|
||||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||||
$result = $wpdb->get_var(
|
$wpdb->insert( $table, [
|
||||||
$wpdb->prepare(
|
'post_id' => $post_id,
|
||||||
"SELECT COALESCE(SUM(estimated_cost), 0) FROM {$table} WHERE created_at >= %s AND response_status = 'success'",
|
'run_id' => $this->run_id,
|
||||||
$first_of_month
|
'stage' => $stage,
|
||||||
)
|
'provider' => 'cloudflare-workers-ai',
|
||||||
);
|
'model' => $model,
|
||||||
|
'prompt_tokens' => 0,
|
||||||
|
'completion_tokens' => 0,
|
||||||
|
'estimated_cost' => $cost_usd,
|
||||||
|
'response_status' => 'success',
|
||||||
|
'error_message' => '',
|
||||||
|
'created_at' => current_time( 'mysql' ),
|
||||||
|
] );
|
||||||
|
}
|
||||||
|
|
||||||
return (float) $result;
|
/**
|
||||||
|
* Check if adding an estimated cost would exceed the monthly budget.
|
||||||
|
*
|
||||||
|
* Unlike is_budget_exceeded() which checks current state, this method
|
||||||
|
* proactively checks whether a planned expenditure would push spend
|
||||||
|
* over the budget. Used by the image pipeline to pre-check before
|
||||||
|
* making an API call.
|
||||||
|
*
|
||||||
|
* @param float $estimated_cost_usd Estimated cost in USD for the planned operation.
|
||||||
|
* @return bool True if (current spend + estimated cost) >= configured budget.
|
||||||
|
*/
|
||||||
|
public function would_exceed_budget( float $estimated_cost_usd ): bool {
|
||||||
|
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
||||||
|
if ( $budget <= 0 ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reporter = new PRAutoBlogger_Cost_Reporter();
|
||||||
|
$projected = $reporter->get_monthly_spend() + $estimated_cost_usd;
|
||||||
|
return round( $projected, 4 ) >= round( $budget, 4 );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -164,91 +203,4 @@ class PRAutoBlogger_Cost_Tracker {
|
|||||||
public function get_current_run_cost(): float {
|
public function get_current_run_cost(): float {
|
||||||
return $this->current_run_cost;
|
return $this->current_run_cost;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get daily spend for the last N days (for the metrics dashboard chart).
|
|
||||||
*
|
|
||||||
* @param int $days Number of days to look back.
|
|
||||||
*
|
|
||||||
* @return array<string, float> Associative array of date => total_cost.
|
|
||||||
*/
|
|
||||||
public function get_daily_spend( int $days = 30 ): array {
|
|
||||||
global $wpdb;
|
|
||||||
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
|
||||||
|
|
||||||
$start_date = gmdate( 'Y-m-d', time() - ( $days * DAY_IN_SECONDS ) );
|
|
||||||
|
|
||||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
|
||||||
$results = $wpdb->get_results(
|
|
||||||
$wpdb->prepare(
|
|
||||||
"SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost
|
|
||||||
FROM {$table}
|
|
||||||
WHERE created_at >= %s AND response_status = 'success'
|
|
||||||
GROUP BY DATE(created_at)
|
|
||||||
ORDER BY day ASC",
|
|
||||||
$start_date . ' 00:00:00'
|
|
||||||
),
|
|
||||||
ARRAY_A
|
|
||||||
);
|
|
||||||
|
|
||||||
$daily = [];
|
|
||||||
foreach ( ( $results ?: [] ) as $row ) {
|
|
||||||
$daily[ $row['day'] ] = (float) $row['total_cost'];
|
|
||||||
}
|
|
||||||
|
|
||||||
return $daily;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get spend breakdown by pipeline stage for a given period.
|
|
||||||
*
|
|
||||||
* @param string $start_date Start date (Y-m-d).
|
|
||||||
* @param string $end_date End date (Y-m-d).
|
|
||||||
*
|
|
||||||
* @return array<string, array{cost: float, tokens: int, calls: int}> Breakdown by stage.
|
|
||||||
*/
|
|
||||||
public function get_spend_by_stage( string $start_date, string $end_date ): array {
|
|
||||||
global $wpdb;
|
|
||||||
$table = $wpdb->prefix . 'prautoblogger_generation_log';
|
|
||||||
|
|
||||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
|
||||||
$results = $wpdb->get_results(
|
|
||||||
$wpdb->prepare(
|
|
||||||
"SELECT stage,
|
|
||||||
SUM(estimated_cost) as total_cost,
|
|
||||||
SUM(prompt_tokens + completion_tokens) as total_tokens,
|
|
||||||
COUNT(*) as call_count
|
|
||||||
FROM {$table}
|
|
||||||
WHERE created_at BETWEEN %s AND %s AND response_status = 'success'
|
|
||||||
GROUP BY stage",
|
|
||||||
$start_date . ' 00:00:00',
|
|
||||||
$end_date . ' 23:59:59'
|
|
||||||
),
|
|
||||||
ARRAY_A
|
|
||||||
);
|
|
||||||
|
|
||||||
$breakdown = [];
|
|
||||||
foreach ( ( $results ?: [] ) as $row ) {
|
|
||||||
$breakdown[ $row['stage'] ] = [
|
|
||||||
'cost' => (float) $row['total_cost'],
|
|
||||||
'tokens' => (int) $row['total_tokens'],
|
|
||||||
'calls' => (int) $row['call_count'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
return $breakdown;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get budget utilization percentage for the current month.
|
|
||||||
*
|
|
||||||
* @return float Percentage (0-100+). Can exceed 100 if overspent.
|
|
||||||
*/
|
|
||||||
public function get_budget_utilization(): float {
|
|
||||||
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
|
||||||
if ( $budget <= 0 ) {
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
return ( $this->get_monthly_spend() / $budget ) * 100.0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ class PRAutoBlogger_Image_Media_Sideloader {
|
|||||||
*
|
*
|
||||||
* @return int|\WP_Error Attachment ID on success, WP_Error on failure.
|
* @return int|\WP_Error Attachment ID on success, WP_Error on failure.
|
||||||
*/
|
*/
|
||||||
public function sideload_image( array $image_data, int $post_id, string $alt_text = '' ): int | \WP_Error {
|
public function sideload_image( array $image_data, int $post_id, string $alt_text = '' ) {
|
||||||
// Validate input.
|
// Validate input.
|
||||||
if ( empty( $image_data['bytes'] ) ) {
|
if ( empty( $image_data['bytes'] ) ) {
|
||||||
return new \WP_Error( 'invalid_image_data', 'Image data (bytes) is empty.' );
|
return new \WP_Error( 'invalid_image_data', 'Image data (bytes) is empty.' );
|
||||||
@@ -97,7 +97,7 @@ class PRAutoBlogger_Image_Media_Sideloader {
|
|||||||
*
|
*
|
||||||
* @return string|\WP_Error Path to temporary file on success, WP_Error on failure.
|
* @return string|\WP_Error Path to temporary file on success, WP_Error on failure.
|
||||||
*/
|
*/
|
||||||
private function create_temp_file( string $bytes, string $mime_type ): string | \WP_Error {
|
private function create_temp_file( string $bytes, string $mime_type ) {
|
||||||
$temp_dir = get_temp_dir();
|
$temp_dir = get_temp_dir();
|
||||||
$filename = 'prautoblogger_img_' . wp_generate_uuid4() . $this->get_extension_for_mime( $mime_type );
|
$filename = 'prautoblogger_img_' . wp_generate_uuid4() . $this->get_extension_for_mime( $mime_type );
|
||||||
$temp_path = $temp_dir . $filename;
|
$temp_path = $temp_dir . $filename;
|
||||||
|
|||||||
@@ -124,7 +124,9 @@ class PRAutoBlogger_Image_Pipeline {
|
|||||||
? $image_a_result->get_error_message()
|
? $image_a_result->get_error_message()
|
||||||
: 'Image A generation produced no attachment ID.';
|
: 'Image A generation produced no attachment ID.';
|
||||||
}
|
}
|
||||||
$result['cost_usd'] += $image_a_result['cost_usd'] ?? 0.0;
|
if ( ! is_wp_error( $image_a_result ) ) {
|
||||||
|
$result['cost_usd'] += $image_a_result['cost_usd'] ?? 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
// Generate Image B (source-driven prompt) if source data is available.
|
// Generate Image B (source-driven prompt) if source data is available.
|
||||||
if ( null !== $source_data && ! empty( $source_data ) ) {
|
if ( null !== $source_data && ! empty( $source_data ) ) {
|
||||||
@@ -136,7 +138,9 @@ class PRAutoBlogger_Image_Pipeline {
|
|||||||
? $image_b_result->get_error_message()
|
? $image_b_result->get_error_message()
|
||||||
: 'Image B generation produced no attachment ID.';
|
: 'Image B generation produced no attachment ID.';
|
||||||
}
|
}
|
||||||
$result['cost_usd'] += $image_b_result['cost_usd'] ?? 0.0;
|
if ( ! is_wp_error( $image_b_result ) ) {
|
||||||
|
$result['cost_usd'] += $image_b_result['cost_usd'] ?? 0.0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
@@ -153,7 +157,7 @@ class PRAutoBlogger_Image_Pipeline {
|
|||||||
* cost_usd: float,
|
* cost_usd: float,
|
||||||
* }|\WP_Error
|
* }|\WP_Error
|
||||||
*/
|
*/
|
||||||
private function generate_image_a( int $post_id, array $article_data ): array | \WP_Error {
|
private function generate_image_a( int $post_id, array $article_data ) {
|
||||||
try {
|
try {
|
||||||
// Build the article-driven prompt.
|
// Build the article-driven prompt.
|
||||||
$prompt = $this->prompt_builder->build_article_prompt( $article_data );
|
$prompt = $this->prompt_builder->build_article_prompt( $article_data );
|
||||||
@@ -219,7 +223,7 @@ class PRAutoBlogger_Image_Pipeline {
|
|||||||
* cost_usd: float,
|
* cost_usd: float,
|
||||||
* }|\WP_Error
|
* }|\WP_Error
|
||||||
*/
|
*/
|
||||||
private function generate_image_b( int $post_id, array $source_data ): array | \WP_Error {
|
private function generate_image_b( int $post_id, array $source_data ) {
|
||||||
try {
|
try {
|
||||||
// Build the source-driven prompt.
|
// Build the source-driven prompt.
|
||||||
$prompt = $this->prompt_builder->build_source_prompt( $source_data );
|
$prompt = $this->prompt_builder->build_source_prompt( $source_data );
|
||||||
|
|||||||
@@ -126,6 +126,11 @@ class PRAutoBlogger_Logger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
global $wpdb;
|
global $wpdb;
|
||||||
|
if ( null === $wpdb ) {
|
||||||
|
// No database available (unit test environment). PHP error_log
|
||||||
|
// was already called above for warnings/errors; silently skip DB write.
|
||||||
|
return;
|
||||||
|
}
|
||||||
$table = $wpdb->prefix . 'prautoblogger_event_log';
|
$table = $wpdb->prefix . 'prautoblogger_event_log';
|
||||||
|
|
||||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||||
|
|||||||
84
includes/providers/class-open-router-config.php
Normal file
84
includes/providers/class-open-router-config.php
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration helpers for OpenRouter provider.
|
||||||
|
*
|
||||||
|
* Resolves admin-configured settings for API endpoint selection
|
||||||
|
* (direct vs. Cloudflare AI Gateway routing) and caching behavior.
|
||||||
|
*
|
||||||
|
* Dependencies: get_option() for WordPress settings lookups.
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php — Parent class that uses this config.
|
||||||
|
* @see class-open-router-validator.php — Also uses API base URL resolution.
|
||||||
|
* @see ARCHITECTURE.md — External API Integrations section.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Config {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default direct-to-OpenRouter endpoint.
|
||||||
|
*
|
||||||
|
* Used when no Cloudflare AI Gateway URL is configured. The active endpoint
|
||||||
|
* is resolved per-request via get_api_base_url() so admins can flip to an
|
||||||
|
* AI Gateway proxy without code changes.
|
||||||
|
*/
|
||||||
|
private const DEFAULT_API_BASE_URL = 'https://openrouter.ai/api/v1';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the API base URL.
|
||||||
|
*
|
||||||
|
* If an admin has configured a Cloudflare AI Gateway URL in settings,
|
||||||
|
* we route through that instead of hitting OpenRouter directly. The
|
||||||
|
* gateway is a transparent OpenAI/OpenRouter-compatible proxy that
|
||||||
|
* adds caching, cost logging, rate-limiting, and provider fallback
|
||||||
|
* — see ARCHITECTURE.md "External API Integrations".
|
||||||
|
*
|
||||||
|
* Expected gateway URL shape:
|
||||||
|
* https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openrouter
|
||||||
|
*
|
||||||
|
* @return string Base URL with no trailing slash.
|
||||||
|
*/
|
||||||
|
public function get_api_base_url(): string {
|
||||||
|
$override = trim( (string) get_option( 'prautoblogger_ai_gateway_base_url', '' ) );
|
||||||
|
if ( '' === $override ) {
|
||||||
|
return self::DEFAULT_API_BASE_URL;
|
||||||
|
}
|
||||||
|
// Only accept https to avoid plaintext-auth regressions.
|
||||||
|
if ( 0 !== stripos( $override, 'https://' ) ) {
|
||||||
|
return self::DEFAULT_API_BASE_URL;
|
||||||
|
}
|
||||||
|
return rtrim( $override, '/' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache TTL (seconds) for AI Gateway response caching.
|
||||||
|
*
|
||||||
|
* Cloudflare honours the `cf-aig-cache-ttl` request header and serves
|
||||||
|
* cached responses for identical payloads within the TTL window. Only
|
||||||
|
* meaningful when a gateway base URL is configured; harmless otherwise.
|
||||||
|
*
|
||||||
|
* @return int Non-negative integer seconds; 0 disables caching.
|
||||||
|
*/
|
||||||
|
public function get_cache_ttl_seconds(): int {
|
||||||
|
$ttl = (int) get_option( 'prautoblogger_ai_gateway_cache_ttl', 0 );
|
||||||
|
return $ttl > 0 ? $ttl : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if routing through Cloudflare AI Gateway vs. direct-to-OpenRouter.
|
||||||
|
*
|
||||||
|
* @return bool True if a gateway URL is configured.
|
||||||
|
*/
|
||||||
|
public function is_via_gateway(): bool {
|
||||||
|
return self::DEFAULT_API_BASE_URL !== $this->get_api_base_url();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the default OpenRouter API base URL constant.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function get_default_api_base_url(): string {
|
||||||
|
return self::DEFAULT_API_BASE_URL;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,60 +11,17 @@ declare(strict_types=1);
|
|||||||
* Triggered by: Content_Analyzer, Content_Generator, Chief_Editor, Metrics_Collector.
|
* Triggered by: Content_Analyzer, Content_Generator, Chief_Editor, Metrics_Collector.
|
||||||
* Dependencies: PRAutoBlogger_Encryption (for API key decryption), wp_remote_post(), PRAutoBlogger_OpenRouter_Pricing.
|
* Dependencies: PRAutoBlogger_Encryption (for API key decryption), wp_remote_post(), PRAutoBlogger_OpenRouter_Pricing.
|
||||||
*
|
*
|
||||||
* @see interface-llm-provider.php — Interface this class implements.
|
* @see interface-llm-provider.php — Interface this class implements.
|
||||||
* @see class-open-router-pricing.php — Pricing and model list lookups.
|
* @see class-open-router-config.php — Config helpers (base URL, cache TTL).
|
||||||
* @see class-cost-tracker.php — Called after every request to log token usage.
|
* @see class-open-router-pricing.php — Pricing and model list lookups.
|
||||||
* @see ARCHITECTURE.md — Data flow diagram showing where this fits.
|
* @see class-open-router-validator.php — Credential validation (delegated).
|
||||||
|
* @see class-open-router-request-builder.php — Request header building + cURL filter.
|
||||||
|
* @see class-open-router-response-parser.php — Response parsing + error classification.
|
||||||
|
* @see class-cost-tracker.php — Called after every request to log token usage.
|
||||||
|
* @see ARCHITECTURE.md — Data flow diagram showing where this fits.
|
||||||
*/
|
*/
|
||||||
class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_Interface {
|
class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_Interface {
|
||||||
|
|
||||||
/**
|
|
||||||
* Default direct-to-OpenRouter endpoint. Used when no Cloudflare AI Gateway
|
|
||||||
* URL is configured. The active endpoint is resolved per-request via
|
|
||||||
* get_api_base_url() so admins can flip to an AI Gateway proxy without code.
|
|
||||||
*/
|
|
||||||
private const DEFAULT_API_BASE_URL = 'https://openrouter.ai/api/v1';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve the API base URL.
|
|
||||||
*
|
|
||||||
* If an admin has configured a Cloudflare AI Gateway URL in settings,
|
|
||||||
* we route through that instead of hitting OpenRouter directly. The
|
|
||||||
* gateway is a transparent OpenAI/OpenRouter-compatible proxy that
|
|
||||||
* adds caching, cost logging, rate-limiting, and provider fallback
|
|
||||||
* — see ARCHITECTURE.md "External API Integrations".
|
|
||||||
*
|
|
||||||
* Expected gateway URL shape:
|
|
||||||
* https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openrouter
|
|
||||||
*
|
|
||||||
* @return string Base URL with no trailing slash.
|
|
||||||
*/
|
|
||||||
private function get_api_base_url(): string {
|
|
||||||
$override = trim( (string) get_option( 'prautoblogger_ai_gateway_base_url', '' ) );
|
|
||||||
if ( '' === $override ) {
|
|
||||||
return self::DEFAULT_API_BASE_URL;
|
|
||||||
}
|
|
||||||
// Only accept https to avoid plaintext-auth regressions.
|
|
||||||
if ( 0 !== stripos( $override, 'https://' ) ) {
|
|
||||||
return self::DEFAULT_API_BASE_URL;
|
|
||||||
}
|
|
||||||
return rtrim( $override, '/' );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cache TTL (seconds) for AI Gateway response caching.
|
|
||||||
*
|
|
||||||
* Cloudflare honours the `cf-aig-cache-ttl` request header and serves
|
|
||||||
* cached responses for identical payloads within the TTL window. Only
|
|
||||||
* meaningful when a gateway base URL is configured; harmless otherwise.
|
|
||||||
*
|
|
||||||
* @return int Non-negative integer seconds; 0 disables caching.
|
|
||||||
*/
|
|
||||||
private function get_cache_ttl_seconds(): int {
|
|
||||||
$ttl = (int) get_option( 'prautoblogger_ai_gateway_cache_ttl', 0 );
|
|
||||||
return $ttl > 0 ? $ttl : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a chat completion request to OpenRouter.
|
* Send a chat completion request to OpenRouter.
|
||||||
*
|
*
|
||||||
@@ -133,49 +90,19 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
|
|
||||||
$last_error = '';
|
$last_error = '';
|
||||||
|
|
||||||
$base_url = $this->get_api_base_url();
|
$config = new PRAutoBlogger_OpenRouter_Config();
|
||||||
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
$base_url = $config->get_api_base_url();
|
||||||
$cache_ttl = $this->get_cache_ttl_seconds();
|
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
||||||
$via_gateway = self::DEFAULT_API_BASE_URL !== $base_url;
|
$cache_ttl = $config->get_cache_ttl_seconds();
|
||||||
|
$via_gateway = $config->is_via_gateway();
|
||||||
|
|
||||||
// Build headers once so the wp_remote_post call and the cURL belt-and-
|
$builder = new PRAutoBlogger_OpenRouter_Request_Builder();
|
||||||
// suspenders filter stay in lockstep. The cf-aig-* headers are only
|
$request_headers = $builder->build_headers( $api_key, $via_gateway, $cache_ttl );
|
||||||
// meaningful when going through a Cloudflare AI Gateway; they are
|
$curl_auth_filter = $builder->register_curl_auth_filter( $request_headers, $base_host );
|
||||||
// ignored by direct OpenRouter calls, so sending them unconditionally
|
|
||||||
// when a gateway is configured is safe and keeps the code branch-free.
|
|
||||||
$request_headers = [
|
|
||||||
'Authorization' => 'Bearer ' . $api_key,
|
|
||||||
'Content-Type' => 'application/json',
|
|
||||||
'HTTP-Referer' => home_url(),
|
|
||||||
'X-Title' => 'PRAutoBlogger WordPress Plugin',
|
|
||||||
];
|
|
||||||
if ( $via_gateway && $cache_ttl > 0 ) {
|
|
||||||
$request_headers['cf-aig-cache-ttl'] = (string) $cache_ttl;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Belt-and-suspenders: inject Authorization header at cURL level.
|
|
||||||
// Some hosting environments (Hostinger, certain proxies) strip the
|
|
||||||
// Authorization header from wp_remote_post's 'headers' array before
|
|
||||||
// the request is sent. The http_api_curl action fires after WordPress
|
|
||||||
// configures the cURL handle but before curl_exec — re-setting
|
|
||||||
// CURLOPT_HTTPHEADER here ensures the header reaches the upstream
|
|
||||||
// (either OpenRouter directly or the Cloudflare AI Gateway proxy).
|
|
||||||
$curl_auth_filter = function ( $handle, $parsed_args, $url ) use ( $request_headers, $base_host ): void {
|
|
||||||
// Scope to the configured upstream host only — never leak auth
|
|
||||||
// into unrelated outbound requests made elsewhere in WordPress.
|
|
||||||
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
$curl_headers = [];
|
|
||||||
foreach ( $request_headers as $name => $value ) {
|
|
||||||
$curl_headers[] = $name . ': ' . $value;
|
|
||||||
}
|
|
||||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
|
||||||
curl_setopt( $handle, CURLOPT_HTTPHEADER, $curl_headers );
|
|
||||||
};
|
|
||||||
add_action( 'http_api_curl', $curl_auth_filter, 99, 3 );
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
$parser = new PRAutoBlogger_OpenRouter_Response_Parser();
|
||||||
|
|
||||||
for ( $attempt = 1; $attempt <= PRAUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
|
for ( $attempt = 1; $attempt <= PRAUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
|
||||||
$response = wp_remote_post(
|
$response = wp_remote_post(
|
||||||
$base_url . '/chat/completions',
|
$base_url . '/chat/completions',
|
||||||
@@ -205,7 +132,7 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
$data = json_decode( $body_raw, true );
|
$data = json_decode( $body_raw, true );
|
||||||
|
|
||||||
// Rate limited (429) or server error (5xx) — retry with backoff.
|
// Rate limited (429) or server error (5xx) — retry with backoff.
|
||||||
if ( 429 === $status_code || $status_code >= 500 ) {
|
if ( $parser->is_retryable( $status_code ) ) {
|
||||||
$last_error = sprintf( 'HTTP %d: %s', $status_code, $body_raw );
|
$last_error = sprintf( 'HTTP %d: %s', $status_code, $body_raw );
|
||||||
PRAutoBlogger_Logger::instance()->warning(
|
PRAutoBlogger_Logger::instance()->warning(
|
||||||
sprintf( 'OpenRouter HTTP %d (attempt %d/%d): %s', $status_code, $attempt, PRAUTOBLOGGER_MAX_RETRIES, substr( $body_raw, 0, 500 ) ),
|
sprintf( 'OpenRouter HTTP %d (attempt %d/%d): %s', $status_code, $attempt, PRAUTOBLOGGER_MAX_RETRIES, substr( $body_raw, 0, 500 ) ),
|
||||||
@@ -225,9 +152,7 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
|
|
||||||
// Client error — don't retry, fail immediately.
|
// Client error — don't retry, fail immediately.
|
||||||
if ( $status_code >= 400 ) {
|
if ( $status_code >= 400 ) {
|
||||||
$error_msg = isset( $data['error']['message'] )
|
$error_msg = $parser->get_error_message( $data, $status_code );
|
||||||
? $data['error']['message']
|
|
||||||
: 'HTTP ' . $status_code;
|
|
||||||
|
|
||||||
// Log detailed diagnostic info for auth errors to aid debugging.
|
// Log detailed diagnostic info for auth errors to aid debugging.
|
||||||
if ( 401 === $status_code || 403 === $status_code ) {
|
if ( 401 === $status_code || 403 === $status_code ) {
|
||||||
@@ -254,22 +179,7 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Success — parse response.
|
// Success — parse response.
|
||||||
if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
|
return $parser->parse_success( $data, $model );
|
||||||
throw new \RuntimeException(
|
|
||||||
__( 'OpenRouter returned unexpected response format.', 'prautoblogger' )
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$usage = $data['usage'] ?? [];
|
|
||||||
|
|
||||||
return [
|
|
||||||
'content' => $data['choices'][0]['message']['content'],
|
|
||||||
'model' => $data['model'] ?? $model,
|
|
||||||
'prompt_tokens' => (int) ( $usage['prompt_tokens'] ?? 0 ),
|
|
||||||
'completion_tokens' => (int) ( $usage['completion_tokens'] ?? 0 ),
|
|
||||||
'total_tokens' => (int) ( $usage['total_tokens'] ?? 0 ),
|
|
||||||
'finish_reason' => $data['choices'][0]['finish_reason'] ?? 'unknown',
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// All retries exhausted.
|
// All retries exhausted.
|
||||||
@@ -327,9 +237,9 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
/**
|
/**
|
||||||
* Validate that the OpenRouter API key is configured and working.
|
* Validate that the OpenRouter API key is configured and working.
|
||||||
*
|
*
|
||||||
* Makes a lightweight request to the /auth/key endpoint.
|
* Delegates to PRAutoBlogger_OpenRouter_Validator for the actual checks.
|
||||||
*
|
*
|
||||||
* Side effects: HTTP request to OpenRouter, logs diagnostic info.
|
* Side effects: HTTP request to OpenRouter (via validator), logs diagnostic info.
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
@@ -341,112 +251,16 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
/**
|
/**
|
||||||
* Validate credentials with detailed diagnostic info.
|
* Validate credentials with detailed diagnostic info.
|
||||||
*
|
*
|
||||||
* Returns an array with status ('ok' or 'error') and a human-readable
|
* Delegates to PRAutoBlogger_OpenRouter_Validator which returns an array
|
||||||
* message explaining what went wrong if validation fails.
|
* with status ('ok' or 'error') and a human-readable message explaining
|
||||||
|
* what went wrong if validation fails.
|
||||||
*
|
*
|
||||||
* Side effects: HTTP request to OpenRouter, logs diagnostic info.
|
* Side effects: HTTP request to OpenRouter (via validator), logs diagnostic info.
|
||||||
*
|
*
|
||||||
* @return array{status: string, message: string, debug?: string}
|
* @return array{status: string, message: string, debug?: string}
|
||||||
*/
|
*/
|
||||||
public function validate_credentials_detailed(): array {
|
public function validate_credentials_detailed(): array {
|
||||||
$encrypted = get_option( 'prautoblogger_openrouter_api_key', '' );
|
return ( new PRAutoBlogger_OpenRouter_Validator() )->run();
|
||||||
if ( '' === $encrypted ) {
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => __( 'No API key saved. Enter your OpenRouter key in settings.', 'prautoblogger' ),
|
|
||||||
'debug' => 'option_empty',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$api_key = PRAutoBlogger_Encryption::decrypt( $encrypted );
|
|
||||||
if ( '' === $api_key ) {
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => __( 'API key decryption failed. Re-enter your key.', 'prautoblogger' ),
|
|
||||||
'debug' => 'decrypt_failed:encrypted_len=' . strlen( $encrypted ),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanity check: OpenRouter keys typically start with "sk-or-".
|
|
||||||
$key_prefix = substr( $api_key, 0, 6 );
|
|
||||||
$key_len = strlen( $api_key );
|
|
||||||
|
|
||||||
if ( 0 !== strpos( $api_key, 'sk-or-' ) ) {
|
|
||||||
PRAutoBlogger_Logger::instance()->error(
|
|
||||||
sprintf(
|
|
||||||
'API key format invalid (prefix="%s", len=%d). Likely salt changed — re-enter key.',
|
|
||||||
$key_prefix,
|
|
||||||
$key_len
|
|
||||||
),
|
|
||||||
'openrouter'
|
|
||||||
);
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => __( 'API key appears corrupted (decryption produced invalid data). Your WordPress auth salt may have changed. Please re-enter your OpenRouter API key in settings.', 'prautoblogger' ),
|
|
||||||
'debug' => sprintf( 'bad_format:prefix=%s,len=%d', $key_prefix, $key_len ),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Belt-and-suspenders: inject Authorization at cURL level (see send_chat_completion).
|
|
||||||
$base_url = $this->get_api_base_url();
|
|
||||||
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
|
||||||
$auth_header_value = 'Bearer ' . $api_key;
|
|
||||||
$curl_auth_filter_cred = function ( $handle, $parsed_args, $url ) use ( $auth_header_value, $base_host ): void {
|
|
||||||
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
|
||||||
curl_setopt( $handle, CURLOPT_HTTPHEADER, [
|
|
||||||
'Authorization: ' . $auth_header_value,
|
|
||||||
] );
|
|
||||||
};
|
|
||||||
add_action( 'http_api_curl', $curl_auth_filter_cred, 99, 3 );
|
|
||||||
|
|
||||||
$response = wp_remote_get(
|
|
||||||
$base_url . '/auth/key',
|
|
||||||
[
|
|
||||||
'timeout' => 15,
|
|
||||||
'headers' => [
|
|
||||||
'Authorization' => 'Bearer ' . $api_key,
|
|
||||||
],
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
remove_action( 'http_api_curl', $curl_auth_filter_cred, 99 );
|
|
||||||
|
|
||||||
if ( is_wp_error( $response ) ) {
|
|
||||||
$err_msg = $response->get_error_message();
|
|
||||||
PRAutoBlogger_Logger::instance()->error(
|
|
||||||
sprintf( 'OpenRouter credential check wp_error: %s (key_prefix=%s, key_len=%d)', $err_msg, $key_prefix, $key_len ),
|
|
||||||
'openrouter'
|
|
||||||
);
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => sprintf( __( 'Network error reaching OpenRouter: %s', 'prautoblogger' ), $err_msg ),
|
|
||||||
'debug' => 'wp_error:' . $err_msg,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$status_code = wp_remote_retrieve_response_code( $response );
|
|
||||||
$body_raw = wp_remote_retrieve_body( $response );
|
|
||||||
|
|
||||||
if ( 200 === $status_code ) {
|
|
||||||
return [
|
|
||||||
'status' => 'ok',
|
|
||||||
'message' => __( 'OpenRouter connected.', 'prautoblogger' ),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
PRAutoBlogger_Logger::instance()->warning(
|
|
||||||
sprintf( 'OpenRouter credential check HTTP %d (key_prefix=%s, key_len=%d): %s', $status_code, $key_prefix, $key_len, substr( $body_raw, 0, 300 ) ),
|
|
||||||
'openrouter'
|
|
||||||
);
|
|
||||||
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => sprintf( __( 'OpenRouter returned HTTP %d. %s', 'prautoblogger' ), $status_code, substr( $body_raw, 0, 200 ) ),
|
|
||||||
'debug' => sprintf( 'http_%d:key_prefix=%s,key_len=%d', $status_code, $key_prefix, $key_len ),
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
79
includes/providers/class-open-router-request-builder.php
Normal file
79
includes/providers/class-open-router-request-builder.php
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request builder for OpenRouter API calls.
|
||||||
|
*
|
||||||
|
* Encapsulates the logic for building HTTP request headers, including
|
||||||
|
* Cloudflare AI Gateway caching directives and belt-and-suspenders
|
||||||
|
* cURL header injection to work around authorization header stripping
|
||||||
|
* in certain hosting environments.
|
||||||
|
*
|
||||||
|
* Triggered by: PRAutoBlogger_OpenRouter_Provider::send_chat_completion()
|
||||||
|
* Dependencies: add_action(), curl_setopt() (via http_api_curl filter).
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php — Parent class that uses this builder.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Request_Builder {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build request headers for OpenRouter API call.
|
||||||
|
*
|
||||||
|
* Includes Authorization, Content-Type, HTTP-Referer, and optional
|
||||||
|
* Cloudflare AI Gateway cache control headers.
|
||||||
|
*
|
||||||
|
* @param string $api_key Decrypted OpenRouter API key.
|
||||||
|
* @param bool $via_gateway Whether the request is routed through Cloudflare AI Gateway.
|
||||||
|
* @param int $cache_ttl Cache TTL in seconds (0 disables caching).
|
||||||
|
*
|
||||||
|
* @return array<string, string> HTTP headers ready for wp_remote_post().
|
||||||
|
*/
|
||||||
|
public function build_headers( string $api_key, bool $via_gateway, int $cache_ttl ): array {
|
||||||
|
$headers = [
|
||||||
|
'Authorization' => 'Bearer ' . $api_key,
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
'HTTP-Referer' => home_url(),
|
||||||
|
'X-Title' => 'PRAutoBlogger WordPress Plugin',
|
||||||
|
];
|
||||||
|
|
||||||
|
if ( $via_gateway && $cache_ttl > 0 ) {
|
||||||
|
$headers['cf-aig-cache-ttl'] = (string) $cache_ttl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a cURL filter to inject Authorization header.
|
||||||
|
*
|
||||||
|
* Some hosting environments (Hostinger, certain proxies) strip the
|
||||||
|
* Authorization header from wp_remote_post's 'headers' array before
|
||||||
|
* the request is sent. The http_api_curl action fires after WordPress
|
||||||
|
* configures the cURL handle but before curl_exec — setting
|
||||||
|
* CURLOPT_HTTPHEADER here ensures the header reaches the upstream.
|
||||||
|
*
|
||||||
|
* Side effects: Adds an http_api_curl filter (caller must remove).
|
||||||
|
*
|
||||||
|
* @param array $request_headers Request headers (includes Authorization).
|
||||||
|
* @param string $base_host Upstream host (scopes the filter to avoid leaking auth).
|
||||||
|
*
|
||||||
|
* @return callable The filter function (for later removal via remove_action).
|
||||||
|
*/
|
||||||
|
public function register_curl_auth_filter( array $request_headers, string $base_host ): callable {
|
||||||
|
$curl_auth_filter = function ( $handle, $parsed_args, $url ) use ( $request_headers, $base_host ): void {
|
||||||
|
// Scope to the configured upstream host only — never leak auth
|
||||||
|
// into unrelated outbound requests made elsewhere in WordPress.
|
||||||
|
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$curl_headers = [];
|
||||||
|
foreach ( $request_headers as $name => $value ) {
|
||||||
|
$curl_headers[] = $name . ': ' . $value;
|
||||||
|
}
|
||||||
|
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||||
|
curl_setopt( $handle, CURLOPT_HTTPHEADER, $curl_headers );
|
||||||
|
};
|
||||||
|
add_action( 'http_api_curl', $curl_auth_filter, 99, 3 );
|
||||||
|
return $curl_auth_filter;
|
||||||
|
}
|
||||||
|
}
|
||||||
87
includes/providers/class-open-router-response-parser.php
Normal file
87
includes/providers/class-open-router-response-parser.php
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response parser for OpenRouter API responses.
|
||||||
|
*
|
||||||
|
* Encapsulates the logic for parsing and validating OpenRouter chat completion
|
||||||
|
* responses, including error classification and retry-decision logic.
|
||||||
|
*
|
||||||
|
* Triggered by: PRAutoBlogger_OpenRouter_Provider::send_chat_completion()
|
||||||
|
* Dependencies: PRAutoBlogger_Logger (for error/warning logging).
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php — Parent class that uses this parser.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Response_Parser {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if an HTTP status code indicates a retryable error.
|
||||||
|
*
|
||||||
|
* Returns true if the failure is transient (5xx, 429) and the retry loop
|
||||||
|
* should continue with backoff. Returns false for 4xx errors, which should
|
||||||
|
* fail immediately without retry.
|
||||||
|
*
|
||||||
|
* @param int $status_code HTTP status code.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_retryable( int $status_code ): bool {
|
||||||
|
return 429 === $status_code || $status_code >= 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a successful OpenRouter response.
|
||||||
|
*
|
||||||
|
* Validates the response contains the required fields and extracts
|
||||||
|
* the completion content and token usage.
|
||||||
|
*
|
||||||
|
* @param array $data Decoded JSON response from OpenRouter.
|
||||||
|
* @param string $model The model that was requested (fallback if not in response).
|
||||||
|
*
|
||||||
|
* @return array{
|
||||||
|
* content: string,
|
||||||
|
* model: string,
|
||||||
|
* prompt_tokens: int,
|
||||||
|
* completion_tokens: int,
|
||||||
|
* total_tokens: int,
|
||||||
|
* finish_reason: string,
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException If response structure is invalid.
|
||||||
|
*/
|
||||||
|
public function parse_success( array $data, string $model ): array {
|
||||||
|
if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
|
||||||
|
throw new \RuntimeException(
|
||||||
|
__( 'OpenRouter returned unexpected response format.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$usage = $data['usage'] ?? [];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'content' => $data['choices'][0]['message']['content'],
|
||||||
|
'model' => $data['model'] ?? $model,
|
||||||
|
'prompt_tokens' => (int) ( $usage['prompt_tokens'] ?? 0 ),
|
||||||
|
'completion_tokens' => (int) ( $usage['completion_tokens'] ?? 0 ),
|
||||||
|
'total_tokens' => (int) ( $usage['total_tokens'] ?? 0 ),
|
||||||
|
'finish_reason' => $data['choices'][0]['finish_reason'] ?? 'unknown',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract the error message from a failed response.
|
||||||
|
*
|
||||||
|
* Prefers the `error.message` field if present; falls back to the
|
||||||
|
* HTTP status code as a string.
|
||||||
|
*
|
||||||
|
* @param array $data Decoded JSON response (may be empty or malformed).
|
||||||
|
* @param int $status HTTP status code.
|
||||||
|
*
|
||||||
|
* @return string Human-readable error message.
|
||||||
|
*/
|
||||||
|
public function get_error_message( array $data, int $status ): string {
|
||||||
|
return isset( $data['error']['message'] )
|
||||||
|
? $data['error']['message']
|
||||||
|
: 'HTTP ' . $status;
|
||||||
|
}
|
||||||
|
}
|
||||||
152
includes/providers/class-open-router-validator.php
Normal file
152
includes/providers/class-open-router-validator.php
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Credential + connectivity validator for the OpenRouter LLM provider.
|
||||||
|
*
|
||||||
|
* Split out of the provider to keep each file under the 300-line cap and
|
||||||
|
* to keep the validation path easy to unit-test without spinning up the
|
||||||
|
* retry loop. The provider's `validate_credentials_detailed()` delegates
|
||||||
|
* straight to `run()` here.
|
||||||
|
*
|
||||||
|
* Triggered by: PRAutoBlogger_OpenRouter_Provider::validate_credentials_detailed()
|
||||||
|
* which is called by the admin "Test Connection" action.
|
||||||
|
* Dependencies: PRAutoBlogger_OpenRouter_Config (URL resolution),
|
||||||
|
* PRAutoBlogger_Encryption (API key decryption),
|
||||||
|
* PRAutoBlogger_Logger (WARN/ERROR lines), wp_remote_get().
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php Parent class that delegates here.
|
||||||
|
* @see class-open-router-config.php Config helpers for base URL.
|
||||||
|
* @see interface-llm-provider.php Return-shape contract.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Validator {
|
||||||
|
|
||||||
|
private const TIMEOUT_SECONDS = 15;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a non-destructive credential check.
|
||||||
|
*
|
||||||
|
* Lightweight probe: hits the /auth/key endpoint. Never makes a real
|
||||||
|
* LLM completion request — that would consume tokens on every click.
|
||||||
|
*
|
||||||
|
* Side effects: one HTTP GET; one Logger line on failure.
|
||||||
|
*
|
||||||
|
* @return array{status: string, message: string, debug?: string}
|
||||||
|
*/
|
||||||
|
public function run(): array {
|
||||||
|
$encrypted = get_option( 'prautoblogger_openrouter_api_key', '' );
|
||||||
|
if ( '' === $encrypted ) {
|
||||||
|
return $this->err(
|
||||||
|
'option_empty',
|
||||||
|
__( 'No API key saved. Enter your OpenRouter key in settings.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$api_key = PRAutoBlogger_Encryption::decrypt( $encrypted );
|
||||||
|
if ( '' === $api_key ) {
|
||||||
|
return $this->err(
|
||||||
|
'decrypt_failed:encrypted_len=' . strlen( $encrypted ),
|
||||||
|
__( 'API key decryption failed. Re-enter your key.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sanity check: OpenRouter keys typically start with "sk-or-".
|
||||||
|
$key_prefix = substr( $api_key, 0, 6 );
|
||||||
|
$key_len = strlen( $api_key );
|
||||||
|
|
||||||
|
if ( 0 !== strpos( $api_key, 'sk-or-' ) ) {
|
||||||
|
PRAutoBlogger_Logger::instance()->error(
|
||||||
|
sprintf(
|
||||||
|
'API key format invalid (prefix="%s", len=%d). Likely salt changed — re-enter key.',
|
||||||
|
$key_prefix,
|
||||||
|
$key_len
|
||||||
|
),
|
||||||
|
'openrouter'
|
||||||
|
);
|
||||||
|
return $this->err(
|
||||||
|
sprintf( 'bad_format:prefix=%s,len=%d', $key_prefix, $key_len ),
|
||||||
|
__( 'API key appears corrupted (decryption produced invalid data). Your WordPress auth salt may have changed. Please re-enter your OpenRouter API key in settings.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Belt-and-suspenders: inject Authorization at cURL level (see send_chat_completion).
|
||||||
|
$config = new PRAutoBlogger_OpenRouter_Config();
|
||||||
|
$base_url = $config->get_api_base_url();
|
||||||
|
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
||||||
|
$auth_header_value = 'Bearer ' . $api_key;
|
||||||
|
$curl_auth_filter_cred = function ( $handle, $parsed_args, $url ) use ( $auth_header_value, $base_host ): void {
|
||||||
|
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||||
|
curl_setopt( $handle, CURLOPT_HTTPHEADER, [
|
||||||
|
'Authorization: ' . $auth_header_value,
|
||||||
|
] );
|
||||||
|
};
|
||||||
|
add_action( 'http_api_curl', $curl_auth_filter_cred, 99, 3 );
|
||||||
|
|
||||||
|
$response = wp_remote_get(
|
||||||
|
$base_url . '/auth/key',
|
||||||
|
[
|
||||||
|
'timeout' => self::TIMEOUT_SECONDS,
|
||||||
|
'headers' => [
|
||||||
|
'Authorization' => 'Bearer ' . $api_key,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
remove_action( 'http_api_curl', $curl_auth_filter_cred, 99 );
|
||||||
|
|
||||||
|
if ( is_wp_error( $response ) ) {
|
||||||
|
$err_msg = $response->get_error_message();
|
||||||
|
PRAutoBlogger_Logger::instance()->error(
|
||||||
|
sprintf( 'OpenRouter credential check wp_error: %s (key_prefix=%s, key_len=%d)', $err_msg, $key_prefix, $key_len ),
|
||||||
|
'openrouter'
|
||||||
|
);
|
||||||
|
return $this->err(
|
||||||
|
'wp_error:' . $err_msg,
|
||||||
|
sprintf(
|
||||||
|
/* translators: %s: transport-layer error message. */
|
||||||
|
esc_html__( 'Network error reaching OpenRouter: %s', 'prautoblogger' ),
|
||||||
|
esc_html( $err_msg )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$status_code = wp_remote_retrieve_response_code( $response );
|
||||||
|
if ( 200 === $status_code ) {
|
||||||
|
return [
|
||||||
|
'status' => 'ok',
|
||||||
|
'message' => __( 'OpenRouter connected.', 'prautoblogger' ),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$body_raw = wp_remote_retrieve_body( $response );
|
||||||
|
PRAutoBlogger_Logger::instance()->warning(
|
||||||
|
sprintf( 'OpenRouter credential check HTTP %d (key_prefix=%s, key_len=%d): %s', $status_code, $key_prefix, $key_len, substr( $body_raw, 0, 300 ) ),
|
||||||
|
'openrouter'
|
||||||
|
);
|
||||||
|
|
||||||
|
return $this->err(
|
||||||
|
sprintf( 'http_%d:key_prefix=%s,key_len=%d', $status_code, $key_prefix, $key_len ),
|
||||||
|
sprintf(
|
||||||
|
/* translators: %1$d: HTTP status, %2$s: response body. */
|
||||||
|
esc_html__( 'OpenRouter returned HTTP %1$d. %2$s', 'prautoblogger' ),
|
||||||
|
$status_code,
|
||||||
|
esc_html( substr( $body_raw, 0, 200 ) )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{status: string, message: string, debug: string}
|
||||||
|
*/
|
||||||
|
private function err( string $debug, string $message ): array {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $message,
|
||||||
|
'debug' => $debug,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,15 +9,15 @@ if ( ! defined( 'ABSPATH' ) ) {
|
|||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
$cost_tracker = new PRAutoBlogger_Cost_Tracker();
|
$cost_reporter = new PRAutoBlogger_Cost_Reporter();
|
||||||
$monthly_spend = $cost_tracker->get_monthly_spend();
|
$monthly_spend = $cost_reporter->get_monthly_spend();
|
||||||
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
||||||
$utilization = $cost_tracker->get_budget_utilization();
|
$utilization = $cost_reporter->get_budget_utilization();
|
||||||
$daily_spend = $cost_tracker->get_daily_spend( 30 );
|
$daily_spend = $cost_reporter->get_daily_spend( 30 );
|
||||||
|
|
||||||
$first_of_month = gmdate( 'Y-m-01' );
|
$first_of_month = gmdate( 'Y-m-01' );
|
||||||
$today = gmdate( 'Y-m-d' );
|
$today = gmdate( 'Y-m-d' );
|
||||||
$stage_breakdown = $cost_tracker->get_spend_by_stage( $first_of_month, $today );
|
$stage_breakdown = $cost_reporter->get_spend_by_stage( $first_of_month, $today );
|
||||||
?>
|
?>
|
||||||
<div class="wrap prautoblogger-metrics">
|
<div class="wrap prautoblogger-metrics">
|
||||||
<h1><?php esc_html_e( 'PRAutoBlogger — Metrics & Costs', 'prautoblogger' ); ?></h1>
|
<h1><?php esc_html_e( 'PRAutoBlogger — Metrics & Costs', 'prautoblogger' ); ?></h1>
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ if ( ! defined( 'ABSPATH' ) ) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'prautoblogger_api';
|
$active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'prautoblogger_api';
|
||||||
$cost_tracker = new PRAutoBlogger_Cost_Tracker();
|
$cost_reporter = new PRAutoBlogger_Cost_Reporter();
|
||||||
$monthly_spend = $cost_tracker->get_monthly_spend();
|
$monthly_spend = $cost_reporter->get_monthly_spend();
|
||||||
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
$budget = (float) get_option( 'prautoblogger_monthly_budget_usd', 50.00 );
|
||||||
$utilization = $budget > 0 ? ( $monthly_spend / $budget ) * 100.0 : 0;
|
$utilization = $budget > 0 ? ( $monthly_spend / $budget ) * 100.0 : 0;
|
||||||
$next_run = wp_next_scheduled( 'prautoblogger_daily_generation' );
|
$next_run = wp_next_scheduled( 'prautoblogger_daily_generation' );
|
||||||
|
|||||||
@@ -55,6 +55,11 @@ if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL' ) ) {
|
|||||||
define( 'PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL', 'google/gemini-2.5-flash-lite' );
|
define( 'PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL', 'google/gemini-2.5-flash-lite' );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Default image style suffix used by ImagePromptBuilder and settings UI.
|
||||||
|
if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX' ) ) {
|
||||||
|
define( 'PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX', 'Style: test infomercial style.' );
|
||||||
|
}
|
||||||
|
|
||||||
// WordPress database constants used in $wpdb queries.
|
// WordPress database constants used in $wpdb queries.
|
||||||
if ( ! defined( 'ARRAY_A' ) ) {
|
if ( ! defined( 'ARRAY_A' ) ) {
|
||||||
define( 'ARRAY_A', 'ARRAY_A' );
|
define( 'ARRAY_A', 'ARRAY_A' );
|
||||||
@@ -92,3 +97,39 @@ if ( ! class_exists( 'WP_Query' ) ) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NOTE: Do NOT stub wp_strip_all_tags() or sanitize_text_field() here.
|
||||||
|
// Brain Monkey / Patchwork manages these stubs in individual tests via
|
||||||
|
// Functions\when(). Defining them in bootstrap causes Patchwork's
|
||||||
|
// "DefinedTooEarly" error.
|
||||||
|
|
||||||
|
// WP_Error stub — used by model registry and image pipeline tests.
|
||||||
|
// This is safe to define here because it's a class (not a function),
|
||||||
|
// so Patchwork doesn't need to intercept its definition.
|
||||||
|
if ( ! class_exists( 'WP_Error' ) ) {
|
||||||
|
class WP_Error {
|
||||||
|
public $errors = [];
|
||||||
|
public $error_data = [];
|
||||||
|
|
||||||
|
public function __construct( $code = '', $message = '', $data = '' ) {
|
||||||
|
if ( $code ) {
|
||||||
|
$this->errors[ $code ][] = $message;
|
||||||
|
if ( $data ) {
|
||||||
|
$this->error_data[ $code ] = $data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_error_code() {
|
||||||
|
$codes = array_keys( $this->errors );
|
||||||
|
return $codes ? $codes[0] : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_error_message( $code = '' ) {
|
||||||
|
if ( ! $code ) {
|
||||||
|
$code = $this->get_error_code();
|
||||||
|
}
|
||||||
|
return isset( $this->errors[ $code ] ) ? $this->errors[ $code ][0] : '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
93
tests/unit/Core/CostReporterTest.php
Normal file
93
tests/unit/Core/CostReporterTest.php
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Tests for PRAutoBlogger_Cost_Reporter.
|
||||||
|
*
|
||||||
|
* Validates monthly spend, daily spend trends, spend-by-stage breakdowns,
|
||||||
|
* and budget utilization reporting methods.
|
||||||
|
*
|
||||||
|
* @package PRAutoBlogger\Tests\Core
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace PRAutoBlogger\Tests\Core;
|
||||||
|
|
||||||
|
use PRAutoBlogger\Tests\BaseTestCase;
|
||||||
|
use Brain\Monkey\Functions;
|
||||||
|
|
||||||
|
class CostReporterTest extends BaseTestCase {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb instance.
|
||||||
|
*/
|
||||||
|
private $wpdb;
|
||||||
|
|
||||||
|
protected function setUp(): void {
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
$this->wpdb = $this->create_mock_wpdb();
|
||||||
|
$GLOBALS['wpdb'] = $this->wpdb;
|
||||||
|
|
||||||
|
// CostReporter methods call get_option for budget settings.
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_monthly_budget_usd' => '50.00',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub current_time used in date-based queries.
|
||||||
|
$this->stub_current_time( '2026-04-12 10:00:00' );
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void {
|
||||||
|
unset( $GLOBALS['wpdb'] );
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test get_monthly_spend returns float.
|
||||||
|
*/
|
||||||
|
public function test_get_monthly_spend_returns_float(): void {
|
||||||
|
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||||
|
$this->wpdb->method( 'get_var' )->willReturn( '10.50' );
|
||||||
|
|
||||||
|
$reporter = new \PRAutoBlogger_Cost_Reporter();
|
||||||
|
$spend = $reporter->get_monthly_spend();
|
||||||
|
|
||||||
|
$this->assertIsFloat( $spend );
|
||||||
|
$this->assertGreaterThanOrEqual( 0.0, $spend );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test get_daily_spend returns array.
|
||||||
|
*/
|
||||||
|
public function test_get_daily_spend_returns_array(): void {
|
||||||
|
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||||
|
$this->wpdb->method( 'get_results' )->willReturn( [] );
|
||||||
|
|
||||||
|
$reporter = new \PRAutoBlogger_Cost_Reporter();
|
||||||
|
$daily = $reporter->get_daily_spend( 30 );
|
||||||
|
|
||||||
|
$this->assertIsArray( $daily );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test get_spend_by_stage returns array.
|
||||||
|
*/
|
||||||
|
public function test_get_spend_by_stage_returns_array(): void {
|
||||||
|
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||||
|
$this->wpdb->method( 'get_results' )->willReturn( [] );
|
||||||
|
|
||||||
|
$reporter = new \PRAutoBlogger_Cost_Reporter();
|
||||||
|
$spend = $reporter->get_spend_by_stage( '2026-04-01', '2026-04-30' );
|
||||||
|
|
||||||
|
$this->assertIsArray( $spend );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test get_budget_utilization returns float between 0 and 100+.
|
||||||
|
*/
|
||||||
|
public function test_get_budget_utilization_returns_float(): void {
|
||||||
|
$reporter = new \PRAutoBlogger_Cost_Reporter();
|
||||||
|
$utilization = $reporter->get_budget_utilization();
|
||||||
|
|
||||||
|
$this->assertIsFloat( $utilization );
|
||||||
|
$this->assertGreaterThanOrEqual( 0.0, $utilization );
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -68,20 +68,6 @@ class CostTrackerTest extends BaseTestCase {
|
|||||||
$this->assertFalse( $tracker->is_budget_exceeded() );
|
$this->assertFalse( $tracker->is_budget_exceeded() );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Test get_monthly_spend returns float.
|
|
||||||
*/
|
|
||||||
public function test_get_monthly_spend_returns_float(): void {
|
|
||||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
|
||||||
$this->wpdb->method( 'get_var' )->willReturn( '10.50' );
|
|
||||||
|
|
||||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
|
||||||
$spend = $tracker->get_monthly_spend();
|
|
||||||
|
|
||||||
$this->assertIsFloat( $spend );
|
|
||||||
$this->assertGreaterThanOrEqual( 0.0, $spend );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test get_current_run_cost returns float.
|
* Test get_current_run_cost returns float.
|
||||||
*/
|
*/
|
||||||
@@ -98,43 +84,6 @@ class CostTrackerTest extends BaseTestCase {
|
|||||||
$this->assertGreaterThanOrEqual( 0.0, $cost );
|
$this->assertGreaterThanOrEqual( 0.0, $cost );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Test get_daily_spend returns array.
|
|
||||||
*/
|
|
||||||
public function test_get_daily_spend_returns_array(): void {
|
|
||||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
|
||||||
$this->wpdb->method( 'get_results' )->willReturn( [] );
|
|
||||||
|
|
||||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
|
||||||
$daily = $tracker->get_daily_spend( 30 );
|
|
||||||
|
|
||||||
$this->assertIsArray( $daily );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test get_spend_by_stage returns array.
|
|
||||||
*/
|
|
||||||
public function test_get_spend_by_stage_returns_array(): void {
|
|
||||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
|
||||||
$this->wpdb->method( 'get_results' )->willReturn( [] );
|
|
||||||
|
|
||||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
|
||||||
$spend = $tracker->get_spend_by_stage( '2026-04-01', '2026-04-30' );
|
|
||||||
|
|
||||||
$this->assertIsArray( $spend );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test get_budget_utilization returns float between 0 and 1.
|
|
||||||
*/
|
|
||||||
public function test_get_budget_utilization_returns_float(): void {
|
|
||||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
|
||||||
$utilization = $tracker->get_budget_utilization();
|
|
||||||
|
|
||||||
$this->assertIsFloat( $utilization );
|
|
||||||
$this->assertGreaterThanOrEqual( 0.0, $utilization );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test log_api_call with mock database.
|
* Test log_api_call with mock database.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -18,8 +18,11 @@ class ImagePipelineTest extends BaseTestCase {
|
|||||||
protected function setUp(): void {
|
protected function setUp(): void {
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
// Mock WordPress functions.
|
// Mock WordPress functions used by the pipeline and its dependencies.
|
||||||
Functions\when( 'wp_generate_uuid4' )->returnArg();
|
Functions\when( 'is_wp_error' )->alias( function ( $thing ) {
|
||||||
|
return $thing instanceof \WP_Error;
|
||||||
|
} );
|
||||||
|
Functions\when( 'wp_generate_uuid4' )->justReturn( 'test-uuid' );
|
||||||
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
|
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
|
||||||
static $options = [
|
static $options = [
|
||||||
'prautoblogger_image_enabled' => '1',
|
'prautoblogger_image_enabled' => '1',
|
||||||
@@ -28,7 +31,12 @@ class ImagePipelineTest extends BaseTestCase {
|
|||||||
return $options[ $key ] ?? $default;
|
return $options[ $key ] ?? $default;
|
||||||
} );
|
} );
|
||||||
Functions\when( 'sanitize_text_field' )->returnArg();
|
Functions\when( 'sanitize_text_field' )->returnArg();
|
||||||
|
Functions\when( 'wp_strip_all_tags' )->alias( function ( $str ) {
|
||||||
|
return trim( strip_tags( $str ) );
|
||||||
|
} );
|
||||||
Functions\when( 'update_post_meta' )->justReturn( true );
|
Functions\when( 'update_post_meta' )->justReturn( true );
|
||||||
|
Functions\when( 'sanitize_title' )->returnArg();
|
||||||
|
Functions\when( 'esc_html__' )->returnArg();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,13 +48,10 @@ class ImagePipelineTest extends BaseTestCase {
|
|||||||
return $options[ $key ] ?? $default;
|
return $options[ $key ] ?? $default;
|
||||||
} );
|
} );
|
||||||
|
|
||||||
// Mock the logger.
|
$provider = $this->createMock( \PRAutoBlogger_Image_Provider_Interface::class );
|
||||||
$logger = $this->createMock( \PRAutoBlogger_Logger::class );
|
|
||||||
$logger->expects( $this->once() )->method( 'info' );
|
|
||||||
|
|
||||||
$provider = $this->createMock( \PRAutoBlogger_Image_Provider_Interface::class );
|
|
||||||
$provider->expects( $this->never() )->method( 'generate_image' );
|
$provider->expects( $this->never() )->method( 'generate_image' );
|
||||||
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
|
|
||||||
|
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
|
||||||
|
|
||||||
$pipeline = new \PRAutoBlogger_Image_Pipeline( $provider, $cost_tracker );
|
$pipeline = new \PRAutoBlogger_Image_Pipeline( $provider, $cost_tracker );
|
||||||
$result = $pipeline->generate_and_attach_images( 1, [ 'post_title' => 'Test' ] );
|
$result = $pipeline->generate_and_attach_images( 1, [ 'post_title' => 'Test' ] );
|
||||||
@@ -75,7 +80,6 @@ class ImagePipelineTest extends BaseTestCase {
|
|||||||
|
|
||||||
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
|
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
|
||||||
$cost_tracker->method( 'would_exceed_budget' )->willReturn( false );
|
$cost_tracker->method( 'would_exceed_budget' )->willReturn( false );
|
||||||
$cost_tracker->method( 'log_image_generation' )->willReturn( true );
|
|
||||||
|
|
||||||
$pipeline = new \PRAutoBlogger_Image_Pipeline( $provider, $cost_tracker );
|
$pipeline = new \PRAutoBlogger_Image_Pipeline( $provider, $cost_tracker );
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ class ImagePromptBuilderTest extends BaseTestCase {
|
|||||||
|
|
||||||
// Mock WordPress functions.
|
// Mock WordPress functions.
|
||||||
Functions\when( 'wp_strip_all_tags' )->alias( function ( $str ) {
|
Functions\when( 'wp_strip_all_tags' )->alias( function ( $str ) {
|
||||||
return wp_strip_all_tags( $str );
|
return trim( strip_tags( $str ) );
|
||||||
} );
|
} );
|
||||||
Functions\when( 'sanitize_text_field' )->returnArg();
|
Functions\when( 'sanitize_text_field' )->returnArg();
|
||||||
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
|
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
|
||||||
|
|||||||
@@ -48,6 +48,9 @@ class OpenRouterProviderTest extends BaseTestCase {
|
|||||||
);
|
);
|
||||||
Functions\when( 'set_transient' )->justReturn( true );
|
Functions\when( 'set_transient' )->justReturn( true );
|
||||||
|
|
||||||
|
// Stub URL parsing.
|
||||||
|
Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
|
||||||
|
|
||||||
// Stub HTTP functions for API calls.
|
// Stub HTTP functions for API calls.
|
||||||
Functions\when( 'wp_remote_post' )->justReturn( [
|
Functions\when( 'wp_remote_post' )->justReturn( [
|
||||||
'body' => '{"choices":[{"message":{"content":"test"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}',
|
'body' => '{"choices":[{"message":{"content":"test"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}',
|
||||||
|
|||||||
199
tests/unit/Providers/OpenRouterValidatorTest.php
Normal file
199
tests/unit/Providers/OpenRouterValidatorTest.php
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Tests for PRAutoBlogger_OpenRouter_Validator.
|
||||||
|
*
|
||||||
|
* Validates credential checking logic including encryption, format validation,
|
||||||
|
* and HTTP connectivity probes.
|
||||||
|
* All HTTP calls are mocked — no real API calls.
|
||||||
|
*
|
||||||
|
* @package PRAutoBlogger\Tests\Providers
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace PRAutoBlogger\Tests\Providers;
|
||||||
|
|
||||||
|
use PRAutoBlogger\Tests\BaseTestCase;
|
||||||
|
use Brain\Monkey\Functions;
|
||||||
|
|
||||||
|
class OpenRouterValidatorTest extends BaseTestCase {
|
||||||
|
|
||||||
|
protected function setUp(): void {
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
// Stub get_option with default empty state.
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => '',
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub wp_salt for encryption.
|
||||||
|
Functions\when( 'wp_salt' )->justReturn( 'test_salt_key_for_unit_tests' );
|
||||||
|
|
||||||
|
// Stub URL parsing.
|
||||||
|
Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
|
||||||
|
|
||||||
|
// Stub HTTP functions.
|
||||||
|
Functions\when( 'wp_remote_get' )->justReturn( [
|
||||||
|
'body' => '{}',
|
||||||
|
'response' => [ 'code' => 200 ],
|
||||||
|
] );
|
||||||
|
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 200 );
|
||||||
|
Functions\when( 'wp_remote_retrieve_body' )->justReturn( '{}' );
|
||||||
|
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validator can be instantiated.
|
||||||
|
*/
|
||||||
|
public function test_validator_instantiation(): void {
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$this->assertInstanceOf( \PRAutoBlogger_OpenRouter_Validator::class, $validator );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test run() returns array with expected keys.
|
||||||
|
*/
|
||||||
|
public function test_run_returns_array_with_status(): void {
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertIsArray( $result );
|
||||||
|
$this->assertArrayHasKey( 'status', $result );
|
||||||
|
$this->assertArrayHasKey( 'message', $result );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when no API key is configured.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_no_api_key(): void {
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'No API key', $result['message'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation succeeds with a valid decrypted key.
|
||||||
|
*/
|
||||||
|
public function test_run_succeeds_with_valid_key(): void {
|
||||||
|
// Round-trip through encryption to get a valid ciphertext.
|
||||||
|
$plaintext = 'sk-or-test-key-1234567890';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'ok', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'connected', strtolower( $result['message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when decryption fails.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_bad_ciphertext(): void {
|
||||||
|
// Stub get_option to return invalid ciphertext.
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => 'corrupted_base64_data_that_is_not_valid',
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'decryption', strtolower( $result['message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when decrypted key has wrong format.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_bad_key_format(): void {
|
||||||
|
// Encrypt a key that doesn't start with "sk-or-".
|
||||||
|
$plaintext = 'invalid-key-format';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'corrupted', strtolower( $result['message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when HTTP request fails.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_wp_error(): void {
|
||||||
|
$plaintext = 'sk-or-test-key-1234567890';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub wp_remote_get to return an error.
|
||||||
|
Functions\when( 'is_wp_error' )->justReturn( true );
|
||||||
|
Functions\when( 'wp_remote_get' )->alias(
|
||||||
|
function () {
|
||||||
|
$error = new \WP_Error( 'http_error', 'Connection refused' );
|
||||||
|
return $error;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'Network error', $result['message'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when API returns non-200 status.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_http_error(): void {
|
||||||
|
$plaintext = 'sk-or-test-key-1234567890';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub to return 401 error.
|
||||||
|
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||||
|
Functions\when( 'wp_remote_get' )->justReturn( [
|
||||||
|
'body' => '{"error":{"message":"Unauthorized"}}',
|
||||||
|
'response' => [ 'code' => 401 ],
|
||||||
|
] );
|
||||||
|
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 401 );
|
||||||
|
Functions\when( 'wp_remote_retrieve_body' )->justReturn( '{"error":{"message":"Unauthorized"}}' );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'HTTP 401', $result['message'] );
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -224,8 +224,7 @@ class OpenRouterModelRegistryTest extends BaseTestCase {
|
|||||||
return 'Connection timed out';
|
return 'Connection timed out';
|
||||||
};
|
};
|
||||||
Functions\when( 'wp_remote_get' )->alias( function () {
|
Functions\when( 'wp_remote_get' )->alias( function () {
|
||||||
$e = new \WP_Error_Stub();
|
return new \WP_Error( 'http_request_failed', 'Connection timed out' );
|
||||||
return $e;
|
|
||||||
} );
|
} );
|
||||||
|
|
||||||
// Accept that update_option will be called for the stale flag.
|
// Accept that update_option will be called for the stale flag.
|
||||||
@@ -240,13 +239,3 @@ class OpenRouterModelRegistryTest extends BaseTestCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Minimal WP_Error stub for testing is_wp_error() branches.
|
|
||||||
*/
|
|
||||||
if ( ! class_exists( 'WP_Error_Stub' ) ) {
|
|
||||||
class WP_Error_Stub {
|
|
||||||
public function get_error_message(): string {
|
|
||||||
return 'Connection timed out';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user