Completed
Push — master ( ce7b38...6ec792 )
by Peter
04:34
created

DomKeeper::addUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 21
ccs 0
cts 20
cp 0
rs 9.3142
cc 1
eloc 17
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * GpsLab component.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2011, Peter Gribanov
7
 * @license   http://opensource.org/licenses/MIT
8
 */
9
namespace GpsLab\Component\Sitemap\Uri\Keeper;
10
11
use GpsLab\Component\Sitemap\Uri\UriInterface;
12
13
class DomKeeper implements KeeperInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $filename = '';
19
20
    /**
21
     * @var \DOMDocument
22
     */
23
    protected $doc;
24
25
    /**
26
     * @var \DOMElement
27
     */
28
    protected $urlset;
29
30
    /**
31
     * @param \DOMDocument $doc
32
     * @param string $filename
33
     */
34
    public function __construct(\DOMDocument $doc, $filename)
35
    {
36
        $this->doc = $doc;
37
        $this->filename = $filename;
38
39
        $this->createUrlSet();
40
    }
41
42
    /**
43
     * @param UriInterface $url
44
     *
45
     * @return self
46
     */
47
    public function addUri(UriInterface $url)
48
    {
49
        $this->urlset->appendChild(
50
            $this->doc
51
                ->createElement('url')
52
                ->appendChild(
53
                    $this->doc->createElement('loc', htmlspecialchars($url->getLoc()))
54
                )->parentNode
55
                ->appendChild(
56
                    $this->doc->createElement('lastmod', $url->getLastMod()->format('Y-m-d'))
57
                )->parentNode
58
                ->appendChild(
59
                    $this->doc->createElement('changefreq', $url->getChangeFreq())
60
                )->parentNode
61
                ->appendChild(
62
                    $this->doc->createElement('priority', $url->getPriority())
63
                )->parentNode
64
        );
65
66
        return $this;
67
    }
68
69
    /**
70
     * @return bool
71
     */
72
    public function save()
73
    {
74
        $result = (bool)$this->doc->save($this->filename);
75
76
        $this->doc->removeChild($this->urlset);
77
        unset($this->urlset);
78
79
        $this->createUrlSet();
80
81
        return $result;
82
    }
83
84
    protected function createUrlSet()
85
    {
86
        $this->urlset = $this->doc->createElement('urlset');
87
        $this->urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
88
        $this->doc->appendChild($this->urlset);
89
    }
90
}
91