Passed
Pull Request — master (#16)
by Sebastian
10:17
created

Mailcode_Translator_Syntax_ApacheVelocity_SetVariable   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 40
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A buildCountAssignment() 0 19 3
A translate() 0 16 3
1
<?php
2
/**
3
 * File containing the {@see Mailcode_Translator_Syntax_ApacheVelocity_SetVariable} class.
4
 *
5
 * @package Mailcode
6
 * @subpackage Translator
7
 * @see Mailcode_Translator_Syntax_ApacheVelocity_SetVariable
8
 */
9
10
declare(strict_types=1);
11
12
namespace Mailcode;
13
14
/**
15
 * Translates the "SetVariable" command to Apache Velocity.
16
 *
17
 * @package Mailcode
18
 * @subpackage Translator
19
 * @author Sebastian Mordziol <[email protected]>
20
 */
21
class Mailcode_Translator_Syntax_ApacheVelocity_SetVariable extends Mailcode_Translator_Syntax_ApacheVelocity implements Mailcode_Translator_Command_SetVariable
22
{
23
    public function translate(Mailcode_Commands_Command_SetVariable $command): string
24
    {
25
        $assignmentString = $command->getAssignmentString();
26
27
        if ($command->isCountEnabled())
28
        {
29
            $result = $this->buildCountAssignment($command);
30
            if($result !== null) {
31
                $assignmentString = $result;
32
            }
33
        }
34
35
        return sprintf(
36
            '#set(%s = %s)',
37
            $command->getVariable()->getFullName(),
38
            $assignmentString
39
        );
40
    }
41
42
    private function buildCountAssignment(Mailcode_Commands_Command_SetVariable $command) : ?string
43
    {
44
        $variable = $command->getCountVariable();
45
46
        if ($variable === null) {
47
            return null;
48
        }
49
50
        if($variable->hasPath()) {
51
            return sprintf(
52
                '$map.of(%s).keys("%s").count()',
53
                dollarize($variable->getPath()),
54
                $variable->getName()
55
            );
56
        }
57
58
        return sprintf(
59
            '$map.of(%s).count()',
60
            dollarize($variable->getName())
61
        );
62
    }
63
}
64