| 1 |
<?php |
| 2 |
/** |
| 3 |
* Endpoints: Parse.ly `/analytics/post/detail` API proxy endpoint class |
| 4 |
* |
| 5 |
* @package Parsely |
| 6 |
* @since 3.6.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
declare(strict_types=1); |
| 10 |
|
| 11 |
namespace Parsely\Endpoints; |
| 12 |
|
| 13 |
use Parsely\Parsely; |
| 14 |
use stdClass; |
| 15 |
use WP_REST_Request; |
| 16 |
use WP_Error; |
| 17 |
|
| 18 |
/** |
| 19 |
* Configures the `/stats/post/detail` REST API endpoint. |
| 20 |
*/ |
| 21 |
final class Analytics_Post_Detail_API_Proxy extends Base_API_Proxy { |
| 22 |
|
| 23 |
/** |
| 24 |
* Registers the endpoint's WP REST route. |
| 25 |
*/ |
| 26 |
public function run(): void { |
| 27 |
$this->register_endpoint( '/stats/post/detail' ); |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Cached "proxy" to the Parse.ly `/analytics/post/detail` API endpoint. |
| 32 |
* |
| 33 |
* @param WP_REST_Request $request The request object. |
| 34 |
* |
| 35 |
* @return stdClass|WP_Error stdClass containing the data or a WP_Error object on failure. |
| 36 |
*/ |
| 37 |
public function get_items( WP_REST_Request $request ) { |
| 38 |
return $this->get_data( $request ); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Generates the final data from the passed response. |
| 43 |
* |
| 44 |
* @param array<stdClass> $response The response received by the proxy. |
| 45 |
* @return array<stdClass> The generated data. |
| 46 |
*/ |
| 47 |
protected function generate_data( $response ): array { |
| 48 |
$site_id = $this->parsely->get_site_id(); |
| 49 |
|
| 50 |
return array_map( |
| 51 |
static function( stdClass $item ) use ( $site_id ) { |
| 52 |
return (object) array( |
| 53 |
'avgEngaged' => self::get_duration( (float) $item->avg_engaged ), |
| 54 |
'dashUrl' => Parsely::get_dash_url( $site_id, $item->url ), |
| 55 |
'url' => $item->url, |
| 56 |
'views' => number_format_i18n( $item->metrics->views ), |
| 57 |
'visitors' => number_format_i18n( $item->metrics->visitors ), |
| 58 |
); |
| 59 |
}, |
| 60 |
$response |
| 61 |
); |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Returns the passed float as a time duration in m:ss format. |
| 66 |
* |
| 67 |
* Examples: |
| 68 |
* - $time of 1.005 yields '1:00'. |
| 69 |
* - $time of 1.5 yields '1:30'. |
| 70 |
* - $time of 1.999 yields '2:00'. |
| 71 |
* |
| 72 |
* @since 3.6.0 |
| 73 |
* |
| 74 |
* @param float $time The time as a float number. |
| 75 |
* @return string The resulting formatted time duration. |
| 76 |
*/ |
| 77 |
private static function get_duration( float $time ): string { |
| 78 |
$minutes = absint( $time ); |
| 79 |
$seconds = absint( round( fmod( $time, 1 ) * 60 ) ); |
| 80 |
|
| 81 |
if ( 60 === $seconds ) { |
| 82 |
$minutes++; |
| 83 |
$seconds = 0; |
| 84 |
} |
| 85 |
|
| 86 |
return sprintf( '%2d:%02d', $minutes, $seconds ); |
| 87 |
} |
| 88 |
} |
| 89 |
|