Assert each paragraph items have the same langcode as the node one.
string $node_id: The node ID which contains the paragraph items to be checked.
string $source_lang: The expected node source langcode. Defaults to 'en'.
string $trans_lang: The expected translated node langcode. Defaults to NULL.
protected function assertParagraphsLangcode($node_id, $source_lang = 'en', $trans_lang = NULL) {
// Update the outdated node and check all the paragraph items langcodes.
\Drupal::entityTypeManager()
->getStorage('node')
->resetCache([
$node_id,
]);
/** @var \Drupal\node\NodeInterface $node */
$node = Node::load($node_id);
$node_langcode = $node->langcode->value;
$this
->assertEquals($node_langcode, $source_lang, 'Host langcode matches.');
/** @var \Drupal\Core\Entity\ContentEntityBase $paragraph */
foreach ($node->field_paragraphs_demo
->referencedEntities() as $paragraph) {
$paragraph_langcode = $paragraph
->language()
->getId();
$message = new FormattableMarkup('Node langcode is "@node", paragraph item langcode is "@item".', [
'@node' => $source_lang,
'@item' => $paragraph_langcode,
]);
$this
->assertEquals($paragraph_langcode, $source_lang, $message);
}
// Check the translation.
if (!empty($trans_lang)) {
$this
->assertTrue($node
->hasTranslation($trans_lang), 'Translation exists.');
}
if ($node
->hasTranslation($trans_lang)) {
$trans_node = $node
->getTranslation($trans_lang);
$trans_node_langcode = $trans_node
->language()
->getId();
$this
->assertEquals($trans_node_langcode, $trans_lang, 'Translated node langcode matches.');
// Check the paragraph item langcode matching the translated node langcode.
foreach ($trans_node->field_paragraphs_demo
->referencedEntities() as $paragraph) {
if ($paragraph
->hasTranslation($trans_lang)) {
$trans_item = $paragraph
->getTranslation($trans_lang);
$paragraph_langcode = $trans_item
->language()
->getId();
$message = new FormattableMarkup('Translated node langcode is "@node", paragraph item langcode is "@item".', [
'@node' => $trans_lang,
'@item' => $paragraph_langcode,
]);
$this
->assertEquals($paragraph_langcode, $trans_lang, $message);
}
}
}
}