RenderIndexFileStream::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
crap 1
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
10
namespace GpsLab\Component\Sitemap\Stream;
11
12
use GpsLab\Component\Sitemap\Render\SitemapIndexRender;
13
use GpsLab\Component\Sitemap\Stream\Exception\FileAccessException;
14
use GpsLab\Component\Sitemap\Stream\Exception\OverflowException;
15
use GpsLab\Component\Sitemap\Stream\Exception\StreamStateException;
16
use GpsLab\Component\Sitemap\Stream\State\StreamState;
17
use GpsLab\Component\Sitemap\Url\Url;
18
19
class RenderIndexFileStream implements FileStream
20
{
21
    /**
22
     * @var SitemapIndexRender
23
     */
24
    private $render;
25
26
    /**
27
     * @var FileStream
28
     */
29
    private $substream;
30
31
    /**
32
     * @var StreamState
33
     */
34
    private $state;
35
36
    /**
37
     * @var resource|null
38
     */
39
    private $handle;
40
41
    /**
42
     * @var string
43
     */
44
    private $host = '';
45
46
    /**
47
     * @var string
48
     */
49
    private $filename = '';
50
51
    /**
52
     * @var string
53
     */
54
    private $tmp_filename = '';
55
56
    /**
57
     * @var int
58
     */
59
    private $index = 0;
60
61
    /**
62
     * @var int
63
     */
64
    private $counter = 0;
65
66
    /**
67
     * @var bool
68
     */
69
    private $empty_index = true;
70
71
    /**
72
     * @param SitemapIndexRender $render
73
     * @param FileStream         $substream
74
     * @param string             $host
75
     * @param string             $filename
76
     */
77 12
    public function __construct(SitemapIndexRender $render, FileStream $substream, $host, $filename)
78
    {
79 12
        $this->render = $render;
80 12
        $this->substream = $substream;
81 12
        $this->host = rtrim($host, '/');
82 12
        $this->filename = $filename;
83 12
        $this->state = new StreamState();
84 12
    }
85
86
    /**
87
     * @return string
88
     */
89 1
    public function getFilename()
90
    {
91 1
        return $this->filename;
92
    }
93
94 9 View Code Duplication
    public function open()
95
    {
96 9
        $this->state->open();
97 9
        $this->substream->open();
98
99 9
        $tmp_filename = tempnam(sys_get_temp_dir(), 'sitemap_index');
100
101 9
        if ($tmp_filename === false) {
102
            throw FileAccessException::failedCreateUnique(sys_get_temp_dir(), 'sitemap_index');
103
        }
104
105 9
        $handle = @fopen($tmp_filename, 'wb');
106
107 9
        if ($handle === false) {
108
            throw FileAccessException::notWritable($tmp_filename);
109
        }
110
111 9
        $this->tmp_filename = $tmp_filename;
112 9
        $this->handle = $handle;
113
114 9
        fwrite($this->handle, $this->render->start());
115 9
    }
116
117 12
    public function close()
118
    {
119 12
        $this->state->close();
120 9
        $this->substream->close();
121
122
        // not add empty sitemap part to index
123 9
        if (!$this->empty_index) {
124 5
            $this->addSubStreamFileToIndex();
125
        }
126
127 8
        fwrite($this->handle, $this->render->end());
128 8
        fclose($this->handle);
129
130 8
        $this->moveParts();
131
132
        // move the sitemap index file from the temporary directory to the target
133 8
        if (!rename($this->tmp_filename, $this->filename)) {
134
            unlink($this->tmp_filename);
135
136
            throw FileAccessException::failedOverwrite($this->tmp_filename, $this->filename);
137
        }
138
139 8
        $this->removeOldParts();
140
141 8
        $this->handle = null;
142 8
        $this->tmp_filename = '';
143 8
        $this->counter = 0;
144 8
    }
145
146
    /**
147
     * @param Url $url
148
     */
149 7
    public function push(Url $url)
150
    {
151 7
        if (!$this->state->isReady()) {
152 2
            throw StreamStateException::notReady();
153
        }
154
155
        try {
156 5
            $this->substream->push($url);
157 1
        } catch (OverflowException $e) {
158 1
            $this->substream->close();
159 1
            $this->addSubStreamFileToIndex();
160 1
            $this->substream->open();
161 1
            $this->substream->push($url);
162
        }
163
164 5
        $this->empty_index = false;
165 5
        ++$this->counter;
166 5
    }
167
168 5
    private function addSubStreamFileToIndex()
169
    {
170 5
        $filename = $this->substream->getFilename();
171 5
        $indexed_filename = $this->getIndexPartFilename($filename, ++$this->index);
172
173 5
        if (!file_exists($filename) || ($time = filemtime($filename)) === false) {
174 1
            throw FileAccessException::notReadable($filename);
175
        }
176
177 4
        $last_mod = (new \DateTimeImmutable())->setTimestamp($time);
178
179
        // rename sitemap file to sitemap part
180 4
        $new_filename = sys_get_temp_dir().'/'.$indexed_filename;
181 4
        if (!rename($filename, $new_filename)) {
182
            throw FileAccessException::failedOverwrite($filename, $new_filename);
183
        }
184
185 4
        fwrite($this->handle, $this->render->sitemap($this->host.'/'.$indexed_filename, $last_mod));
0 ignored issues
show
Security Bug introduced by
It seems like $last_mod defined by (new \DateTimeImmutable())->setTimestamp($time) on line 177 can also be of type false; however, GpsLab\Component\Sitemap...pIndexRender::sitemap() does only seem to accept null|object<DateTimeImmutable>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
186 4
    }
187
188
    /**
189
     * @param string $path
190
     * @param int    $index
191
     *
192
     * @return string
193
     */
194 9
    private function getIndexPartFilename($path, $index)
195
    {
196
        // use explode() for correct add index
197
        // sitemap.xml -> sitemap1.xml
198
        // sitemap.xml.gz -> sitemap1.xml.gz
199
200 9
        list($path, $extension) = explode('.', basename($path), 2) + ['', ''];
201
202 9
        return sprintf('%s%s.%s', $path, $index, $extension);
203
    }
204
205
    /**
206
     * @return int
207
     */
208 4
    public function count()
209
    {
210 4
        return $this->counter;
211
    }
212
213
    /**
214
     * Move parts of the sitemap from the temporary directory to the target.
215
     */
216 8
    private function moveParts()
217
    {
218 8
        $filename = $this->substream->getFilename();
219 8
        for ($i = 1; $i <= $this->index; ++$i) {
220 4
            $indexed_filename = $this->getIndexPartFilename($filename, $i);
221 4
            $source = sys_get_temp_dir().'/'.$indexed_filename;
222 4
            $target = dirname($this->filename).'/'.$indexed_filename;
223 4
            if (!rename($source, $target)) {
224
                throw FileAccessException::failedOverwrite($source, $target);
225
            }
226
        }
227 8
    }
228
229
    /**
230
     * Remove old parts of the sitemap from the target directory.
231
     */
232 8
    private function removeOldParts()
233
    {
234 8
        $filename = $this->substream->getFilename();
235 8
        for ($i = $this->index + 1; true; ++$i) {
236 8
            $indexed_filename = $this->getIndexPartFilename($filename, $i);
237 8
            $target = dirname($this->filename).'/'.$indexed_filename;
238 8
            if (file_exists($target)) {
239
                unlink($target);
240
            } else {
241 8
                break;
242
            }
243
        }
244 8
    }
245
}
246