Completed
Push — twital-1.0 ( 9ab6a6...7cf757 )
by Asmir
03:17
created

TranslateAttrAttribute::visit()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6.0045

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 19
cts 20
cp 0.95
rs 8.439
c 0
b 0
f 0
cc 6
eloc 18
nc 10
nop 2
crap 6.0045
1
<?php
2
namespace Goetas\TwitalBundle\Attribute;
3
4
use Goetas\Twital\Attribute;
5
use Goetas\Twital\Compiler;
6
use DOMAttr;
7
use Goetas\Twital\Helper\ParserHelper;
8
9
/**
10
 *
11
 * @author Asmir Mustafic <[email protected]>
12
 *
13
 */
14
class TranslateAttrAttribute implements Attribute
15
{
16
17 8
    public static function getVarname(\DOMNode $node)
18
    {
19 8
        return "__a" . str_replace("-", "_", spl_object_hash($node));
20
    }
21
22 8
    public function visit(DOMAttr $att, Compiler $context)
23
    {
24 8
        $node = $att->ownerElement;
25 8
        $expressions = ParserHelper::staticSplitExpression($att->value, ",");
26 8
        $varName = self::getVarname($node);
27
28 8
        $parts = array();
29
30 8
        foreach ($expressions as $expression) {
31
32 8
            $attrExpr = ParserHelper::staticSplitExpression($expression, ":");
33
34 8
            if (!$node->hasAttribute($attrExpr[0])) {
35
                throw new \Exception("Can't find the attribute named '" . $attrExpr[0] . "'");
36
            }
37
38 8
            $attNode = $node->getAttributeNode($attrExpr[0]);
39
40 8
            $transParams = isset($attrExpr[1]) ? ParserHelper::staticSplitExpression(trim($attrExpr[1], "[]\n\r\t"), ",") : array();
41
42 8
            $parts[$attrExpr[0]] = "['" . addcslashes($attNode->value, "'") . "'|trans(" . (isset($transParams[0]) ? ($transParams[0]) : '') . (isset($transParams[1]) ? ", $transParams[1]" : "") . ")]";
43
44 8
            $node->removeAttributeNode($attNode);
45 8
        }
46
47 8
        $code = "set $varName = $varName|default({})|merge({" . ParserHelper::implodeKeyed(",", $parts, true) . "})";
48 8
        $node->setAttribute("__attr__", $varName);
49
50 8
        $pi = $context->createControlNode($code);
51
52 8
        $node->parentNode->insertBefore($pi, $node);
53
54 8
        $node->removeAttributeNode($att);
55 8
    }
56
}
57