Sitemap::add()   D
last analyzed

Complexity

Conditions 9
Paths 10

Size

Total Lines 32
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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