Test Failed
Pull Request — master (#611)
by
unknown
02:09
created

Document::buildDetails()   B

Complexity

Conditions 10
Paths 63

Size

Total Lines 64
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 10

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 10
eloc 29
nc 63
nop 0
dl 0
loc 64
ccs 26
cts 26
cp 1
crap 10
rs 7.6666
c 1
b 1
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @file
5
 *          This file is part of the PdfParser library.
6
 *
7
 * @author  Sébastien MALOT <[email protected]>
8
 *
9
 * @date    2017-01-03
10
 *
11
 * @license LGPLv3
12
 *
13
 * @url     <https://github.com/smalot/pdfparser>
14
 *
15
 *  PdfParser is a pdf library written in PHP, extraction oriented.
16
 *  Copyright (C) 2017 - Sébastien MALOT <[email protected]>
17
 *
18
 *  This program is free software: you can redistribute it and/or modify
19
 *  it under the terms of the GNU Lesser General Public License as published by
20
 *  the Free Software Foundation, either version 3 of the License, or
21
 *  (at your option) any later version.
22
 *
23
 *  This program is distributed in the hope that it will be useful,
24
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26
 *  GNU Lesser General Public License for more details.
27
 *
28
 *  You should have received a copy of the GNU Lesser General Public License
29
 *  along with this program.
30
 *  If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
31
 */
32
33
namespace Smalot\PdfParser;
34
35
use Smalot\PdfParser\Encoding\PDFDocEncoding;
36
37
/**
38
 * Technical references :
39
 * - http://www.mactech.com/articles/mactech/Vol.15/15.09/PDFIntro/index.html
40
 * - http://framework.zend.com/issues/secure/attachment/12512/Pdf.php
41
 * - http://www.php.net/manual/en/ref.pdf.php#74211
42
 * - http://cpansearch.perl.org/src/JV/PostScript-Font-1.10.02/lib/PostScript/ISOLatin1Encoding.pm
43
 * - http://cpansearch.perl.org/src/JV/PostScript-Font-1.10.02/lib/PostScript/ISOLatin9Encoding.pm
44
 * - http://cpansearch.perl.org/src/JV/PostScript-Font-1.10.02/lib/PostScript/StandardEncoding.pm
45
 * - http://cpansearch.perl.org/src/JV/PostScript-Font-1.10.02/lib/PostScript/WinAnsiEncoding.pm
46
 *
47
 * Class Document
48
 */
49
class Document
50
{
51
    /**
52
     * @var PDFObject[]
53
     */
54
    protected $objects = [];
55
56
    /**
57
     * @var array
58
     */
59
    protected $dictionary = [];
60
61
    /**
62
     * @var Header
63
     */
64
    protected $trailer;
65
66
    /**
67
     * @var array<mixed>
68
     */
69 72
    protected $metadata = [];
70
71 72
    /**
72 72
     * @var array
73
     */
74 49
    protected $details;
75
76 49
    public function __construct()
77
    {
78 49
        $this->trailer = new Header([], $this);
79
    }
80
81 49
    public function init()
82 49
    {
83 49
        $this->buildDictionary();
84
85 49
        $this->buildDetails();
86
87
        // Propagate init to objects.
88
        foreach ($this->objects as $object) {
89
            $object->getHeader()->init();
90 49
            $object->init();
91
        }
92
    }
93 49
94
    /**
95 49
     * Build dictionary based on type header field.
96
     */
97 49
    protected function buildDictionary()
98
    {
99 49
        // Build dictionary.
100 49
        $this->dictionary = [];
101 49
102
        foreach ($this->objects as $id => $object) {
103
            // Cache objects by type and subtype
104
            $type = $object->getHeader()->get('Type')->getContent();
105
106
            if (null != $type) {
107 49
                if (!isset($this->dictionary[$type])) {
108
                    $this->dictionary[$type] = [
109 49
                        'all' => [],
110 49
                        'subtype' => [],
111 42
                    ];
112 42
                }
113
114 42
                $this->dictionary[$type]['all'][$id] = $object;
115
116
                $subtype = $object->getHeader()->get('Subtype')->getContent();
117
                if (null != $subtype) {
118 49
                    if (!isset($this->dictionary[$type]['subtype'][$subtype])) {
119
                        $this->dictionary[$type]['subtype'][$subtype] = [];
120
                    }
121
                    $this->dictionary[$type]['subtype'][$subtype][$id] = $object;
122
                }
123 49
            }
124
        }
125
    }
126 49
127
    /**
128
     * Build details array.
129 49
     */
130
    protected function buildDetails()
131 40
    {
132
        // Build details array.
133
        $details = [];
134 40
135 40
        // Extract document info
136
        if ($this->trailer->has('Info')) {
137
            /** @var PDFObject $info */
138
            $info = $this->trailer->get('Info');
139
            // This could be an ElementMissing object, so we need to check for
140
            // the getHeader method first.
141 49
            if (null !== $info && method_exists($info, 'getHeader')) {
142 48
                $details = $info->getHeader()->getDetails();
143 2
            }
144 2
        }
145
146
        // Retrieve the page count
147 49
        try {
148 49
            $pages = $this->getPages();
149
            $details['Pages'] = \count($pages);
150 1
        } catch (\Exception $e) {
151
            $details['Pages'] = 0;
152 1
        }
153
154
        // Decode and repair encoded document properties
155
        foreach ($details as $key => $value) {
156
            if (\is_string($value)) {
157
158 49
                // If the string is already UTF-8 encoded, that means we only
159
                // need to repair Adobe's ham-fisted insertion of line-feeds
160 49
                // every ~127 characters, which doesn't seem to be multi-byte
161
                // safe
162 49
                if (mb_check_encoding($value, 'UTF-8')) {
163 49
164
                    $value = str_replace("\x5c\x0d", '', $value);
165
166
                    while (preg_match("/\x5c\x5c\xe0([\xb4-\xb8])(.)/", $value, $match)) {
167
                        $diff = (\ord($match[1]) - 182) * 64;
168 1
                        $newbyte = PDFDocEncoding::convertPDFDoc2UTF8(\chr(\ord($match[2]) + $diff));
169
                        $value = preg_replace("/\x5c\x5c\xe0".$match[1].$match[2]."/", $newbyte, $value);
170 1
                    }
171
172
                    while (preg_match("/(.)\x9c\xe0([\xb3-\xb7])/", $value, $match)) {
173
                        $diff = \ord($match[2]) - 181;
174
                        $newbyte = \chr(\ord($match[1]) + $diff);
175
                        $value = preg_replace("/".$match[1]."\x9c\xe0".$match[2]."/", $newbyte, $value);
176 46
                    }
177
178 46
                    $value = str_replace("\xe5\xb0\x8d", '', $value);
179 46
180
                    $details[$key] = $value;
181
182 3
                // If the string is just PDFDocEncoding, remove any line-feeds
183
                // and decode the whole thing.
184
                } else {
185 50
                    $value = str_replace("\\\r", '', $value);
186
                    $details[$key] = PDFDocEncoding::convertPDFDoc2UTF8($value);
187 50
                }
188
            }
189
        }
190 53
191
        $details = array_merge($details, $this->metadata);
192 53
193 12
        $this->details = $details;
194
    }
195
196 48
    /**
197
     * Extract XMP Metadata
198
     */
199
    public function extractXMPMetadata(string $content): void
200
    {
201
        $xml = xml_parser_create();
202
        xml_parser_set_option($xml, \XML_OPTION_SKIP_WHITE, 1);
203
204 48
        if (1 === xml_parse_into_struct($xml, $content, $values, $index)) {
205
            /*
206
             * short overview about the following code parts:
207
             *
208
             * The output of xml_parse_into_struct is a single dimensional array (= $values), and the $stack is a last-on,
209
             * first-off array of pointers to positions in $metadata, while iterating through it, that potentially turn the
210 27
             * results into a more intuitive multi-dimensional array. When an "open" XML tag is encountered,
211
             * we save the current $metadata context in the $stack, then create a child array of $metadata and
212 27
             * make that the current $metadata context. When a "close" XML tag is encountered, the operations are
213
             * reversed: the most recently added $metadata context from $stack (IOW, the parent of the current
214
             * element) is set as the current $metadata context.
215 21
             */
216
            $metadata = [];
217 21
            $stack = [];
218 21
            foreach ($values as $val) {
219 3
                // Standardize to lowercase
220
                $val['tag'] = strtolower($val['tag']);
221
222 18
                // Ignore structural x: and rdf: XML elements
223
                if (0 === strpos($val['tag'], 'x:')) {
224
                    continue;
225
                } elseif (0 === strpos($val['tag'], 'rdf:') && 'rdf:li' != $val['tag']) {
226
                    continue;
227
                }
228
229
                switch ($val['type']) {
230 50
                    case 'open':
231
                        // Create an array of list items
232 50
                        if ('rdf:li' == $val['tag']) {
233
                            $metadata[] = [];
234 42
235 42
                            // Move up one level in the stack
236
                            $stack[\count($stack)] = &$metadata;
237
                            $metadata = &$metadata[\count($metadata) - 1];
238 42
                        } else {
239 42
                            // Else create an array of named values
240 42
                            $metadata[$val['tag']] = [];
241
242
                            // Move up one level in the stack
243
                            $stack[\count($stack)] = &$metadata;
244 9
                            $metadata = &$metadata[$val['tag']];
245
                        }
246 1
                        break;
247
248
                    case 'complete':
249 1
                        if (isset($val['value'])) {
250 1
                            // Assign a value to this list item
251 1
                            if ('rdf:li' == $val['tag']) {
252
                                $metadata[] = $val['value'];
253
254 1
                                // Else assign a value to this property
255
                            } else {
256
                                $metadata[$val['tag']] = $val['value'];
257 9
                            }
258
                        }
259 7
                        break;
260
261 7
                    case 'close':
262
                        // If the value of this property is a single-
263
                        // element array where the element is of type
264 3
                        // string, use the value of the first list item
265
                        // as the value for this property
266
                        if (\is_array($metadata) && isset($metadata[0]) && 1 == \count($metadata) && \is_string($metadata[0])) {
267 12
                            $metadata = $metadata[0];
268
                        }
269 12
270 12
                        // Move down one level in the stack
271
                        $metadata = &$stack[\count($stack) - 1];
272
                        unset($stack[\count($stack) - 1]);
273 12
                        break;
274 1
                }
275
            }
276
277 12
            // Only use this metadata if it's referring to a PDF
278
            if (isset($metadata['dc:format']) && 'application/pdf' == $metadata['dc:format']) {
279
                // According to the XMP specifications: 'Conflict resolution
280
                // for separate packets that describe the same resource is
281 12
                // beyond the scope of this document.' - Section 6.1
282
                // Source: https://www.adobe.com/devnet/xmp.html
283
                // Source: https://github.com/adobe/XMP-Toolkit-SDK/blob/main/docs/XMPSpecificationPart1.pdf
284 12
                // So if there are multiple XMP blocks, just merge the values
285 12
                // of each found block over top of the existing values
286
                $this->metadata = array_merge($this->metadata, $metadata);
287
            }
288
        }
289 12
        xml_parser_free($xml);
290
    }
291
292
    public function getDictionary(): array
293
    {
294
        return $this->dictionary;
295
    }
296
297 41
    /**
298
     * @param PDFObject[] $objects
299 41
     */
300 41
    public function setObjects($objects = [])
301
    {
302 12
        $this->objects = (array) $objects;
303
304 12
        $this->init();
305
    }
306
307
    /**
308
     * @return PDFObject[]
309
     */
310
    public function getObjects()
311
    {
312
        return $this->objects;
313
    }
314
315
    /**
316
     * @return PDFObject|Font|Page|Element|null
317
     */
318
    public function getObjectById(string $id)
319
    {
320
        if (isset($this->objects[$id])) {
321
            return $this->objects[$id];
322
        }
323
324
        return null;
325
    }
326
327
    public function hasObjectsByType(string $type, string $subtype = null): bool
328
    {
329
        return 0 < \count($this->getObjectsByType($type, $subtype));
330
    }
331
332
    public function getObjectsByType(string $type, string $subtype = null): array
333
    {
334
        if (!isset($this->dictionary[$type])) {
335
            return [];
336
        }
337
338
        if (null != $subtype) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $subtype of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
339
            if (!isset($this->dictionary[$type]['subtype'][$subtype])) {
340
                return [];
341
            }
342
343
            return $this->dictionary[$type]['subtype'][$subtype];
344
        }
345
346
        return $this->dictionary[$type]['all'];
347
    }
348
349
    /**
350
     * @return Font[]
351
     */
352
    public function getFonts()
353
    {
354
        return $this->getObjectsByType('Font');
355
    }
356
357
    public function getFirstFont(): ?Font
358
    {
359
        $fonts = $this->getFonts();
360
        if ([] === $fonts) {
361
            return null;
362
        }
363
364
        return reset($fonts);
365
    }
366
367
    /**
368
     * @return Page[]
369
     *
370
     * @throws \Exception
371
     */
372
    public function getPages()
373
    {
374
        if ($this->hasObjectsByType('Catalog')) {
375
            // Search for catalog to list pages.
376
            $catalogues = $this->getObjectsByType('Catalog');
377
            $catalogue = reset($catalogues);
378
379
            /** @var Pages $object */
380
            $object = $catalogue->get('Pages');
381
            if (method_exists($object, 'getPages')) {
382
                return $object->getPages(true);
383
            }
384
        }
385
386
        if ($this->hasObjectsByType('Pages')) {
387
            // Search for pages to list kids.
388
            $pages = [];
389
390
            /** @var Pages[] $objects */
391
            $objects = $this->getObjectsByType('Pages');
392
            foreach ($objects as $object) {
393
                $pages = array_merge($pages, $object->getPages(true));
394
            }
395
396
            return $pages;
397
        }
398
399
        if ($this->hasObjectsByType('Page')) {
400
            // Search for 'page' (unordered pages).
401
            $pages = $this->getObjectsByType('Page');
402
403
            return array_values($pages);
404
        }
405
406
        throw new \Exception('Missing catalog.');
407
    }
408
409
    public function getText(int $pageLimit = null): string
410
    {
411
        $texts = [];
412
        $pages = $this->getPages();
413
414
        // Only use the first X number of pages if $pageLimit is set and numeric.
415
        if (\is_int($pageLimit) && 0 < $pageLimit) {
416
            $pages = \array_slice($pages, 0, $pageLimit);
417
        }
418
419
        foreach ($pages as $index => $page) {
420
            /**
421
             * In some cases, the $page variable may be null.
422
             */
423
            if (null === $page) {
424
                continue;
425
            }
426
            if ($text = trim($page->getText())) {
427
                $texts[] = $text;
428
            }
429
        }
430
431
        return implode("\n\n", $texts);
432
    }
433
434
    public function getTrailer(): Header
435
    {
436
        return $this->trailer;
437
    }
438
439
    public function setTrailer(Header $trailer)
440
    {
441
        $this->trailer = $trailer;
442
    }
443
444
    public function getDetails(): array
445
    {
446
        return $this->details;
447
    }
448
}
449