Completed
Push — master ( 416cb1...222de5 )
by Anton
03:44
created

Sitemap::add()   D

Complexity

Conditions 9
Paths 10

Size

Total Lines 32
Code Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 32
rs 4.9091
cc 9
eloc 10
nc 10
nop 4
1
<?php
2
3
namespace Utils\Tools {
4
5
	use Utils\Lister, Utils\Validate, Date, Explorer, Number, XML;
6
7
	class Sitemap {
8
9
		private $xml = null, $loaded = false;
10
11
		# Constructor
12
13
		public function __construct() {
14
15
			$urlset = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />';
16
17
			if (false !== ($xml = XML::create($urlset))) $this->xml = $xml;
18
		}
19
20
		# Load sitemap
21
22
		public function load(int $time) {
23
24
			$file_name = (DIR_SYSTEM_DATA . 'Sitemap.xml');
25
26
			$modified = Explorer::modified($file_name);
27
28
			if ((false === $modified) || ($modified <= $time)) return false;
29
30
			if (false === ($xml = Explorer::xml($file_name))) return false;
31
32
			# ------------------------
33
34
			return (($this->xml = $xml) && ($this->loaded = true));
35
		}
36
37
		# Save sitemap
38
39
		public function save() {
40
41
			if ((null === $this->xml) || $this->loaded) return false;
42
43
			$file_name = (DIR_SYSTEM_DATA . 'Sitemap.xml');
44
45
			# ------------------------
46
47
			return Explorer::save($file_name, $this->xml->asXML(), true);
48
		}
49
50
		# Add item
51
52
		public function add(string $loc, string $lastmod = null, string $changefreq = null, float $priority = null) {
53
54
			if ((null === $this->xml) || $this->loaded) return false;
55
56
			if (false === ($loc = Validate::url($loc))) return false;
57
58
			# Create url object
59
60
			($url = $this->xml->addChild('url'))->addChild('loc', $loc);
61
62
			# Set last modified
63
64
			if ((null !== $lastmod) && (false !== ($lastmod = Date::validate($lastmod, DATE_FORMAT_W3C)))) {
65
66
				$url->addChild('lastmod', $lastmod);
67
			}
68
69
			# Set change frequency
70
71
			if ((null !== $changefreq) && (false !== ($changefreq = Lister\Frequency::validate($changefreq)))) {
72
73
				$url->addChild('changefreq', $changefreq);
74
			}
75
76
			# Set priority
77
78
			if (null !== $priority) $url->addChild('priority', Number::formatFloat($priority, 0, 1, 1));
79
80
			# ------------------------
81
82
			return true;
83
		}
84
85
		# Return XMl
86
87
		public function xml() {
88
89
			return $this->xml;
90
		}
91
	}
92
}
93