Further modules included.
[yaffs-website] / web / modules / contrib / drupalmoduleupgrader / src / Plugin / DMU / Rewriter / Generic.php
1 <?php
2
3 namespace Drupal\drupalmoduleupgrader\Plugin\DMU\Rewriter;
4
5 use Drupal\Core\StringTranslation\TranslationInterface;
6 use Drupal\drupalmoduleupgrader\PluginBase;
7 use Drupal\drupalmoduleupgrader\RewriterInterface;
8 use Drupal\drupalmoduleupgrader\Utility\Filter\FieldValueFilter;
9 use Drupal\drupalmoduleupgrader\Utility\Filter\NodeAssignmentFilter;
10 use Pharborist\ArrayLookupNode;
11 use Pharborist\Constants\ConstantNode;
12 use Pharborist\ExpressionNode;
13 use Pharborist\Filter;
14 use Pharborist\Functions\CallNode;
15 use Pharborist\Functions\EmptyNode;
16 use Pharborist\Functions\IssetNode;
17 use Pharborist\Functions\ParameterNode;
18 use Pharborist\Node;
19 use Pharborist\NodeCollection;
20 use Pharborist\Objects\ClassConstantLookupNode;
21 use Pharborist\Objects\ObjectMethodCallNode;
22 use Pharborist\Objects\ObjectPropertyNode;
23 use Pharborist\Operators\AssignNode;
24 use Pharborist\Operators\BooleanNotNode;
25 use Pharborist\Parser;
26 use Pharborist\Types\StringNode;
27 use Pharborist\Variables\VariableNode;
28 use Psr\Log\LoggerInterface;
29
30 /**
31  * @Rewriter(
32  *  id = "_rewriter",
33  *  deriver = "\Drupal\drupalmoduleupgrader\Plugin\DMU\Rewriter\GenericDeriver"
34  * )
35  */
36 class Generic extends PluginBase implements RewriterInterface {
37
38   /**
39    * @var \Drupal\drupalmoduleupgrader\Utility\Filter\NodeAssignmentFilter
40    */
41   protected $isAssigned;
42
43   public function __construct(array $configuration, $plugin_id, $plugin_definition, TranslationInterface $translator, LoggerInterface $log) {
44     parent::__construct($configuration, $plugin_id, $plugin_definition, $translator, $log);
45     $this->isAssigned = new NodeAssignmentFilter();
46   }
47
48   /**
49    * {@inheritdoc}
50    */
51   public function rewrite(ParameterNode $parameter) {
52     // Don't even try to rewrite the function if the parameter is reassigned.
53     if ($this->isReassigned($parameter)) {
54       $error = $this->t('@function() cannot be parametrically rewritten because @parameter is reassigned.', [
55         '@parameter' => $parameter->getName(),
56         '@function' => $parameter->getFunction()->getName()->getText(),
57       ]);
58       throw new \LogicException($error);
59     }
60
61     foreach ($this->getExpressions($parameter)->not($this->isAssigned) as $expr) {
62       $property = $this->getProperty($expr);
63       if (empty($property)) {
64         continue;
65       }
66
67       $getter = $this->rewriteAsGetter($expr, $property);
68       if ($getter) {
69         $empty = $expr->closest(Filter::isFunctionCall('empty', 'isset'));
70
71         // If the original expression was wrapped by a call to isset() or
72         // empty(), we need to replace it entirely.
73         if ($getter instanceof CallNode && $empty instanceof CallNode) {
74           // If the isset() or empty() call was negated, reverse that logic.
75           $parent = $empty->parent();
76           if ($parent instanceof BooleanNotNode) {
77             $parent->replaceWith($getter);
78           }
79           else {
80             $empty->replaceWith(BooleanNotNode::fromExpression($getter));
81           }
82         }
83         else {
84           $expr->replaceWith($getter);
85         }
86       }
87     }
88
89     foreach ($this->getExpressions($parameter)->filter($this->isAssigned) as $expr) {
90       // If the property cannot be determined, don't even try to rewrite the
91       // expression.
92       $property = $this->getProperty($expr);
93       if (empty($property)) {
94         continue;
95       }
96
97       $assignment = $expr->closest(Filter::isInstanceOf('\Pharborist\Operators\AssignNode'));
98
99       $setter = $this->rewriteAsSetter($expr, $property, $assignment);
100       if ($setter) {
101         $assignment->replaceWith($setter);
102       }
103     }
104
105     // Set the type hint, if one is defined.
106     if (isset($this->pluginDefinition['type_hint'])) {
107       $parameter->setTypeHint($this->pluginDefinition['type_hint']);
108
109       // If the type hint extends FieldableEntityInterface, rewrite any field
110       // lookups (e.g. $node->body[LANGUAGE_NONE][0]['value']).
111       if (in_array('Drupal\Core\Entity\FieldableEntityInterface', class_implements($this->pluginDefinition['type_hint']))) {
112         $filter = new FieldValueFilter($parameter->getName());
113
114         foreach ($parameter->getFunction()->find($filter) as $lookup) {
115           $lookup->replaceWith(self::rewriteFieldLookup($lookup));
116         }
117       }
118     }
119   }
120
121   /**
122    * Finds every rewritable expression in the function body.
123    *
124    * @param \Pharborist\Functions\ParameterNode $parameter
125    *  The parameter on which the rewrite is based.
126    *
127    * @return \Pharborist\NodeCollection
128    */
129   protected function getExpressions(ParameterNode $parameter) {
130     $filter = Filter::isInstanceOf('\Pharborist\ArrayLookupNode', '\Pharborist\Objects\ObjectPropertyNode');
131     $expressions = new NodeCollection();
132
133     $parameter
134       ->getFunction()
135       ->find(Filter::isInstanceOf('\Pharborist\Variables\VariableNode'))
136       ->filter(function(VariableNode $variable) use ($parameter) {
137         return $variable->getName() == $parameter->getName();
138       })
139       ->each(function(VariableNode $variable) use ($filter, $expressions) {
140         $root = $variable->furthest($filter);
141         if ($root) {
142           $expressions->add($root);
143         }
144       });
145
146     return $expressions;
147   }
148
149   /**
150    * Returns the property used by a rewritable expression, or NULL if the
151    * property cannot be determined.
152    *
153    * @param \Pharborist\ExpressionNode $expr
154    *  The rewritable expression.
155    *
156    * @return string|NULL
157    */
158   protected function getProperty(ExpressionNode $expr) {
159     if ($expr instanceof ObjectPropertyNode) {
160       return $expr->getPropertyName();
161     }
162     elseif ($expr instanceof ArrayLookupNode) {
163       $key = $expr->getKey(0);
164
165       if ($key instanceof StringNode) {
166         return $key->toValue();
167       }
168     }
169   }
170
171   /**
172    * Rewrites the given expression as a property getter. Returns NULL if the
173    * expression cannot be rewritten.
174    *
175    * @param \Pharborist\ExpressionNode $expr
176    *  The expression to rewrite.
177    * @param string $property
178    *  The property being used in the expression.
179    *
180    * @return \Pharborist\ExpressionNode|NULL
181    */
182   public function rewriteAsGetter(ExpressionNode $expr, $property) {
183     if ($expr instanceof ObjectPropertyNode) {
184       // Should be getRootObject() or getLookupRoot().
185       // @see Pharborist issue #191
186       $object = clone $expr->getObject();
187     }
188     elseif ($expr instanceof ArrayLookupNode) {
189       $object = clone $expr->getRootArray();
190     }
191
192     if (isset($object) && isset($this->pluginDefinition['properties'][$property]['get'])) {
193       return ObjectMethodCallNode::create($object, $this->pluginDefinition['properties'][$property]['get']);
194     }
195   }
196
197   /**
198    * Rewrites an assignment expression as a property setter. Returns NULL if
199    * the expression cannot be rewritten.
200    *
201    * @param \Pharborist\ExpressionNode $expr
202    *  The expression to rewrite.
203    * @param string $property
204    *  The property being used in the expression.
205    * @param \Pharborist\Operators\AssignNode $assignment
206    *  The entire assignment expression being rewritten.
207    *
208    * @return \Pharborist\ExpressionNode|NULL
209    */
210   public function rewriteAsSetter(ExpressionNode $expr, $property, AssignNode $assignment) {
211     if ($expr instanceof ObjectPropertyNode) {
212       // Should be getRootObject() or getLookupRoot().
213       // @see Pharborist issue #191
214       $object = clone $expr->getObject();
215     }
216     elseif ($expr instanceof ArrayLookupNode) {
217       $object = clone $expr->getRootArray();
218     }
219
220     if (isset($object) && isset($this->pluginDefinition['properties'][$property]['set'])) {
221       return ObjectMethodCallNode::create($object, $this->pluginDefinition['properties'][$property]['set'])
222         ->appendArgument(clone $assignment->getRightOperand());
223     }
224   }
225
226   /**
227    * Returns if the parameter is fully reassigned anywhere in the function.
228    *
229    * @param \Pharborist\Functions\ParameterNode $parameter
230    *  The parameter to check.
231    *
232    * @return boolean
233    */
234   protected function isReassigned(ParameterNode $parameter) {
235     return (boolean) $parameter
236       ->getFunction()
237       ->find(Filter::isInstanceOf('\Pharborist\Variables\VariableNode'))
238       ->filter(function(VariableNode $variable) use ($parameter) {
239         return $variable->getName() == $parameter->getName();
240       })
241       ->filter($this->isAssigned)
242       ->count();
243   }
244
245   /**
246    * Rewrites a Drupal 7 field lookup like so:
247    *
248    * $node->body[LANGUAGE_NONE][0]['value'] --> $node->body[0]->value
249    * $node->body['fr'][0]['value'] --> $node->getTranslation('fr')->body[0]->value
250    *
251    * @param \Pharborist\ArrayLookupNode $node
252    *  The original field lookup.
253    *
254    * @return \Pharborist\ExpressionNode
255    */
256   public static function rewriteFieldLookup(ArrayLookupNode $node) {
257     $keys = $node->getKeys();
258     /** @var \Pharborist\Objects\ObjectPropertyNode $root */
259     $root = $node->getRootArray();
260     $expr = $root->getObject()->getText();
261
262     if (self::isTranslation($keys[0])) {
263       $expr .= '->getTranslation(' . $keys[0] . ')';
264     }
265     $expr .= '->' . $root->getPropertyName() . '[' . $keys[1] . ']';
266
267     /** @var \Pharborist\Types\StringNode|\Pharborist\Node $column */
268     foreach (array_slice($keys, 2) as $column) {
269       $expr .= '->';
270       $expr .= $column instanceof StringNode ? $column->toValue() : $column->getText();
271     }
272
273     return Parser::parseExpression($expr);
274   }
275
276   /**
277    * Checks if a field lookup key is translated. This will be TRUE unless one
278    * of the following conditions applies:
279    *
280    * - The key is the Drupal\Core\Language\Language::LANGCODE_NOT_SPECIFIED
281    *   constant.
282    * - The key is the LANGUAGE_NONE constant from Drupal 7.
283    * - The key is the string 'und'.
284    *
285    * @param Node $key
286    *  The key to check.
287    *
288    * @return boolean
289    */
290   public static function isTranslation(Node $key) {
291     if ($key instanceof ClassConstantLookupNode) {
292       $constant = $key->getClassName() . '::' . $key->getConstantName();
293       return $constant != '\Drupal\Core\Language\Language::LANGCODE_NOT_SPECIFIED';
294     }
295     elseif ($key instanceof ConstantNode) {
296       return $key->getConstantName() != 'LANGUAGE_NONE';
297     }
298     elseif ($key instanceof StringNode) {
299       return $key->toValue() != 'und';
300     }
301     else {
302       return TRUE;
303     }
304   }
305
306 }