<?php

namespace FeedsByTag\test;

class TermObjectCache extends \WP_UnitTestCase {

	public function testObjectTermCache() {
		$post_factory = new \WP_UnitTest_Factory_For_Post( $this );
		$term_factory = new \WP_UnitTest_Factory_For_Term( $this );

		register_post_type( 'sandwich', array( 'public' => true ) );
		register_taxonomy( 'condiment', array( 'sandwich' ), array( 'label' => 'Condiments' ) );

		$sauerkraut = $term_factory->create([
			'taxonomy' => 'condiment',
			'name' => 'Sauerkraut'
		]);

		$reuben = $post_factory->create([
			'post_title' => 'Reuben',
			'post_type' => 'sandwich',
		]);

		wp_set_object_terms( $reuben, array( $sauerkraut ), 'condiment' );

		add_filter( 'get_term', array( $this, 'noTermsForGuests' ), 10, 2 );

		$sandwiches = get_posts( [ 'post_type' => 'sandwich', 'update_post_term_cache' => false ] );
		$this->assertCount( 1, $sandwiches ); // This is fine

		$sandwiches = get_posts( [ 'post_type' => 'sandwich', 'update_post_term_cache' => true ] );
		$this->assertCount( 1, $sandwiches ); // This throws an

		remove_filter( 'get_term', array( $this, 'noTermsForGuests' ) );


	}

	public function noTermsForGuests( $term, $taxonomy ) {
		if ( ! is_user_logged_in() ) {
			$term = null;
		}
		return $term;
	}

}
