Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
PdfStream
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
4 / 4
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setFilter
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 toPdf
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 toIndirectObject
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Phpdftk\Pdf\Core;
6
7use Phpdftk\Filters\FilterInterface;
8
9/**
10 * Represents a PDF stream object: a dictionary + binary/text data.
11 *
12 * The /Length entry in the dictionary is set automatically when toPdf() is called.
13 */
14class PdfStream extends PdfObject
15{
16    public PdfDictionary $dictionary;
17    public string $data = '';
18
19    private ?FilterInterface $filter = null;
20    private ?string $pdfFilterName = null;
21
22    public function __construct(PdfDictionary $dictionary = new PdfDictionary(), string $data = '')
23    {
24        $this->dictionary = $dictionary;
25        $this->data = $data;
26    }
27
28    /**
29     * Set a filter to encode/decode the stream data.
30     *
31     * @param FilterInterface $filter       The filter implementation
32     * @param string          $pdfFilterName The PDF filter name (e.g. 'FlateDecode', 'ASCII85Decode')
33     */
34    public function setFilter(FilterInterface $filter, string $pdfFilterName): void
35    {
36        $this->filter = $filter;
37        $this->pdfFilterName = $pdfFilterName;
38    }
39
40    /**
41     * Returns the stream body: dictionary, stream keyword, data, endstream.
42     * /Length is injected into the dictionary at serialization time.
43     * If a filter is set, the data is encoded before writing.
44     */
45    public function toPdf(): string
46    {
47        $streamData = $this->data;
48
49        if ($this->filter !== null && $this->pdfFilterName !== null) {
50            $streamData = $this->filter->encode($streamData);
51            $this->dictionary->set('Filter', new PdfName($this->pdfFilterName));
52        }
53
54        // Set the length based on current (possibly encoded) data
55        $this->dictionary->set('Length', strlen($streamData));
56
57        return $this->dictionary->toPdf()
58            . "\nstream\n"
59            . $streamData
60            . "\nendstream";
61    }
62
63    public function toIndirectObject(): string
64    {
65        return sprintf(
66            "%d %d obj\n%s\nendobj",
67            $this->objectNumber,
68            $this->generationNumber,
69            $this->toPdf(),
70        );
71    }
72}