| 1 |
<?php |
| 2 |
/** |
| 3 |
* Endpoints: Parse.ly `/analytics/posts` API proxy endpoint class |
| 4 |
* |
| 5 |
* @package Parsely |
| 6 |
* @since 3.4.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
declare(strict_types=1); |
| 10 |
|
| 11 |
namespace Parsely\Endpoints; |
| 12 |
|
| 13 |
use stdClass; |
| 14 |
use WP_REST_Request; |
| 15 |
use WP_Error; |
| 16 |
use Parsely\Parsely; |
| 17 |
|
| 18 |
use function Parsely\Utils\get_date_format; |
| 19 |
|
| 20 |
/** |
| 21 |
* Configures the `/stats/posts` REST API endpoint. |
| 22 |
*/ |
| 23 |
final class Analytics_Posts_API_Proxy extends Base_API_Proxy { |
| 24 |
|
| 25 |
/** |
| 26 |
* Registers the endpoint's WP REST route. |
| 27 |
*/ |
| 28 |
public function run(): void { |
| 29 |
$this->register_endpoint( '/stats/posts' ); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Cached "proxy" to the Parse.ly `/analytics/posts` API endpoint. |
| 34 |
* |
| 35 |
* @param WP_REST_Request $request The request object. |
| 36 |
* |
| 37 |
* @return stdClass|WP_Error stdClass containing the data or a WP_Error object on failure. |
| 38 |
*/ |
| 39 |
public function get_items( WP_REST_Request $request ) { |
| 40 |
return $this->get_data( $request ); |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Generates the final data from the passed response. |
| 45 |
* |
| 46 |
* @param array<stdClass> $response The response received by the proxy. |
| 47 |
* @return array<stdClass> The generated data. |
| 48 |
*/ |
| 49 |
protected function generate_data( $response ): array { |
| 50 |
$date_format = get_date_format(); |
| 51 |
$site_id = $this->parsely->get_site_id(); |
| 52 |
|
| 53 |
return array_map( |
| 54 |
static function( stdClass $item ) use ( $date_format, $site_id ) { |
| 55 |
return (object) array( |
| 56 |
'author' => $item->author, |
| 57 |
'dashUrl' => Parsely::get_dash_url( $site_id, $item->url ), |
| 58 |
'date' => $item->pub_date ? wp_date( $date_format, strtotime( $item->pub_date ) ) : null, |
| 59 |
// Unique ID (can be replaced by Parse.ly API ID if it becomes available). |
| 60 |
'id' => $item->url, |
| 61 |
// WordPress Post ID (0 if the post cannot be found, might not be unique). |
| 62 |
'postId' => url_to_postid( $item->url ), // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.url_to_postid_url_to_postid |
| 63 |
'thumbUrlMedium' => $item->thumb_url_medium, |
| 64 |
'title' => $item->title, |
| 65 |
'url' => $item->url, |
| 66 |
'views' => $item->metrics->views, |
| 67 |
); |
| 68 |
}, |
| 69 |
$response |
| 70 |
); |
| 71 |
} |
| 72 |
} |
| 73 |
|