<?php

/**
 * Implements common logic for testing Wiaas API
 *
 * Class Wiaas_API_Unit_Test_Case
 */
class Wiaas_API_Unit_Test_Case extends Wiaas_Unit_Test_Case {
	protected $server;

	function setUp() {
		parent::setUp();

		/** @var WP_REST_Server $wp_rest_server */
		global $wp_rest_server;
		$this->server = $wp_rest_server = new \WP_REST_Server;
		do_action( 'rest_api_init' );
	}

	/**
	 * Test that given endpoint is forbidden when accessed as guest
	 *
	 * @param WP_REST_Request $request Request to test
	 */
	function check_endpoint_forbidden_for_guest($request) {
		wp_set_current_user(0);

		$response = $this->server->dispatch( $request );

		$this->assertNotNull($response);
		$this->assertInstanceOf('WP_REST_Response',$response);
		$this->assertTrue($response->is_error());
		$this->assertEquals($response->get_status(), 401);

		$error_data = $response->as_error();
		$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
	}

	/**
	 * Handles common action during dispatching of rest request
	 *
	 * @param WP_REST_Request $request
	 * @param int $expected_status_code
	 * @param bool $is_error_expected
	 *
	 * @return mixed Result error when error is expected, result data otherwise
	 */
	function dispatch_endpoint_request($request, $expected_status_code = 200, $is_error_expected = false) {
		$response = $this->server->dispatch( $request );

		$this->assertNotNull($response);
		$this->assertInstanceOf('WP_REST_Response',$response);
		$this->assertEquals($response->get_status(), $expected_status_code);

		if ($is_error_expected) {
			$this->assertTrue($response->is_error());
			return $response->as_error();
		}

		$this->assertFalse($response->is_error());
		return $response->get_data();
	}
}