Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
NameListFormattableMarkup
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
4 / 4
8
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 __toString
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 jsonSerialize
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 escapeValues
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Drupal\name\Render;
6
7use Drupal\Component\Render\MarkupInterface;
8use Drupal\Component\Utility\Html;
9
10/**
11 * Formats a string for HTML display by replacing variable placeholders.
12 *
13 * Adds special handling of @names, @last.
14 */
15class NameListFormattableMarkup implements MarkupInterface {
16
17  /**
18   * The names.
19   *
20   * @var array
21   */
22  protected $names = [];
23
24
25  /**
26   * The name separator.
27   *
28   * @var string
29   */
30  protected $separator = ', ';
31
32  /**
33   * Constructor for NameListFormattableMarkup.
34   *
35   * @param array $names
36   *   Names to render in the list.
37   * @param mixed $separator
38   *   A separator between rendered names. When the separator implements
39   *   MarkupInterface, it is treated as trusted markup. Any other value is
40   *   cast to string and escaped.
41   */
42  public function __construct(array $names = [], $separator = ', ') {
43    $this->names = $names;
44    $this->separator = $separator instanceof MarkupInterface ? (string) $separator : Html::escape((string) $separator);
45  }
46
47  /**
48   * {@inheritdoc}
49   */
50  public function __toString() {
51    return $this->escapeValues($this->names);
52  }
53
54  /**
55   * {@inheritdoc}
56   */
57  public function jsonSerialize() : mixed {
58    return $this->__toString();
59  }
60
61  /**
62   * Escapes values if needed.
63   *
64   * @param array|string|\Drupal\Component\Render\MarkupInterface $value
65   *   A placeholder replacement value. Will recursively escape array values
66   *   using the specified separator.
67   *
68   * @return string
69   *   The properly escaped replacement value.
70   */
71  protected function escapeValues($value) {
72    if (is_array($value)) {
73      $escaped = [];
74      foreach ($value as $child_value) {
75        $escaped[] = $this->escapeValues($child_value);
76      }
77      return implode($this->separator, $escaped);
78    }
79
80    return $value instanceof MarkupInterface ? (string) $value : Html::escape($value);
81  }
82
83}