<?php

/**
 * @group canonical
 * @group rewrite
 * @ticket 12456
 */
class Tests_Canonical_redirectPostId extends WP_Canonical_UnitTestCase {
	protected $post_id;

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

		$this->post_id = self::factory()->post->create(
			array(
				'post_title' => 'Foo Bar',
				'post_name'  => 'foo-bar',
			)
		);

		$this->set_permalink_structure( '/%post_id%/%postname%/' );

		flush_rewrite_rules();
	}

	public function tearDown() {
		$this->post_id = null;

		parent::tearDown();
	}

	public function test_old_slug_redirect() {
		$old_permalink = user_trailingslashit( get_site_url().'/'.$this->post_id );

		$permalink = user_trailingslashit( get_permalink( $this->post_id ) );

		$this->go_to( $old_permalink );
		
		$can_url = $this->get_canonical( $old_permalink );
		
		$this->assertSame( $permalink, $can_url );
	}

	/**
	 * Get the canonical URL given a raw URL.
	 *
	 * @param string $test_url Should be absolute 
	 *                         ie http://example.com/category/uncategorized/
	 * @return $can_url Returns the original $test_url if no canonical can be generated, otherwise returns
	 *                  the fully-qualified URL as generated by redirect_canonical().
	 */
	public function get_canonical( $test_url ) {
		$can_url = redirect_canonical( $test_url, false );
		if ( ! $can_url ) {
			return $test_url; // No redirect will take place for this request.
		}

		return $can_url;
	}
}
