Debian Codegraph @

lib/3rdParty/composer/symfony/translation/Extractor/Visitor/ConstraintVisitor.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Translation\Extractor\Visitor;
13
14 use PhpParser\Node;
15 use PhpParser\NodeVisitor;
16
17 /**
18 * @author Mathieu Santostefano <[email protected]>
19 *
20 * Code mostly comes from https://github.com/php-translation/extractor/blob/master/src/Visitor/Php/Symfony/Constraint.php
21 */
22 final class ConstraintVisitor extends AbstractVisitor implements NodeVisitor
23 {
24 public function __construct(
25 private readonly array $constraintClassNames = [],
26 ) {
27 }
28
29 public function beforeTraverse(array $nodes): ?Node
30 {
31 return null;
32 }
33
34 public function enterNode(Node $node): ?Node
35 {
36 return null;
37 }
38
39 public function leaveNode(Node $node): ?Node
40 {
41 if (!$node instanceof Node\Expr\New_ && !$node instanceof Node\Attribute) {
42 return null;
43 }
44
45 $className = $node instanceof Node\Attribute ? $node->name : $node->class;
46 if (!$className instanceof Node\Name) {
47 return null;
48 }
49
50 $parts = $className->getParts();
51 $isConstraintClass = false;
52
53 foreach ($parts as $part) {
54 if (\in_array($part, $this->constraintClassNames, true)) {
55 $isConstraintClass = true;
56
57 break;
58 }
59 }
60
61 if (!$isConstraintClass) {
62 return null;
63 }
64
65 $arg = $node->args[0] ?? null;
66 if (!$arg instanceof Node\Arg) {
67 return null;
68 }
69
70 if ($this->hasNodeNamedArguments($node)) {
71 $messages = $this->getStringArguments($node, '/message/i', true);
72 } else {
73 if (!$arg->value instanceof Node\Expr\Array_) {
74 // There is no way to guess which argument is a message to be translated.
75 return null;
76 }
77
78 $messages = [];
79 $options = $arg->value;
80
81 foreach ($options->items as $item) {
82 if (!$item->key instanceof Node\Scalar\String_) {
83 continue;
84 }
85
86 if (false === stripos($item->key->value ?? '', 'message')) {
87 continue;
88 }
89
90 if (!$item->value instanceof Node\Scalar\String_) {
91 continue;
92 }
93
94 $messages[] = $item->value->value;
95
96 break;
97 }
98 }
99
100 foreach ($messages as $message) {
101 $this->addMessageToCatalogue($message, 'validators', $node->getStartLine());
102 }
103
104 return null;
105 }
106
107 public function afterTraverse(array $nodes): ?Node
108 {
109 return null;
110 }
111 }