Completed
Push — travis ( f73ca9 )
by Asmir
03:03
created

TranslateAttrAttribute::getVarname()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 View Code Duplication
            if (!$node->hasAttribute($attrExpr[0])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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