Passed
Push — master ( 174259...689687 )
by Sebastian
04:01
created

Mailcode_Translator_Syntax_ApacheVelocity_ShowDate   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 31
c 1
b 0
f 0
dl 0
loc 55
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A translate() 0 6 1
A translateFormat() 0 24 3
1
<?php
2
/**
3
 * File containing the {@see Mailcode_Translator_Syntax_ApacheVelocity_ShowDate} class.
4
 *
5
 * @package Mailcode
6
 * @subpackage Translator
7
 * @see Mailcode_Translator_Syntax_ApacheVelocity_ShowDate
8
 */
9
10
declare(strict_types=1);
11
12
namespace Mailcode;
13
14
use AppUtils\ConvertHelper;
15
16
/**
17
 * Translates the "ShowDate" command to Apache Velocity.
18
 *
19
 * @package Mailcode
20
 * @subpackage Translator
21
 * @author Sebastian Mordziol <[email protected]>
22
 */
23
class Mailcode_Translator_Syntax_ApacheVelocity_ShowDate extends Mailcode_Translator_Syntax_ApacheVelocity implements Mailcode_Translator_Command_ShowDate
24
{
25
    const ERROR_UNKNOWN_DATE_FORMAT_CHARACTER = 55501;
26
    
27
   /**
28
    * @var string[]string
29
    */
30
    private $charTable = array(
31
        'd' => 'd',
32
        'm' => 'M',
33
        'Y' => 'yyyy',
34
        'y' => 'yy',
35
        'H' => 'H',
36
        'i' => 'm',
37
        's' => 's',
38
        '.' => '.',
39
        ':' => ':',
40
        '-' => '-',
41
        '/' => '/',
42
        ' ' => ' '
43
    );
44
    
45
    public function translate(Mailcode_Commands_Command_ShowDate $command): string
46
    {
47
        return sprintf(
48
            '$date.format("%s", $%s)',
49
            $this->translateFormat($command->getFormatString()),
50
            ltrim($command->getVariableName(), '$')
51
        );
52
    }
53
    
54
    private function translateFormat(string $formatString) : string
55
    {
56
        $chars = ConvertHelper::string2array($formatString);
57
        $result = array();
58
        
59
        foreach($chars as $char)
60
        {
61
            if(!isset($this->charTable[$char]))
62
            {
63
                throw new Mailcode_Translator_Exception(
64
                    'Unknown date format string character',
65
                    sprintf(
66
                        'No translation for character %s available.',
67
                        ConvertHelper::hidden2visible($char)
68
                    ),
69
                    self::ERROR_UNKNOWN_DATE_FORMAT_CHARACTER
70
                );
71
                
72
            }
73
            
74
            $result[] = $this->charTable[$char]; 
75
        }
76
        
77
        return implode('', $result);
78
    }
79
}
80