Completed
Branch 0.2.3 (4e241d)
by Anton
15:52 queued 09:37
created

Sitemap::load()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 16
rs 9.2
c 1
b 0
f 0
cc 4
eloc 7
nc 3
nop 1
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
			$this->xml = $xml; $this->loaded = true;
33
34
			# ------------------------
35
36
			return true;
37
		}
38
39
		# Save sitemap
40
41
		public function save() {
42
43
			if ((null === $this->xml) || $this->loaded) return false;
44
45
			$file_name = (DIR_SYSTEM_DATA . 'Sitemap.xml');
46
47
			if (false === Explorer::save($file_name, XML::string($this->xml), true)) return false;
48
49
			# ------------------------
50
51
			return true;
52
		}
53
54
		# Add item
55
56
		public function add(string $loc, string $lastmod = null, string $changefreq = null, float $priority = null) {
57
58
			if ((null === $this->xml) || $this->loaded) return false;
59
60
			if (false === ($loc = Validate::url($loc))) return false;
61
62
			# Create url object
63
64
			$url = $this->xml->addChild('url'); $url->addChild('loc', $loc);
65
66
			# Set last modified
67
68
			if ((null !== $lastmod) && (false !== ($lastmod = Date::validate($lastmod, DATE_FORMAT_W3C)))) {
69
70
				$url->addChild('lastmod', $lastmod);
71
			}
72
73
			# Set change frequency
74
75
			if ((null !== $changefreq) && (false !== ($changefreq = Lister\Frequency::validate($changefreq)))) {
76
77
				$url->addChild('changefreq', $changefreq);
78
			}
79
80
			# Set priority
81
82
			if (null !== $priority) $url->addChild('priority', Number::formatFloat($priority, 0, 1, 1));
83
84
			# ------------------------
85
86
			return true;
87
		}
88
89
		# Return XMl
90
91
		public function xml() {
92
93
			return $this->xml;
94
		}
95
	}
96
}
97