Passed
Push — master ( e7c89c...d9a062 )
by Sebastian
06:11 queued 12s
created

Date::create()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 44
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 28
nc 12
nop 4
dl 0
loc 44
rs 9.1608
c 1
b 0
f 0
1
<?php
2
/**
3
 * File containing the class {@see \Mailcode\Factory\CommandSets\Set\Show\Date}.
4
 *
5
 * @package Mailcode
6
 * @subpackage Factory
7
 * @see \Mailcode\Factory\CommandSets\Set\Show\Date
8
 */
9
10
declare(strict_types=1);
11
12
namespace Mailcode\Factory\CommandSets\Set\Show;
13
14
use Mailcode\Mailcode_Commands_Command_ShowDate;
15
use Mailcode\Mailcode_Factory_CommandSets_Set;
16
17
/**
18
 * Factory class for the `showdate` command.
19
 *
20
 * @package Mailcode
21
 * @subpackage Factory
22
 * @author Sebastian Mordziol <[email protected]>
23
 */
24
class Date extends Mailcode_Factory_CommandSets_Set
25
{
26
    public function create(string $variableName, string $formatString = "", string $timezoneString = null, string $timezoneVariable = null): Mailcode_Commands_Command_ShowDate
27
    {
28
        $variableName = $this->instantiator->filterVariableName($variableName);
29
30
        $format = '';
31
        if (!empty($formatString)) {
32
            $format = sprintf(
33
                ' "%s"',
34
                $formatString
35
            );
36
        }
37
38
        $timezone = '';
39
        if (!empty($timezoneString)) {
40
            $timezone = sprintf(
41
                ' %s',
42
                $this->quoteString($timezoneString)
43
            );
44
        } else if (!empty($timezoneVariable)) {
45
            $timezone = sprintf(
46
                ' %s',
47
                $timezoneVariable
48
            );
49
        }
50
51
        $cmd = $this->commands->createCommand(
52
            'ShowDate',
53
            '',
54
            $variableName . $format . $timezone,
55
            sprintf(
56
                '{showdate: %s%s%s}',
57
                $variableName,
58
                $format,
59
                $timezone
60
            )
61
        );
62
63
        $this->instantiator->checkCommand($cmd);
64
65
        if ($cmd instanceof Mailcode_Commands_Command_ShowDate) {
66
            return $cmd;
67
        }
68
69
        throw $this->instantiator->exceptionUnexpectedType('ShowDate', $cmd);
70
    }
71
72
    private function quoteString(string $string): string
73
    {
74
        if (substr($string, 0, 1) === '"' && substr($string, -1, 1) === '"') {
75
            return $string;
76
        }
77
78
        return '"' . str_replace('"', '\"', $string) . '"';
79
    }
80
81
}
82