Passed
Pull Request — master (#453)
by Konrad
01:59
created

Page::getDataCommands()   C

Complexity

Conditions 15
Paths 26

Size

Total Lines 130
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 17.3795

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 15
eloc 40
c 1
b 0
f 0
nc 26
nop 1
dl 0
loc 130
ccs 32
cts 41
cp 0.7805
crap 17.3795
rs 5.9166

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\ElementMissing;
35
use Smalot\PdfParser\Element\ElementNull;
36
use Smalot\PdfParser\Element\ElementXRef;
37
38
class Page extends PDFObject
39
{
40
    /**
41
     * @var Font[]
42
     */
43
    protected $fonts = null;
44
45
    /**
46
     * @var PDFObject[]
47
     */
48
    protected $xobjects = null;
49
50
    /**
51
     * @var array
52
     */
53
    protected $dataTm = null;
54
55
    /**
56
     * @return Font[]
57
     */
58 23
    public function getFonts()
59
    {
60 23
        if (null !== $this->fonts) {
61 19
            return $this->fonts;
62
        }
63
64 23
        $resources = $this->get('Resources');
65
66 23
        if (method_exists($resources, 'has') && $resources->has('Font')) {
67 20
            if ($resources->get('Font') instanceof ElementMissing) {
0 ignored issues
show
Bug introduced by
The method get() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

67
            if ($resources->/** @scrutinizer ignore-call */ get('Font') instanceof ElementMissing) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
68 1
                return [];
69
            }
70
71 19
            if ($resources->get('Font') instanceof Header) {
72 13
                $fonts = $resources->get('Font')->getElements();
73
            } else {
74 8
                $fonts = $resources->get('Font')->getHeader()->getElements();
75
            }
76
77 19
            $table = [];
78
79 19
            foreach ($fonts as $id => $font) {
80 19
                if ($font instanceof Font) {
81 19
                    $table[$id] = $font;
82
83
                    // Store too on cleaned id value (only numeric)
84 19
                    $id = preg_replace('/[^0-9\.\-_]/', '', $id);
85 19
                    if ('' != $id) {
86 19
                        $table[$id] = $font;
87
                    }
88
                }
89
            }
90
91 19
            return $this->fonts = $table;
92
        }
93
94 5
        return [];
95
    }
96
97 21
    public function getFont(string $id): ?Font
98
    {
99 21
        $fonts = $this->getFonts();
100
101 21
        if (isset($fonts[$id])) {
102 18
            return $fonts[$id];
103
        }
104
105
        // According to the PDF specs (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf, page 238)
106
        // "The font resource name presented to the Tf operator is arbitrary, as are the names for all kinds of resources"
107
        // Instead, we search for the unfiltered name first and then do this cleaning as a fallback, so all tests still pass.
108
109 4
        if (isset($fonts[$id])) {
110
            return $fonts[$id];
111
        } else {
112 4
            $id = preg_replace('/[^0-9\.\-_]/', '', $id);
113 4
            if (isset($fonts[$id])) {
114 1
                return $fonts[$id];
115
            }
116
        }
117
118 3
        return null;
119
    }
120
121
    /**
122
     * Support for XObject
123
     *
124
     * @return PDFObject[]
125
     */
126 4
    public function getXObjects()
127
    {
128 4
        if (null !== $this->xobjects) {
129 3
            return $this->xobjects;
130
        }
131
132 4
        $resources = $this->get('Resources');
133
134 4
        if (method_exists($resources, 'has') && $resources->has('XObject')) {
135 4
            if ($resources->get('XObject') instanceof Header) {
136 4
                $xobjects = $resources->get('XObject')->getElements();
137
            } else {
138
                $xobjects = $resources->get('XObject')->getHeader()->getElements();
139
            }
140
141 4
            $table = [];
142
143 4
            foreach ($xobjects as $id => $xobject) {
144 4
                $table[$id] = $xobject;
145
146
                // Store too on cleaned id value (only numeric)
147 4
                $id = preg_replace('/[^0-9\.\-_]/', '', $id);
148 4
                if ('' != $id) {
149 4
                    $table[$id] = $xobject;
150
                }
151
            }
152
153 4
            return $this->xobjects = $table;
154
        }
155
156
        return [];
157
    }
158
159 4
    public function getXObject(string $id): ?PDFObject
160
    {
161 4
        $xobjects = $this->getXObjects();
162
163 4
        if (isset($xobjects[$id])) {
164 4
            return $xobjects[$id];
165
        }
166
167
        return null;
168
        /*$id = preg_replace('/[^0-9\.\-_]/', '', $id);
169
170
        if (isset($xobjects[$id])) {
171
            return $xobjects[$id];
172
        } else {
173
            return null;
174
        }*/
175
    }
176
177 13
    public function getText(self $page = null): string
178
    {
179 13
        if ($contents = $this->get('Contents')) {
180 13
            if ($contents instanceof ElementMissing) {
181
                return '';
182 13
            } elseif ($contents instanceof ElementNull) {
183
                return '';
184 13
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
185 10
                $elements = $contents->getHeader()->getElements();
186
187 10
                if (is_numeric(key($elements))) {
188
                    $new_content = '';
189
190
                    foreach ($elements as $element) {
191
                        if ($element instanceof ElementXRef) {
192
                            $new_content .= $element->getObject()->getContent();
193
                        } else {
194
                            $new_content .= $element->getContent();
195
                        }
196
                    }
197
198
                    $header = new Header([], $this->document);
199 10
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
200
                }
201 3
            } elseif ($contents instanceof ElementArray) {
202
                // Create a virtual global content.
203 3
                $new_content = '';
204
205 3
                foreach ($contents->getContent() as $content) {
206 3
                    $new_content .= $content->getContent()."\n";
207
                }
208
209 3
                $header = new Header([], $this->document);
210 3
                $contents = new PDFObject($this->document, $header, $new_content, $this->config);
211
            }
212
213 13
            return $contents->getText($this);
0 ignored issues
show
Bug introduced by
The method getText() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

213
            return $contents->/** @scrutinizer ignore-call */ getText($this);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
214
        }
215
216
        return '';
217
    }
218
219 4
    public function getTextArray(self $page = null): array
220
    {
221 4
        if ($contents = $this->get('Contents')) {
222 4
            if ($contents instanceof ElementMissing) {
223
                return [];
224 4
            } elseif ($contents instanceof ElementNull) {
225
                return [];
226 4
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
227 4
                $elements = $contents->getHeader()->getElements();
228
229 4
                if (is_numeric(key($elements))) {
230
                    $new_content = '';
231
232
                    /** @var PDFObject $element */
233
                    foreach ($elements as $element) {
234
                        if ($element instanceof ElementXRef) {
235
                            $new_content .= $element->getObject()->getContent();
236
                        } else {
237
                            $new_content .= $element->getContent();
238
                        }
239
                    }
240
241
                    $header = new Header([], $this->document);
242
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
243
                }
244
                else {
245
                    try {
246 4
                        $contents->getTextArray($this);
247 1
                    } catch (\Error $e) {
248 4
                        return $contents->getTextArray();
249
                    } 
250
                }
251
            } elseif ($contents instanceof ElementArray) {
252
                // Create a virtual global content.
253
                $new_content = '';
254
255
                /** @var PDFObject $content */
256
                foreach ($contents->getContent() as $content) {
257
                    $new_content .= $content->getContent()."\n";
258
                }
259
260
                $header = new Header([], $this->document);
261
                $contents = new PDFObject($this->document, $header, $new_content, $this->config);
262
            }
263
264 3
            return $contents->getTextArray($this);
0 ignored issues
show
Bug introduced by
The method getTextArray() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

264
            return $contents->/** @scrutinizer ignore-call */ getTextArray($this);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
265
        }
266
267
        return [];
268
    }
269
270
    /**
271
     * Gets all the text data with its internal representation of the page.
272
     *
273
     * @return array An array with the data and the internal representation
274
     */
275 8
    public function extractRawData(): array
276
    {
277
        /*
278
         * Now you can get the complete content of the object with the text on it
279
         */
280 8
        $extractedData = [];
281 8
        $content = $this->get('Contents');
282 8
        $values = $content->getContent();
283 8
        if (isset($values) && \is_array($values)) {
284
            $text = '';
285
            foreach ($values as $section) {
286
                $text .= $section->getContent();
287
            }
288
            $sectionsText = $this->getSectionsText($text);
289
            foreach ($sectionsText as $sectionText) {
290
                $commandsText = $this->getCommandsText($sectionText);
291
                foreach ($commandsText as $command) {
292
                    $extractedData[] = $command;
293
                }
294
            }
295
        } else {
296 8
            $sectionsText = $content->getSectionsText($content->getContent());
0 ignored issues
show
Bug introduced by
The method getSectionsText() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

296
            /** @scrutinizer ignore-call */ 
297
            $sectionsText = $content->getSectionsText($content->getContent());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
297 8
            foreach ($sectionsText as $sectionText) {
298 8
                $extractedData[] = ['t' => '', 'o' => 'BT', 'c' => ''];
299
300 8
                $commandsText = $content->getCommandsText($sectionText);
0 ignored issues
show
Bug introduced by
The method getCommandsText() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

300
                /** @scrutinizer ignore-call */ 
301
                $commandsText = $content->getCommandsText($sectionText);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
301 8
                foreach ($commandsText as $command) {
302 8
                    $extractedData[] = $command;
303
                }
304
            }
305
        }
306
307 8
        return $extractedData;
308
    }
309
310
    /**
311
     * Gets all the decoded text data with it internal representation from a page.
312
     *
313
     * @param array $extractedRawData the extracted data return by extractRawData or
314
     *                                null if extractRawData should be called
315
     *
316
     * @return array An array with the data and the internal representation
317
     */
318 7
    public function extractDecodedRawData(array $extractedRawData = null): array
319
    {
320 7
        if (!isset($extractedRawData) || !$extractedRawData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extractedRawData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
321 7
            $extractedRawData = $this->extractRawData();
322
        }
323 7
        $currentFont = null; /** @var Font $currentFont */
324 7
        $clippedFont = null;
325 7
        foreach ($extractedRawData as &$command) {
326 7
            if ('Tj' == $command['o'] || 'TJ' == $command['o']) {
327 7
                $data = $command['c'];
328 7
                if (!\is_array($data)) {
329 5
                    $tmpText = '';
330 5
                    if (isset($currentFont)) {
331 5
                        $tmpText = $currentFont->decodeOctal($data);
332
                        //$tmpText = $currentFont->decodeHexadecimal($tmpText, false);
333
                    }
334 5
                    $tmpText = str_replace(
335 5
                            ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
336 5
                            ['\\', '(', ')', "\n", "\r", "\t", ' '],
337
                            $tmpText
338
                    );
339 5
                    $tmpText = utf8_encode($tmpText);
340 5
                    if (isset($currentFont)) {
341 5
                        $tmpText = $currentFont->decodeContent($tmpText);
342
                    }
343 5
                    $command['c'] = $tmpText;
344 5
                    continue;
345
                }
346 7
                $numText = \count($data);
347 7
                for ($i = 0; $i < $numText; ++$i) {
348 7
                    if (0 != ($i % 2)) {
349 5
                        continue;
350
                    }
351 7
                    $tmpText = $data[$i]['c'];
352 7
                    $decodedText = '';
353 7
                    if (isset($currentFont)) {
354 5
                        $decodedText = $currentFont->decodeOctal($tmpText);
355
                        //$tmpText = $currentFont->decodeHexadecimal($tmpText, false);
356
                    } else {
357 2
                        $decodedText = $tmpText;
358
                    }
359 7
                    $decodedText = str_replace(
360 7
                            ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
361 7
                            ['\\', '(', ')', "\n", "\r", "\t", ' '],
362
                            $decodedText
363
                    );
364 7
                    $decodedText = utf8_encode($decodedText);
365 7
                    if (isset($currentFont)) {
366 5
                        $decodedText = $currentFont->decodeContent($decodedText);
367
                    }
368 7
                    $command['c'][$i]['c'] = $decodedText;
369 7
                    continue;
370
                }
371 7
            } elseif ('Tf' == $command['o'] || 'TF' == $command['o']) {
372 7
                $fontId = explode(' ', $command['c'])[0];
373 7
                $currentFont = $this->getFont($fontId);
374 7
                continue;
375 7
            } elseif ('Q' == $command['o']) {
376
                $currentFont = $clippedFont;
377 7
            } elseif ('q' == $command['o']) {
378
                $clippedFont = $currentFont;
379
            }
380
        }
381
382 7
        return $extractedRawData;
383
    }
384
385
    /**
386
     * Gets just the Text commands that are involved in text positions and
387
     * Text Matrix (Tm)
388
     *
389
     * It extract just the PDF commands that are involved with text positions, and
390
     * the Text Matrix (Tm). These are: BT, ET, TL, Td, TD, Tm, T*, Tj, ', ", and TJ
391
     *
392
     * @param array $extractedDecodedRawData The data extracted by extractDecodeRawData.
393
     *                                       If it is null, the method extractDecodeRawData is called.
394
     *
395
     * @return array An array with the text command of the page
396
     */
397 5
    public function getDataCommands(array $extractedDecodedRawData = null): array
398
    {
399 5
        if (!isset($extractedDecodedRawData) || !$extractedDecodedRawData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extractedDecodedRawData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
400 5
            $extractedDecodedRawData = $this->extractDecodedRawData();
401
        }
402 5
        $extractedData = [];
403 5
        foreach ($extractedDecodedRawData as $command) {
404 5
            switch ($command['o']) {
405
                /*
406
                 * BT
407
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
408
                 */
409 5
                case 'BT':
410 5
                    $extractedData[] = $command;
411 5
                    break;
412
413
                /*
414
                 * ET
415
                 * End a text object, discarding the text matrix
416
                 */
417 5
                case 'ET':
418
                    $extractedData[] = $command;
419
                    break;
420
421
                /*
422
                 * leading TL
423
                 * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
424
                 * Initial value: 0
425
                 */
426 5
                case 'TL':
427 3
                    $extractedData[] = $command;
428 3
                    break;
429
430
                /*
431
                 * tx ty Td
432
                 * Move to the start of the next line, offset form the start of the
433
                 * current line by tx, ty.
434
                 */
435 5
                case 'Td':
436 5
                    $extractedData[] = $command;
437 5
                    break;
438
439
                /*
440
                 * tx ty TD
441
                 * Move to the start of the next line, offset form the start of the
442
                 * current line by tx, ty. As a side effect, this operator set the leading
443
                 * parameter in the text state. This operator has the same effect as the
444
                 * code:
445
                 * -ty TL
446
                 * tx ty Td
447
                 */
448 5
                case 'TD':
449
                    $extractedData[] = $command;
450
                    break;
451
452
                /*
453
                 * a b c d e f Tm
454
                 * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
455
                 * all numbers, and the initial value for Tm and Tlm is the identity matrix
456
                 * [1 0 0 1 0 0]
457
                 */
458 5
                case 'Tm':
459 3
                    $extractedData[] = $command;
460 3
                    break;
461
462
                /*
463
                 * T*
464
                 * Move to the start of the next line. This operator has the same effect
465
                 * as the code:
466
                 * 0 Tl Td
467
                 * Where Tl is the current leading parameter in the text state.
468
                 */
469 5
                case 'T*':
470 3
                    $extractedData[] = $command;
471 3
                    break;
472
473
                /*
474
                 * string Tj
475
                 * Show a Text String
476
                 */
477 5
                case 'Tj':
478 4
                    $extractedData[] = $command;
479 4
                    break;
480
481
                /*
482
                 * string '
483
                 * Move to the next line and show a text string. This operator has the
484
                 * same effect as the code:
485
                 * T*
486
                 * string Tj
487
                 */
488 5
                case "'":
489
                    $extractedData[] = $command;
490
                    break;
491
492
                /*
493
                 * aw ac string "
494
                 * Move to the next lkine and show a text string, using aw as the word
495
                 * spacing and ac as the character spacing. This operator has the same
496
                 * effect as the code:
497
                 * aw Tw
498
                 * ac Tc
499
                 * string '
500
                 * Tw set the word spacing, Tw, to wordSpace.
501
                 * Tc Set the character spacing, Tc, to charsSpace.
502
                 */
503 5
                case '"':
504
                    $extractedData[] = $command;
505
                    break;
506
507
                /*
508
                 * array TJ
509
                 * Show one or more text strings allow individual glyph positioning.
510
                 * Each lement of array con be a string or a number. If the element is
511
                 * a string, this operator shows the string. If it is a number, the
512
                 * operator adjust the text position by that amount; that is, it translates
513
                 * the text matrix, Tm. This amount is substracted form the current
514
                 * horizontal or vertical coordinate, depending on the writing mode.
515
                 * in the default coordinate system, a positive adjustment has the effect
516
                 * of moving the next glyph painted either to the left or down by the given
517
                 * amount.
518
                 */
519 5
                case 'TJ':
520 5
                    $extractedData[] = $command;
521 5
                    break;
522
                default:
523
            }
524
        }
525
526 5
        return $extractedData;
527
    }
528
529
    /**
530
     * Gets the Text Matrix of the text in the page
531
     *
532
     * Return an array where every item is an array where the first item is the
533
     * Text Matrix (Tm) and the second is a string with the text data.  The Text matrix
534
     * is an array of 6 numbers. The last 2 numbers are the coordinates X and Y of the
535
     * text. The first 4 numbers has to be with Scalation, Rotation and Skew of the text.
536
     *
537
     * @param array $dataCommands the data extracted by getDataCommands
538
     *                            if null getDataCommands is called
539
     *
540
     * @return array an array with the data of the page including the Tm information
541
     *               of any text in the page
542
     */
543 4
    public function getDataTm(array $dataCommands = null): array
544
    {
545 4
        if (!isset($dataCommands) || !$dataCommands) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $dataCommands of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
546 4
            $dataCommands = $this->getDataCommands();
547
        }
548
549
        /*
550
         * At the beginning of a text object Tm is the identity matrix
551
         */
552 4
        $defaultTm = ['1', '0', '0', '1', '0', '0'];
553
554
        /*
555
         *  Set the text leading used by T*, ' and " operators
556
         */
557 4
        $defaultTl = 0;
558
559
        /*
560
         * Setting where are the X and Y coordinates in the matrix (Tm)
561
         */
562 4
        $x = 4;
563 4
        $y = 5;
564 4
        $Tx = 0;
565 4
        $Ty = 0;
566
567 4
        $Tm = $defaultTm;
568 4
        $Tl = $defaultTl;
569
570 4
        $extractedTexts = $this->getTextArray();
571 4
        $extractedData = [];
572 4
        foreach ($dataCommands as $command) {
573 4
            $currentText = $extractedTexts[\count($extractedData)];
574 4
            switch ($command['o']) {
575
                /*
576
                 * BT
577
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
578
                 */
579 4
                case 'BT':
580 4
                    $Tm = $defaultTm;
581 4
                    $Tl = $defaultTl; //review this.
582 4
                    $Tx = 0;
583 4
                    $Ty = 0;
584 4
                    break;
585
586
                /*
587
                 * ET
588
                 * End a text object, discarding the text matrix
589
                 */
590 4
                case 'ET':
591
                    $Tm = $defaultTm;
592
                    $Tl = $defaultTl;  //review this
593
                    $Tx = 0;
594
                    $Ty = 0;
595
                    break;
596
597
                /*
598
                 * leading TL
599
                 * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
600
                 * Initial value: 0
601
                 */
602 4
                case 'TL':
603 2
                    $Tl = (float) $command['c'];
604 2
                    break;
605
606
                /*
607
                 * tx ty Td
608
                 * Move to the start of the next line, offset form the start of the
609
                 * current line by tx, ty.
610
                 */
611 4
                case 'Td':
612 4
                    $coord = explode(' ', $command['c']);
613 4
                    $Tx += (float) $coord[0];
614 4
                    $Ty += (float) $coord[1];
615 4
                    $Tm[$x] = (string) $Tx;
616 4
                    $Tm[$y] = (string) $Ty;
617 4
                    break;
618
619
                /*
620
                 * tx ty TD
621
                 * Move to the start of the next line, offset form the start of the
622
                 * current line by tx, ty. As a side effect, this operator set the leading
623
                 * parameter in the text state. This operator has the same effect as the
624
                 * code:
625
                 * -ty TL
626
                 * tx ty Td
627
                 */
628 4
                case 'TD':
629
                    $coord = explode(' ', $command['c']);
630
                    $Tl = (float) $coord[1];
631
                    $Tx += (float) $coord[0];
632
                    $Ty -= (float) $coord[1];
633
                    $Tm[$x] = (string) $Tx;
634
                    $Tm[$y] = (string) $Ty;
635
                    break;
636
637
                /*
638
                 * a b c d e f Tm
639
                 * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
640
                 * all numbers, and the initial value for Tm and Tlm is the identity matrix
641
                 * [1 0 0 1 0 0]
642
                 */
643 4
                case 'Tm':
644 2
                    $Tm = explode(' ', $command['c']);
645 2
                    $Tx = (float) $Tm[$x];
646 2
                    $Ty = (float) $Tm[$y];
647 2
                    break;
648
649
                /*
650
                 * T*
651
                 * Move to the start of the next line. This operator has the same effect
652
                 * as the code:
653
                 * 0 Tl Td
654
                 * Where Tl is the current leading parameter in the text state.
655
                 */
656 4
                case 'T*':
657 2
                    $Ty -= $Tl;
658 2
                    $Tm[$y] = (string) $Ty;
659 2
                    break;
660
661
                /*
662
                 * string Tj
663
                 * Show a Text String
664
                 */
665 4
                case 'Tj':
666 3
                    $extractedData[] = [$Tm, $currentText];
667 3
                    break;
668
669
                /*
670
                 * string '
671
                 * Move to the next line and show a text string. This operator has the
672
                 * same effect as the code:
673
                 * T*
674
                 * string Tj
675
                 */
676 4
                case "'":
677
                    $Ty -= $Tl;
678
                    $Tm[$y] = (string) $Ty;
679
                    $extractedData[] = [$Tm, $currentText];
680
                    break;
681
682
                /*
683
                 * aw ac string "
684
                 * Move to the next line and show a text string, using aw as the word
685
                 * spacing and ac as the character spacing. This operator has the same
686
                 * effect as the code:
687
                 * aw Tw
688
                 * ac Tc
689
                 * string '
690
                 * Tw set the word spacing, Tw, to wordSpace.
691
                 * Tc Set the character spacing, Tc, to charsSpace.
692
                 */
693 4
                case '"':
694
                    $data = explode(' ', $currentText);
695
                    $Ty -= $Tl;
696
                    $Tm[$y] = (string) $Ty;
697
                    $extractedData[] = [$Tm, $data[2]]; //Verify
698
                    break;
699
700
                /*
701
                 * array TJ
702
                 * Show one or more text strings allow individual glyph positioning.
703
                 * Each lement of array con be a string or a number. If the element is
704
                 * a string, this operator shows the string. If it is a number, the
705
                 * operator adjust the text position by that amount; that is, it translates
706
                 * the text matrix, Tm. This amount is substracted form the current
707
                 * horizontal or vertical coordinate, depending on the writing mode.
708
                 * in the default coordinate system, a positive adjustment has the effect
709
                 * of moving the next glyph painted either to the left or down by the given
710
                 * amount.
711
                 */
712 4
                case 'TJ':
713 4
                    $extractedData[] = [$Tm, $currentText];
714 4
                    break;
715
                default:
716
            }
717
        }
718 4
        $this->dataTm = $extractedData;
719
720 4
        return $extractedData;
721
    }
722
723
    /**
724
     * Gets text data that are around the given coordinates (X,Y)
725
     *
726
     * If the text is in near the given coordinates (X,Y) (or the TM info),
727
     * the text is returned.  The extractedData return by getDataTm, could be use to see
728
     * where is the coordinates of a given text, using the TM info for it.
729
     *
730
     * @param float $x      The X value of the coordinate to search for. if null
731
     *                      just the Y value is considered (same Row)
732
     * @param float $y      The Y value of the coordinate to search for
733
     *                      just the X value is considered (same column)
734
     * @param float $xError The value less or more to consider an X to be "near"
735
     * @param float $yError The value less or more to consider an Y to be "near"
736
     *
737
     * @return array An array of text that are near the given coordinates. If no text
738
     *               "near" the x,y coordinate, an empty array is returned. If Both, x
739
     *               and y coordinates are null, null is returned.
740
     */
741 1
    public function getTextXY(float $x = null, float $y = null, float $xError = 0, float $yError = 0): array
742
    {
743 1
        if (!isset($this->dataTm) || !$this->dataTm) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->dataTm of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
744 1
            $this->getDataTm();
745
        }
746
747 1
        if (null !== $x) {
748 1
            $x = (float) $x;
749
        }
750
751 1
        if (null !== $y) {
752 1
            $y = (float) $y;
753
        }
754
755 1
        if (null === $x && null === $y) {
756
            return [];
757
        }
758
759 1
        $xError = (float) $xError;
760 1
        $yError = (float) $yError;
761
762 1
        $extractedData = [];
763 1
        foreach ($this->dataTm as $item) {
764 1
            $tm = $item[0];
765 1
            $xTm = (float) $tm[4];
766 1
            $yTm = (float) $tm[5];
767 1
            $text = $item[1];
768 1
            if (null === $y) {
769
                if (($xTm >= ($x - $xError)) &&
770
                    ($xTm <= ($x + $xError))) {
771
                    $extractedData[] = [$tm, $text];
772
                    continue;
773
                }
774
            }
775 1
            if (null === $x) {
776
                if (($yTm >= ($y - $yError)) &&
777
                    ($yTm <= ($y + $yError))) {
778
                    $extractedData[] = [$tm, $text];
779
                    continue;
780
                }
781
            }
782 1
            if (($xTm >= ($x - $xError)) &&
783 1
                ($xTm <= ($x + $xError)) &&
784 1
                ($yTm >= ($y - $yError)) &&
785 1
                ($yTm <= ($y + $yError))) {
786 1
                $extractedData[] = [$tm, $text];
787 1
                continue;
788
            }
789
        }
790
791 1
        return $extractedData;
792
    }
793
}
794