Passed
Pull Request — master (#18)
by
unknown
13:04 queued 09:21
created

ApacheVelocity::getSyntaxName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * File containing the {@see \Mailcode\Translator\Syntax\ApacheVelocity} class.
4
 *
5
 * @package Mailcode
6
 * @subpackage Translator
7
 * @see \Mailcode\Translator\Syntax\ApacheVelocity
8
 */
9
10
declare(strict_types=1);
11
12
namespace Mailcode\Translator\Syntax;
13
14
use Mailcode\Interfaces\Commands\EncodableInterface;
15
use Mailcode\Mailcode_Commands_Command;
16
use Mailcode\Mailcode_Commands_Keywords;
17
use Mailcode\Mailcode_Number_Info;
18
use Mailcode\Mailcode_Number_LocalCurrency;
19
use Mailcode\Translator\BaseCommandTranslation;
20
use function Mailcode\dollarize;
21
22
/**
23
 * Abstract base class for apache velocity command translation classes.
24
 *
25
 * @package Mailcode
26
 * @subpackage Translator
27
 * @author Sebastian Mordziol <[email protected]>
28
 */
29
abstract class ApacheVelocity extends BaseCommandTranslation
30
{
31
    /**
32
     * @var string[]
33
     */
34
    private array $regexSpecialChars = array(
35
        '?',
36
        '.',
37
        '[',
38
        ']',
39
        '|',
40
        '{',
41
        '}',
42
        '$',
43
        '*',
44
        '^',
45
        '+',
46
        '<',
47
        '>',
48
        '(',
49
        ')'
50
    );
51
52
    public function getLabel(): string
53
    {
54
        return 'Apache Velocity';
55
    }
56
57
    /**
58
     * Filters the string for use in an Apache Velocity (Java)
59
     * regex string: escapes all special characters.
60
     *
61
     * Velocity does its own escaping, so no need to escape special
62
     * characters as if they were a javascript string.
63
     *
64
     * @param string $string
65
     * @return string
66
     */
67
    public function filterRegexString(string $string): string
68
    {
69
        // Special case: previously escaped quotes.
70
        // To avoid modifying them, we strip them out.
71
        $string = str_replace('\\"', 'ESCQUOTE', $string);
72
73
        // Any other existing backslashes in the string
74
        // have to be double-escaped, giving four
75
        // backslashes in the java regex.
76
        $string = str_replace('\\', '\\\\', $string);
77
78
        // All other special characters have to be escaped
79
        // with two backslashes.
80
        foreach ($this->regexSpecialChars as $char) {
81
            $string = str_replace($char, '\\' . $char, $string);
82
        }
83
84
        // Restore the escaped quotes, which stay escaped
85
        // with a single backslash.
86
        $string = str_replace('ESCQUOTE', '\\"', $string);
87
88
        return $string;
89
    }
90
91
    protected function renderVariableEncodings(Mailcode_Commands_Command $command, string $varName): string
92
    {
93
        if (!$command instanceof EncodableInterface || !$command->hasActiveEncodings()) {
94
            return sprintf(
95
                '${%s}',
96
                $varName
97
            );
98
        }
99
100
        return $this->renderEncodings($command, dollarize($varName));
101
    }
102
103
    public function renderNumberFormat(string $varName, Mailcode_Number_Info $numberInfo, bool $absolute): string
104
    {
105
        $varName = dollarize($varName);
106
107
        if ($absolute) {
108
            $varName = sprintf('${numeric.abs(%s)}', $varName);
109
        }
110
111
        return sprintf(
112
            "numeric.format(%s, %s, '%s', '%s')",
113
            $varName,
114
            $numberInfo->getDecimals(),
115
            $numberInfo->getDecimalsSeparator(),
116
            $numberInfo->getThousandsSeparator()
117
        );
118
    }
119
120
    public function renderStringToNumber(string $varName): string
121
    {
122
        return sprintf(
123
            '$numeric.toNumber(%s)',
124
            dollarize($varName)
125
        );
126
    }
127
128
    public function renderPrice(string $varName, Mailcode_Number_LocalCurrency $localCurrency, bool $absolute = false, bool $withCurrencyName = true): string
129
    {
130
        $varName = dollarize($varName);
131
132
        if ($absolute) {
133
            $varName = sprintf('${numeric.abs(%s)}', $varName);
134
        }
135
136
        $numberInfo = $localCurrency->getFormatInfo();
137
138
        $displayedCurrency = $withCurrencyName
139
            ? $localCurrency->getCurrencyName()
140
            : $localCurrency->getCurrencySymbol();
141
142
        return sprintf(
143
            "money.amount(%s, '%s').group('%s').unit('%s', '%s').separator('%s')",
144
            $varName,
145
            $numberInfo->getDecimalsSeparator(),
146
            $numberInfo->getThousandsSeparator(),
147
            $displayedCurrency,
148
            $localCurrency->getCountry(),
149
            $localCurrency->getUnitSeparator()
150
        );
151
    }
152
153
    public function renderQuotedValue(string $value): string
154
    {
155
        return sprintf(
156
            '"%s"',
157
            str_replace('"', '\"', $value)
158
        );
159
    }
160
161
    public function getSyntaxName(): string
162
    {
163
        return 'ApacheVelocity';
164
    }
165
166
    /**
167
     * @var array<string,string>
168
     */
169
    private array $encodingTemplates = array(
170
        Mailcode_Commands_Keywords::TYPE_URLENCODE => '${esc.url(%s)}',
171
        Mailcode_Commands_Keywords::TYPE_URLDECODE => '${esc.unurl(%s)}',
172
        Mailcode_Commands_Keywords::TYPE_IDN_ENCODE => '${text.idn(%s)}',
173
        Mailcode_Commands_Keywords::TYPE_IDN_DECODE => '${text.unidn(%s)}'
174
    );
175
176
    protected function renderEncodings(EncodableInterface $command, string $statement): string
177
    {
178
        $encodings = $command->getActiveEncodings();
179
        $result = $statement;
180
181
        foreach ($encodings as $encoding) {
182
            $result = $this->renderEncoding($encoding, $result, $command);
183
        }
184
185
        return $result;
186
    }
187
188
    protected function renderEncoding(string $keyword, string $result, EncodableInterface $command): string
0 ignored issues
show
Unused Code introduced by
The parameter $command is not used and could be removed. ( Ignorable by Annotation )

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

188
    protected function renderEncoding(string $keyword, string $result, /** @scrutinizer ignore-unused */ EncodableInterface $command): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
189
    {
190
        $template = $this->encodingTemplates[$keyword] ?? '%s';
191
192
        return sprintf($template, $result);
193
    }
194
}
195