5 use Drupal\Core\Cache\CacheableDependencyInterface;
6 use Drupal\Core\TypedData\DataDefinitionInterface;
7 use Drupal\Core\TypedData\TypedDataInterface;
8 use Drupal\Core\TypedData\TypedData;
9 use Drupal\filter\FilterProcessResult;
10 use Drupal\filter\Render\FilteredMarkup;
13 * A computed property for processing text with a format.
15 * Required settings (below the definition's 'settings' key) are:
16 * - text source: The text property containing the to be processed text.
18 class TextProcessed extends TypedData implements CacheableDependencyInterface {
21 * Cached processed text.
23 * @var \Drupal\filter\FilterProcessResult|null
25 protected $processed = NULL;
30 public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
31 parent::__construct($definition, $name, $parent);
33 if ($definition->getSetting('text source') === NULL) {
34 throw new \InvalidArgumentException("The definition's 'text source' key has to specify the name of the text property to be processed.");
41 public function getValue() {
42 if ($this->processed !== NULL) {
43 return FilteredMarkup::create($this->processed->getProcessedText());
46 $item = $this->getParent();
47 $text = $item->{($this->definition->getSetting('text source'))};
49 // Avoid doing unnecessary work on empty strings.
50 if (!isset($text) || $text === '') {
51 $this->processed = new FilterProcessResult('');
55 '#type' => 'processed_text',
57 '#format' => $item->format,
58 '#filter_types_to_skip' => [],
59 '#langcode' => $item->getLangcode(),
61 // Capture the cacheability metadata associated with the processed text.
62 $processed_text = $this->getRenderer()->renderPlain($build);
63 $this->processed = FilterProcessResult::createFromRenderArray($build)->setProcessedText((string) $processed_text);
65 return FilteredMarkup::create($this->processed->getProcessedText());
71 public function setValue($value, $notify = TRUE) {
72 $this->processed = $value;
73 // Notify the parent of any changes.
74 if ($notify && isset($this->parent)) {
75 $this->parent->onChange($this->name);
82 public function getCacheTags() {
84 return $this->processed->getCacheTags();
90 public function getCacheContexts() {
92 return $this->processed->getCacheContexts();
98 public function getCacheMaxAge() {
100 return $this->processed->getCacheMaxAge();
104 * Returns the renderer service.
106 * @return \Drupal\Core\Render\RendererInterface
108 protected function getRenderer() {
109 return \Drupal::service('renderer');