You are here

public function FormState::rewrite in Drupal 7 to 8/9 Module Upgrader 8

Parametrically rewrites the function containing the given parameter.

Parameters

\Pharborist\Functions\ParameterNode $parameter: The parameter upon which to base the rewrite. The parameter must be attached to a function or method declaration node, or fatal errors will likely result.

Overrides Generic::rewrite

File

src/Plugin/DMU/Rewriter/FormState.php, line 117

Class

FormState
Plugin annotation @Rewriter( id = "form_state", type_hint = "\Drupal\Core\Form\FormStateInterface", properties = { "always_process" = { "get" = "getAlwaysProcess", "set" = "setAlwaysProcess" }, "build_info" = { "get" =…

Namespace

Drupal\drupalmoduleupgrader\Plugin\DMU\Rewriter

Code

public function rewrite(ParameterNode $parameter) {
  parent::rewrite($parameter);
  $function = $parameter
    ->getFunction();
  $form_state = Token::variable('$' . $parameter
    ->getName());
  $set_errors = $function
    ->find(Filter::isFunctionCall('form_set_error', 'form_error'));

  /** @var \Pharborist\Functions\FunctionCallNode $set_error */
  foreach ($set_errors as $set_error) {
    $arguments = $set_error
      ->getArguments();
    $method = $set_error
      ->getName()
      ->getText() == 'form_set_error' ? 'setErrorByName' : 'setError';
    $rewrite = ObjectMethodCallNode::create(clone $form_state, $method);
    foreach ($arguments as $argument) {
      if (is_object($argument)) {
        $rewrite
          ->appendArgument(clone $argument);
      }
    }
    $set_error
      ->replaceWith($rewrite);
  }

  // form_clear_error() --> $form_state->clearErrors().
  $clear_errors = $function
    ->find(Filter::isFunctionCall('form_clear_error'));
  foreach ($clear_errors as $clear_error) {
    $clear_error
      ->replaceWith(ObjectMethodCallNode::create(clone $form_state, 'clearErrors'));
  }

  // form_get_errors() --> $form_state->getErrors()
  $get_errors = $function
    ->find(Filter::isFunctionCall('form_get_errors'));
  foreach ($get_errors as $get_error) {
    $get_error
      ->replaceWith(ObjectMethodCallNode::create(clone $form_state, 'getErrors'));
  }

  // form_get_error() --> $form_state->getError()
  $get_errors = $function
    ->find(Filter::isFunctionCall('form_get_error'));

  /** @var \Pharborist\Functions\FunctionCallNode $get_error */
  foreach ($get_errors as $get_error) {
    $rewrite = ObjectMethodCallNode::create(clone $form_state, 'getError')
      ->appendArgument($get_error
      ->getArguments()
      ->get(0));
    $get_error
      ->replaceWith($rewrite);
  }
}