Passed
Pull Request — master (#312)
by
unknown
02:14
created

Parser::parseHeaderElement()   D

Complexity

Conditions 18
Paths 17

Size

Total Lines 54
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 18.2039

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 18
eloc 35
c 3
b 1
f 0
nc 17
nop 3
dl 0
loc 54
ccs 32
cts 35
cp 0.9143
crap 18.2039
rs 4.8666

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
 * @date    2017-01-03
9
 *
10
 * @license LGPLv3
11
 * @url     <https://github.com/smalot/pdfparser>
12
 *
13
 *  PdfParser is a pdf library written in PHP, extraction oriented.
14
 *  Copyright (C) 2017 - Sébastien MALOT <[email protected]>
15
 *
16
 *  This program is free software: you can redistribute it and/or modify
17
 *  it under the terms of the GNU Lesser General Public License as published by
18
 *  the Free Software Foundation, either version 3 of the License, or
19
 *  (at your option) any later version.
20
 *
21
 *  This program is distributed in the hope that it will be useful,
22
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 *  GNU Lesser General Public License for more details.
25
 *
26
 *  You should have received a copy of the GNU Lesser General Public License
27
 *  along with this program.
28
 *  If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
29
 */
30
31
namespace Smalot\PdfParser;
32
33
use Smalot\PdfParser\Element\ElementArray;
34
use Smalot\PdfParser\Element\ElementBoolean;
35
use Smalot\PdfParser\Element\ElementDate;
36
use Smalot\PdfParser\Element\ElementHexa;
37
use Smalot\PdfParser\Element\ElementName;
38
use Smalot\PdfParser\Element\ElementNull;
39
use Smalot\PdfParser\Element\ElementNumeric;
40
use Smalot\PdfParser\Element\ElementString;
41
use Smalot\PdfParser\Element\ElementXRef;
42
use Smalot\PdfParser\RawData\RawDataParser;
43
44
/**
45
 * Class Parser
46
 */
47
class Parser
48
{
49
    /**
50
     * @var PDFObject[]
51
     */
52
    protected $objects = [];
53
54
    protected $rawDataParser;
55
56 17
    public function __construct($cfg = [])
57
    {
58 17
        $this->rawDataParser = new RawDataParser($cfg);
59 17
    }
60
61
    /**
62
     * @param string $filename
63
     *
64
     * @return Document
65
     *
66
     * @throws \Exception
67
     */
68 17
    public function parseFile($filename)
69
    {
70 17
        $content = file_get_contents($filename);
71
        /*
72
         * 2018/06/20 @doganoo as multiple times a
73
         * users have complained that the parseFile()
74
         * method dies silently, it is an better option
75
         * to remove the error control operator (@) and
76
         * let the users know that the method throws an exception
77
         * by adding @throws tag to PHPDoc.
78
         *
79
         * See here for an example: https://github.com/smalot/pdfparser/issues/204
80
         */
81 17
        return $this->parseContent($content);
82
    }
83
84
    /**
85
     * @param string $content PDF content to parse
86
     *
87
     * @return Document
88
     *
89
     * @throws \Exception if secured PDF file was detected
90
     * @throws \Exception if no object list was found
91
     */
92 17
    public function parseContent($content)
93
    {
94
        // Create structure from raw data.
95 17
        list($xref, $data) = $this->rawDataParser->parseData($content);
96
97 17
        if (isset($xref['trailer']['encrypt'])) {
98
            throw new \Exception('Secured pdf file are currently not supported.');
99
        }
100
101 17
        if (empty($data)) {
102
            throw new \Exception('Object list not found. Possible secured file.');
103
        }
104
105
        // Create destination object.
106 17
        $document = new Document();
107 17
        $this->objects = [];
108
109 17
        foreach ($data as $id => $structure) {
110 17
            $this->parseObject($id, $structure, $document);
111 17
            unset($data[$id]);
112
        }
113
114 17
        $document->setTrailer($this->parseTrailer($xref['trailer'], $document));
115 17
        $document->setObjects($this->objects);
116
117 17
        return $document;
118
    }
119
120 17
    protected function parseTrailer($structure, $document)
121
    {
122 17
        $trailer = [];
123
124 17
        foreach ($structure as $name => $values) {
125 17
            $name = ucfirst($name);
126
127 17
            if (is_numeric($values)) {
128 17
                $trailer[$name] = new ElementNumeric($values);
129 17
            } elseif (\is_array($values)) {
130 16
                $value = $this->parseTrailer($values, null);
131 16
                $trailer[$name] = new ElementArray($value, null);
0 ignored issues
show
Bug introduced by
$value of type Smalot\PdfParser\Header is incompatible with the type string expected by parameter $value of Smalot\PdfParser\Element...entArray::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

131
                $trailer[$name] = new ElementArray(/** @scrutinizer ignore-type */ $value, null);
Loading history...
132 17
            } elseif (false !== strpos($values, '_')) {
133 17
                $trailer[$name] = new ElementXRef($values, $document);
134
            } else {
135 16
                $trailer[$name] = $this->parseHeaderElement('(', $values, $document);
136
            }
137
        }
138
139 17
        return new Header($trailer, $document);
140
    }
141
142
    /**
143
     * @param string   $id
144
     * @param array    $structure
145
     * @param Document $document
146
     */
147 17
    protected function parseObject($id, $structure, $document)
148
    {
149 17
        $header = new Header([], $document);
150 17
        $content = '';
151
152 17
        foreach ($structure as $position => $part) {
153 17
            if (\is_int($part)) {
154
                $part = [null, null];
155
            }
156 17
            switch ($part[0]) {
157 17
                case '[':
158 4
                    $elements = [];
159
160 4
                    foreach ($part[1] as $sub_element) {
0 ignored issues
show
Bug introduced by
The expression $part[1] of type null is not traversable.
Loading history...
161 4
                        $sub_type = $sub_element[0];
162 4
                        $sub_value = $sub_element[1];
163 4
                        $elements[] = $this->parseHeaderElement($sub_type, $sub_value, $document);
164
                    }
165
166 4
                    $header = new Header($elements, $document);
0 ignored issues
show
Bug introduced by
It seems like $elements can also be of type Smalot\PdfParser\Header[]; however, parameter $elements of Smalot\PdfParser\Header::__construct() does only seem to accept Smalot\PdfParser\Element[], maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

166
                    $header = new Header(/** @scrutinizer ignore-type */ $elements, $document);
Loading history...
167 4
                    break;
168
169 17
                case '<<':
170 17
                    $header = $this->parseHeader($part[1], $document);
171 17
                    break;
172
173 17
                case 'stream':
174 17
                    $content = isset($part[3][0]) ? $part[3][0] : $part[1];
175
176 17
                    if ($header->get('Type')->equals('ObjStm')) {
177 2
                        $match = [];
178
179
                        // Split xrefs and contents.
180 2
                        preg_match('/^((\d+\s+\d+\s*)*)(.*)$/s', $content, $match);
181 2
                        $content = $match[3];
182
183
                        // Extract xrefs.
184 2
                        $xrefs = preg_split(
185 2
                            '/(\d+\s+\d+\s*)/s',
186 2
                            $match[1],
187 2
                            -1,
188 2
                          PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
189
                        );
190 2
                        $table = [];
191
192 2
                        foreach ($xrefs as $xref) {
193 2
                            list($id, $position) = explode(' ', trim($xref));
194 2
                            $table[$position] = $id;
195
                        }
196
197 2
                        ksort($table);
198
199 2
                        $ids = array_values($table);
200 2
                        $positions = array_keys($table);
201
202 2
                        foreach ($positions as $index => $position) {
0 ignored issues
show
Comprehensibility Bug introduced by
$position is overwriting a variable from outer foreach loop.
Loading history...
203 2
                            $id = $ids[$index].'_0';
204 2
                            $next_position = isset($positions[$index + 1]) ? $positions[$index + 1] : \strlen($content);
205 2
                            $sub_content = substr($content, $position, (int) $next_position - (int) $position);
206
207 2
                            $sub_header = Header::parse($sub_content, $document);
208 2
                            $object = PDFObject::factory($document, $sub_header, '');
209 2
                            $this->objects[$id] = $object;
210
                        }
211
212
                        // It is not necessary to store this content.
213 2
                        $content = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $content is dead and can be removed.
Loading history...
214
215 2
                        return;
216
                    }
217 17
                    break;
218
219
                default:
220 17
                    if ('null' != $part) {
221 17
                        $element = $this->parseHeaderElement($part[0], $part[1], $document);
222
223 17
                        if ($element) {
224 16
                            $header = new Header([$element], $document);
0 ignored issues
show
Bug introduced by
array($element) of type array<integer,Smalot\PdfParser\Header> is incompatible with the type Smalot\PdfParser\Element[] expected by parameter $elements of Smalot\PdfParser\Header::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

224
                            $header = new Header(/** @scrutinizer ignore-type */ [$element], $document);
Loading history...
225
                        }
226
                    }
227 17
                    break;
228
            }
229
        }
230
231 17
        if (!isset($this->objects[$id])) {
232 17
            $this->objects[$id] = PDFObject::factory($document, $header, $content);
233
        }
234 17
    }
235
236
    /**
237
     * @param array    $structure
238
     * @param Document $document
239
     *
240
     * @return Header
241
     *
242
     * @throws \Exception
243
     */
244 17
    protected function parseHeader($structure, $document)
245
    {
246 17
        $elements = [];
247 17
        $count = \count($structure);
248
249 17
        for ($position = 0; $position < $count; $position += 2) {
250 17
            $name = $structure[$position][1];
251 17
            $type = $structure[$position + 1][0];
252 17
            $value = $structure[$position + 1][1];
253
254 17
            $elements[$name] = $this->parseHeaderElement($type, $value, $document);
255
        }
256
257 17
        return new Header($elements, $document);
258
    }
259
260
    /**
261
     * @param string       $type
262
     * @param string|array $value
263
     * @param Document     $document
264
     *
265
     * @return Element|Header|null
266
     *
267
     * @throws \Exception
268
     */
269 17
    protected function parseHeaderElement($type, $value, $document)
270
    {
271 17
        switch ($type) {
272 17
            case '<<':
273 17
            case '>>':
274 17
                return $this->parseHeader($value, $document);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type string; however, parameter $structure of Smalot\PdfParser\Parser::parseHeader() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

274
                return $this->parseHeader(/** @scrutinizer ignore-type */ $value, $document);
Loading history...
275
276 17
            case 'numeric':
277 17
                return new ElementNumeric($value);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type array; however, parameter $value of Smalot\PdfParser\Element...tNumeric::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

277
                return new ElementNumeric(/** @scrutinizer ignore-type */ $value);
Loading history...
278
279 17
            case 'boolean':
280 4
                return new ElementBoolean($value);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type array; however, parameter $value of Smalot\PdfParser\Element...tBoolean::__construct() does only seem to accept boolean|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

280
                return new ElementBoolean(/** @scrutinizer ignore-type */ $value);
Loading history...
281
282 17
            case 'null':
283 2
                return new ElementNull();
284
285 17
            case '(':
286 17
                if ($date = ElementDate::parse('('.$value.')', $document)) {
0 ignored issues
show
Bug introduced by
Are you sure $value of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

286
                if ($date = ElementDate::parse('('./** @scrutinizer ignore-type */ $value.')', $document)) {
Loading history...
287 16
                    return $date;
288
                }
289
290 17
                return ElementString::parse('('.$value.')', $document);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Smalot\PdfParser\...value . ')', $document) could also return false which is incompatible with the documented return type Smalot\PdfParser\Element...t\PdfParser\Header|null. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
291
292 17
            case '<':
293 4
                return $this->parseHeaderElement('(', ElementHexa::decode($value, $document), $document);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type array; however, parameter $value of Smalot\PdfParser\Element\ElementHexa::decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

293
                return $this->parseHeaderElement('(', ElementHexa::decode(/** @scrutinizer ignore-type */ $value, $document), $document);
Loading history...
294
295 17
            case '/':
296 17
                return ElementName::parse('/'.$value, $document);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Smalot\PdfParser\.../' . $value, $document) could also return false which is incompatible with the documented return type Smalot\PdfParser\Element...t\PdfParser\Header|null. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
297
298 17
            case 'ojbref': // old mistake in tcpdf parser
299 17
            case 'objref':
300 17
                return new ElementXRef($value, $document);
301
302 17
            case '[':
303 17
                $values = [];
304
305 17
                if (\is_array($value)) {
306 17
                    foreach ($value as $sub_element) {
307 17
                        $sub_type = $sub_element[0];
308 17
                        $sub_value = $sub_element[1];
309 17
                        $values[] = $this->parseHeaderElement($sub_type, $sub_value, $document);
310
                    }
311
                }
312
313 17
                return new ElementArray($values, $document);
0 ignored issues
show
Bug introduced by
$values of type Smalot\PdfParser\Header[]|array is incompatible with the type string expected by parameter $value of Smalot\PdfParser\Element...entArray::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

313
                return new ElementArray(/** @scrutinizer ignore-type */ $values, $document);
Loading history...
314
315 17
            case 'endstream':
316
            case 'obj': //I don't know what it means but got my project fixed.
317
            case '':
318
                // Nothing to do with.
319 17
                return null;
320
321
            default:
322
                throw new \Exception('Invalid type: "'.$type.'".');
323
        }
324
    }
325
}
326