Completed
Push — master ( 021991...b6042d )
by Hannes
03:28 queued 01:54
created

Merger::merge()   C

Complexity

Conditions 9
Paths 29

Size

Total Lines 47
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 11
Bugs 2 Features 2
Metric Value
c 11
b 2
f 2
dl 0
loc 47
rs 5.2941
cc 9
eloc 28
nc 29
nop 0
1
<?php
2
3
namespace iio\libmergepdf;
4
5
use Symfony\Component\Finder\Finder;
6
7
/**
8
 * Merge existing pdfs into one
9
 */
10
class Merger
11
{
12
    /**
13
     * Array of files to be merged.
14
     *
15
     * Values for each files are filename, Pages object and a boolean value
16
     * indicating if the file should be deleted after merging is complete.
17
     *
18
     * @var array
19
     */
20
    private $files = array();
21
22
    /**
23
     * @var \FPDI Fpdi object
24
     */
25
    private $fpdi;
26
27
    /**
28
     * @var string Directory path used for temporary files
29
     */
30
    private $tempDir;
31
32
    /**
33
     * Constructor
34
     *
35
     * @param \FPDI $fpdi
36
     */
37
    public function __construct(\FPDI $fpdi = null)
38
    {
39
        $this->fpdi = $fpdi ?: new \FPDI;
40
    }
41
42
    /**
43
     * Add raw PDF from string
44
     *
45
     * Note that your PDFs are merged in the order that you add them
46
     *
47
     * @param  string    $pdf
48
     * @param  Pages     $pages
49
     * @return void
50
     * @throws Exception if unable to create temporary file
51
     */
52
    public function addRaw($pdf, Pages $pages = null)
53
    {
54
        assert('is_string($pdf)');
55
56
        // Create temporary file
57
        $fname = $this->getTempFname();
58
        if (@file_put_contents($fname, $pdf) === false) {
59
            throw new Exception("Unable to create temporary file");
60
        }
61
62
        $this->addFromFile($fname, $pages, true);
63
    }
64
65
    /**
66
     * Add PDF from filesystem path
67
     *
68
     * Note that your PDFs are merged in the order that you add them
69
     *
70
     * @param  string    $fname   Name of file to add
71
     * @param  Pages     $pages   Pages to add from file
72
     * @param  bool      $cleanup Flag if file should be deleted after merging
73
     * @return void
74
     * @throws Exception If $fname is not a valid file
75
     */
76
    public function addFromFile($fname, Pages $pages = null, $cleanup = false)
77
    {
78
        assert('is_string($fname)');
79
        assert('is_bool($cleanup)');
80
81
        if (!is_file($fname) || !is_readable($fname)) {
82
            throw new Exception("'$fname' is not a valid file");
83
        }
84
85
        if (!$pages) {
86
            $pages = new Pages();
87
        }
88
89
        $this->files[] = array($fname, $pages, $cleanup);
90
    }
91
92
    /**
93
     * Add files using iterator
94
     *
95
     * @param  array|\Traversable $iterator
96
     * @return void
97
     * @throws Exception If $iterator is not valid
98
     */
99
    public function addIterator($iterator)
100
    {
101
        if (!is_array($iterator) && !$iterator instanceof \Traversable) {
102
            throw new Exception("\$iterator must be traversable");
103
        }
104
105
        foreach ($iterator as $fname) {
106
            $this->addFromFile($fname);
107
        }
108
    }
109
110
    /**
111
     * Add files using symfony finder
112
     *
113
     * @param  Finder $finder
114
     * @return void
115
     */
116
    public function addFinder(Finder $finder)
117
    {
118
        foreach ($finder as $fileInfo) {
119
            $this->addFromFile($fileInfo->getRealpath());
120
        }
121
    }
122
123
    /**
124
     * Merges your provided PDFs and get raw string
125
     *
126
     * @return string
127
     * @throws Exception If no PDFs were added
128
     * @throws Exception If a specified page does not exist
129
     */
130
    public function merge()
131
    {
132
        if (empty($this->files)) {
133
            throw new Exception("Unable to merge, no PDFs added");
134
        }
135
136
        $fname = '';
137
        try {
138
            $fpdi = clone $this->fpdi;
139
140
            foreach ($this->files as $fileData) {
141
                list($fname, $pages, $cleanup) = $fileData;
142
                $pages = $pages->getPages();
143
                $iPageCount = $fpdi->setSourceFile($fname);
144
145
                // If no pages are specified, add all pages
146
                if (empty($pages)) {
147
                    $pages = range(1, $iPageCount);
148
                }
149
150
                // Add specified pages
151
                foreach ($pages as $page) {
152
                    $template = $fpdi->importPage($page);
153
                    $size = $fpdi->getTemplateSize($template);
154
                    $orientation = ($size['w'] > $size['h']) ? 'L' : 'P';
155
                    $fpdi->AddPage($orientation, array($size['w'], $size['h']));
156
                    $fpdi->useTemplate($template);
157
                }
158
            }
159
160
            $output = $fpdi->Output('', 'S');
161
162
            $fpdi->cleanUp();
163
            foreach ($this->files as $fileData) {
164
                list($fname, $pages, $cleanup) = $fileData;
0 ignored issues
show
Unused Code introduced by
The assignment to $pages is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
165
                if ($cleanup) {
166
                    unlink($fname);
167
                }
168
            }
169
            $this->files = array();
170
171
            return $output;
172
173
        } catch (\Exception $e) {
174
            throw new Exception("FPDI: '{$e->getMessage()}' in '$fname'", 0, $e);
175
        }
176
    }
177
178
    /**
179
     * Create temporary file and return name
180
     *
181
     * @return string
182
     */
183
    public function getTempFname()
184
    {
185
        return tempnam($this->getTempDir(), "libmergepdf");
186
    }
187
188
    /**
189
     * Get directory path for temporary files
190
     *
191
     * Set path using setTempDir(), defaults to sys_get_temp_dir().
192
     *
193
     * @return string
194
     */
195
    public function getTempDir()
196
    {
197
        return $this->tempDir ?: sys_get_temp_dir();
198
    }
199
200
    /**
201
     * Set directory path for temporary files
202
     *
203
     * @param  string $dirname
204
     * @return void
205
     */
206
    public function setTempDir($dirname)
207
    {
208
        $this->tempDir = $dirname;
209
    }
210
}
211