Generator::sentence() can often generate an empty string with just a period.

Created on 16 February 2023, about 2 years ago

Problem/Motivation

I am often seeing sentences being generated in the styleguide that just contain a period and nothing else:

πŸ› Bug report
Status

Fixed

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States dave reid Nebraska USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @dave reid
  • πŸ‡ΊπŸ‡ΈUnited States dave reid Nebraska USA

    What's happening is a bug in the following code:

      public function sentence($link = FALSE) {
        $graph = $this->random->sentences(mt_rand(60, 180));
        $explode = explode('.', $graph);
        // This $explode will always result in all of its array entries with one space at the beginning of the string, and then an always empty string as the last array value.
        $rand = array_rand($explode);
        $sentence = trim($explode[$rand]);
        if ($link) {
          $explode = explode(' ', $sentence);
          $link = [
            '#type' => 'link',
            '#title' => $explode[0],
            '#url' => $link,
            '#options' => [
              'attributes' => [],
              'html' => FALSE,
            ],
            '#text' => $explode[0],
          ];
          $explode[0] = \Drupal::service('renderer')->render($link);
          $sentence = implode(' ', $explode);
        }
        return Markup::create($sentence . '.');
      }
    

    By changing the first explode('.', $graph) call to use preg_split('/\. ?/', $graph, -1, PREG_SPLIT_NO_EMPTY); we end up with a clean array of sentences with no empty values or leading spaces in each array value.

  • @dave-reid opened merge request.
  • Status changed to Fixed about 2 years ago
  • πŸ‡ΊπŸ‡ΈUnited States dave reid Nebraska USA
  • Automatically closed - issue fixed for 2 weeks with no activity.

Production build 0.71.5 2024