You are here

public function TestSubContext::flagPhpScenarioErrors in Panopoly 8.2

Same name and namespace in other branches
  1. 7 modules/panopoly/panopoly_test/behat/steps/panopoly_test.behat.inc \TestSubContext::flagPhpScenarioErrors()

Output any PHP notices that were logged in the scenario.

@AfterScenario

File

modules/panopoly/panopoly_test/behat/steps/panopoly_test.behat.inc, line 174
Provide Behat step-definitions for generic Panopoly tests.

Class

TestSubContext
Behat sub-context for Panopoly.

Code

public function flagPhpScenarioErrors(AfterScenarioScope $scope) {
  $flagPhp = getenv('PANOPOLY_BEHAT_FLAG_PHP_NOTICES');
  if (!empty($flagPhp)) {
    $scenarioName = $scope
      ->getFeature()
      ->getTitle();
    $result = \Drupal::database()
      ->select('watchdog', 'w')
      ->fields('w', [])
      ->condition('w.type', 'php', '=')
      ->execute();
    $errors = [];
    foreach ($result as $entry) {
      $variables = unserialize($entry->variables);
      $time = date('Ymd-Hi', $entry->timestamp);

      // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
      $errors[] = "{$scenarioName}|{$time}|" . strip_tags(t($entry->message, $variables));
    }
    if (!empty($errors)) {
      $message = implode("\r\n", $errors);
      print "{$message}\n";

      // Write the error message(s) to a file.
      $local_file_path = getenv('PANOPOLY_BEHAT_SCREENSHOT_PATH');
      if (empty($local_file_path)) {
        print "Environment variable PANOPOLY_BEHAT_SCREENSHOT_PATH is not set, unable to save errors\n";
      }
      elseif (!is_dir($local_file_path)) {
        print "Directory {$local_file_path} does not exist, unable to save errors\n";
      }
      else {
        $file_location = "{$local_file_path}/behat-php-errors.txt";
        if (@file_put_contents($file_location, $message . "\r\n", FILE_APPEND) !== FALSE) {
          print "PHP errors saved to {$file_location}\n";
        }
        else {
          print "Unable to save errors\n";
        }
      }

      // Clear the log for the next scenario.
      \Drupal::database()
        ->update('watchdog')
        ->fields([
        'type' => 'behat',
      ])
        ->condition('type', 'php')
        ->execute();
      if ($flagPhp == self::PANOPOLY_BEHAT_FLAG_PHP_NOTICES_FAIL) {
        throw new \Exception("PHP errors were logged. See scenario output for details.");
      }
    }
  }
}