Passed
Push — master ( d8dc61...dfdb64 )
by Sebastian
09:05
created

SetVariableTranslation   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 21
c 0
b 0
f 0
dl 0
loc 45
rs 10

2 Methods

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