SprintfToPH   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 57
ccs 15
cts 15
cp 1
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 25 2
A __construct() 0 2 1
1
<?php
2
3
4
namespace Matecat\SubFiltering\Filters;
5
6
7
use Matecat\SubFiltering\Commons\AbstractHandler;
8
use Matecat\SubFiltering\Enum\CTypeEnum;
9
use Matecat\SubFiltering\Filters\Sprintf\SprintfLocker;
10
11
class SprintfToPH extends AbstractHandler {
12
13 98
    public function __construct() {
14 98
        parent::__construct();
15
    }
16
17
    /**
18
     * TestSet:
19
     * <code>
20
     * |%-4d|%-4d|
21
     * |%':4d|
22
     * |%-':4d|
23
     * |%-'04d|
24
     * %02.2f
25
     * %02d
26
     * %1$s!
27
     * %08b
28
     * 20%-os - ignored
29
     * 20%-dir - ignored
30
     * 20%-zar - ignored
31
     *</code>
32
     *
33
     * @param $segment
34
     *
35
     * @return string
36
     * @see
37
     * - https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
38
     * - https://en.cppreference.com/w/c/io/fprintf
39
     * - https://www.php.net/manual/en/function.sprintf.php
40
     * - https://www.w3resource.com/c-programming/stdio/c_library_method_sprintf.php
41
     *
42
     */
43 88
    public function transform( string $segment ): string {
44
45 88
        $sprintfLocker = new SprintfLocker( $this->pipeline->getSource(), $this->pipeline->getTarget() );
46
47
        // placeholding
48 88
        $segment = $sprintfLocker->lock( $segment );
49
50
        // Octal parsing is disabled due to Hungarian percentages 20%-os
51 88
        $regex = '/(?:\x25\x25)|(\x25(?:(?:[1-9]\d*)\$|\((?:[^\)]+)\))?(?:\+)?(?:0|[+-]?\'[^$])?(?:-)?(?:\d+)?(?:\.(?:\d+))?((?:[hjlqtzL]{0,2}[ac-giopsuxAC-GOSUX]{1})(?![\d\w])|(?:#@[\w]+@)|(?:@)))/';
52
53
54 88
        preg_match_all( $regex, $segment, $vars, PREG_SET_ORDER );
55 88
        foreach ( $vars as $variable ) {
56
57
            //replace subsequent elements excluding already encoded
58 4
            $segment = preg_replace(
59 4
                    '/' . preg_quote( $variable[ 0 ], '/' ) . '/',
60 4
                    '<ph id="' . $this->getPipeline()->getNextId() . '" ctype="' . CTypeEnum::SPRINTF . '" equiv-text="base64:' . base64_encode( $variable[ 0 ] ) . '"/>',
61 4
                    $segment,
62 4
                    1
63 4
            );
64
        }
65
66
        //revert placeholding
67 88
        return $sprintfLocker->unlock( $segment );
68
    }
69
70
}