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