toolshed-8.x-1.x-dev/src/Discovery/YamlDiscovery.php
src/Discovery/YamlDiscovery.php
<?php
namespace Drupal\toolshed\Discovery;
use Drupal\Core\Discovery\YamlDiscovery as CoreYamlDiscovery;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* The default strategy YAML discovery class.
*/
class YamlDiscovery extends CoreYamlDiscovery {
/**
* Contains an array of translatable properties passed along to t().
*
* @var string[]
*
* @see \Drupal\Core\Plugin\Discovery\YamlDiscovery::addTranslatableProperty()
*/
protected array $translatableProperties = [];
/**
* Set one of the YAML values as being translatable.
*
* @param string $value_key
* The key corresponding to the value in the YAML that contains a
* translatable string.
* @param string $context_key
* (Optional) the translation context for the value specified by the
* $value_key.
*
* @return $this
*/
public function addTranslatableProperty($value_key, $context_key = ''): self {
$this->translatableProperties[$value_key] = $context_key;
return $this;
}
/**
* {@inheritdoc}
*/
public function findAll(): array {
$definitions = parent::findAll();
foreach ($definitions as $provider => &$list) {
foreach ($list as &$definition) {
// Add TranslatableMarkup.
foreach ($this->translatableProperties as $property => $context_key) {
if (isset($definition[$property])) {
$options = [];
// Move the t() context from the definition to the translation.
if ($context_key && isset($definition[$context_key])) {
$options['context'] = $definition[$context_key];
unset($definition[$context_key]);
}
// Property is from static YAML files and should be scannable for
// translation from there? This is also how this is done for
// Drupal\Core\Plugin\Discovery\YamlDiscovery so unless a better
// way is managed there, this is a valid use of non-literal string
// for t().
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
$definition[$property] = new TranslatableMarkup($definition[$property], [], $options);
}
}
$definition += ['provider' => $provider];
}
}
return $definitions;
}
}
