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

StreamKeeper::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

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 9
ccs 0
cts 8
cp 0
rs 9.6666
cc 1
eloc 6
nc 1
nop 0
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 StreamKeeper implements KeeperInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $filename = '';
19
20
    /**
21
     * @var resource
22
     */
23
    protected $handle;
24
25
    /**
26
     * @param string $filename
27
     */
28
    public function __construct($filename)
29
    {
30
        $this->filename = $filename;
31
    }
32
33
    /**
34
     * @param UriInterface $url
35
     *
36
     * @return self
37
     */
38 View Code Duplication
    public function addUri(UriInterface $url)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39
    {
40
        $this->start();
41
42
        fwrite(
43
            $this->handle,
44
            '<url>'.
45
                '<loc>'.htmlspecialchars($url->getLoc()).'</loc>'.
46
                '<lastmod>'.$url->getLastMod()->format('Y-m-d').'</lastmod>'.
47
                '<changefreq>'.$url->getChangeFreq().'</changefreq>'.
48
                '<priority>'.$url->getPriority().'</priority>'.
49
            '</url>'
50
        );
51
52
        return $this;
53
    }
54
55
    /**
56
     * @return bool
57
     */
58
    public function save()
59
    {
60
        $this->start();
61
        fwrite($this->handle, '</urlset>');
62
        $result = fclose($this->handle);
63
        $this->handle = null;
64
65
        return $result;
66
    }
67
68
    protected function start()
69
    {
70
        if (!is_resource($this->handle)) {
71
            $this->handle = @fopen($this->filename, 'wb');
72
            if ($this->handle === false) {
73
                throw new \RuntimeException(sprintf('Failed to write file "%s".', $this->filename));
74
            }
75
76
            fwrite(
77
                $this->handle,
78
                '<?xml version="1.0" encoding="utf-8"?>'.PHP_EOL.
79
                '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
80
            );
81
        }
82
    }
83
}
84