1<?php
2declare(strict_types=1);
3
4namespace ZipStream;
5
6class DeflateStream extends Stream
7{
8    protected $filter;
9
10    /**
11     * @var Option\File
12     */
13    protected $options;
14
15    /**
16     * Rewind stream
17     *
18     * @return void
19     */
20    public function rewind(): void
21    {
22        // deflate filter needs to be removed before rewind
23        if ($this->filter) {
24            $this->removeDeflateFilter();
25            $this->seek(0);
26            $this->addDeflateFilter($this->options);
27        } else {
28            rewind($this->stream);
29        }
30    }
31
32    /**
33     * Remove the deflate filter
34     *
35     * @return void
36     */
37    public function removeDeflateFilter(): void
38    {
39        if (!$this->filter) {
40            return;
41        }
42        stream_filter_remove($this->filter);
43        $this->filter = null;
44    }
45
46    /**
47     * Add a deflate filter
48     *
49     * @param Option\File $options
50     * @return void
51     */
52    public function addDeflateFilter(Option\File $options): void
53    {
54        $this->options = $options;
55        // parameter 4 for stream_filter_append expects array
56        // so we convert the option object in an array
57        $optionsArr = [
58            'comment' => $options->getComment(),
59            'method' => $options->getMethod(),
60            'deflateLevel' => $options->getDeflateLevel(),
61            'time' => $options->getTime()
62        ];
63        $this->filter = stream_filter_append(
64            $this->stream,
65            'zlib.deflate',
66            STREAM_FILTER_READ,
67            $optionsArr
68        );
69    }
70}
71