Completed
Pull Request — develop (#1350)
by Naveen
03:22
created

Video_Sitemap::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @since 3.31.0
4
 * @author Naveen Muthusamy <[email protected]>
5
 */
6
7
namespace Wordlift\Videoobject\Sitemap;
8
9
use Wordlift\Cache\Ttl_Cache;
10
11
class Video_Sitemap {
12
13
	/**
14
	 * @var Ttl_Cache
15
	 */
16
	private $sitemap_cache;
17
18
	const XML_CACHE_KEY = 'video_sitemap';
19
20
	public function __construct( $sitemap_cache ) {
21
		$this->sitemap_cache = $sitemap_cache;
22
	}
23
24
	public function init() {
25
		if ( self::is_video_sitemap_enabled() ) {
26
			add_action( 'template_include', array( $this, 'print_video_sitemap' ), 1 );
27
		}
28
	}
29
30
	/**
31
	 * Print video sitemap.
32
	 */
33
	public function print_video_sitemap() {
34
		global $wp;
35
36
		$url = home_url( $wp->request );
37
38
		if ( strpos( $url, 'wl-video-sitemap.xml' ) === false ) {
39
			return;
40
		}
41
42
		header( "Content-type: text/xml" );
43
44
		$xml = $this->sitemap_cache->get( self::XML_CACHE_KEY );
45
46
		if ( ! $xml ) {
47
			$xml = $this->get_sitemap_xml();
48
			$this->sitemap_cache->put( self::XML_CACHE_KEY, $xml );
49
		}
50
51
		echo $xml;
52
		die();
53
	}
54
55
	public static function is_video_sitemap_enabled() {
56
		return intval( get_option( '_wl_video_sitemap_generation', false ) ) === 1;
57
	}
58
59
	/**
60
	 * @return string
61
	 */
62
	private function get_sitemap_xml() {
63
		$sitemap_start_tag = <<<EOF
64
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
65
        xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
66
EOF;
67
		$sitemap_body      = Xml_Generator::get_xml_for_all_posts_with_videos();
68
69
		$sitemap_end_tag = "</urlset>";
70
71
		$xml = $sitemap_start_tag . $sitemap_body . $sitemap_end_tag;
72
73
		return $xml;
74
	}
75
76
}