Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
AsciiHexFilter
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 encode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 decode
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Phpdftk\Filters;
6
7/**
8 * ASCIIHexDecode — hex encoding for binary data (ISO 32000-2 §7.4.2).
9 *
10 * Simplest PDF filter: each byte becomes two hex digits. Doubles the
11 * size but produces fully human-readable output, useful for debugging.
12 * Terminated by '>'.
13 */
14final class AsciiHexFilter implements FilterInterface
15{
16    public function encode(string $data): string
17    {
18        return bin2hex($data) . '>';
19    }
20
21    public function decode(string $data): string
22    {
23        // Strip whitespace
24        $data = preg_replace('/\s+/', '', $data);
25        // Strip trailing >
26        $data = rtrim($data, '>');
27        if (!ctype_xdigit($data) && $data !== '') {
28            throw new \RuntimeException('AsciiHexFilter: invalid hex data');
29        }
30        // If odd number of hex chars, pad with trailing zero
31        if (strlen($data) % 2 !== 0) {
32            $data .= '0';
33        }
34        return hex2bin($data);
35    }
36}