3 namespace Drupal\Core\Plugin\Discovery;
5 use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
6 use Drupal\Component\Plugin\Discovery\DiscoveryTrait;
7 use Drupal\Core\Discovery\YamlDiscovery as CoreYamlDiscovery;
8 use Drupal\Core\StringTranslation\TranslatableMarkup;
11 * Allows YAML files to define plugin definitions.
13 * If the value of a key (like title) in the definition is translatable then
14 * the addTranslatableProperty() method can be used to mark it as such and also
15 * to add translation context. Then
16 * \Drupal\Core\StringTranslation\TranslatableMarkup will be used to translate
17 * the string and also to mark it safe. Only strings written in the YAML files
18 * should be marked as safe, strings coming from dynamic plugin definitions
19 * potentially containing user input should not.
21 class YamlDiscovery implements DiscoveryInterface {
26 * YAML file discovery and parsing handler.
28 * @var \Drupal\Core\Discovery\YamlDiscovery
33 * Contains an array of translatable properties passed along to t().
35 * @see \Drupal\Core\Plugin\Discovery\YamlDiscovery::addTranslatableProperty()
39 protected $translatableProperties = [];
42 * Construct a YamlDiscovery object.
45 * The file name suffix to use for discovery; for example, 'test' will
46 * become 'MODULE.test.yml'.
47 * @param array $directories
48 * An array of directories to scan.
50 public function __construct($name, array $directories) {
51 $this->discovery = new CoreYamlDiscovery($name, $directories);
55 * Set one of the YAML values as being translatable.
57 * @param string $value_key
58 * The key corresponding to the value in the YAML that contains a
59 * translatable string.
60 * @param string $context_key
61 * (Optional) the translation context for the value specified by the
66 public function addTranslatableProperty($value_key, $context_key = '') {
67 $this->translatableProperties[$value_key] = $context_key;
74 public function getDefinitions() {
75 $plugins = $this->discovery->findAll();
77 // Flatten definitions into what's expected from plugins.
79 foreach ($plugins as $provider => $list) {
80 foreach ($list as $id => $definition) {
81 // Add TranslatableMarkup.
82 foreach ($this->translatableProperties as $property => $context_key) {
83 if (isset($definition[$property])) {
85 // Move the t() context from the definition to the translation
87 if ($context_key && isset($definition[$context_key])) {
88 $options['context'] = $definition[$context_key];
89 unset($definition[$context_key]);
91 $definition[$property] = new TranslatableMarkup($definition[$property], [], $options);
94 // Add ID and provider.
95 $definitions[$id] = $definition + [
96 'provider' => $provider,