<?php

namespace ParcelPanel\CmsPlus;

use ParcelPanel\CmsPlus\Trait\SingletonTrait;
use WP_REST_Posts_Controller;
use WP_REST_Request;

/**
 * 根据 URL 路径获取文章
 */
class ActionGetPostForUrl
{
    use SingletonTrait;

    public function init()
    {
        add_action('rest_api_init', function () {
            register_rest_route(PARCELPANEL_CMS_PLUS_ROUTE_NAMESPACE, '/path/(?P<url>.*?)', array(
                'methods' => 'GET',
                'callback' => [$this, 'get_post_for_url']
            ));
        });
    }

    public function get_post_for_url($data): \WP_Error|\WP_REST_Response|\WP_Post
    {
        $postId = url_to_postid($data['url']);
        $postType = get_post_type($postId);

        $request = new WP_REST_Request('GET', "/wp/v2/{$postType}s/{$postId}");
        $request->set_url_params(array('id' => $postId));

        $controller = new WP_REST_Posts_Controller($postType);
        return $controller->get_item($request);
    }
}