Prior to this change ContentEntityInterface::getTranslation()
used to instantiate a new translation if the specified language was valid but no corresponding translation existed. This could easily lead to inadvertently creating new translations and in general to writing ambiguous code.
Now it is required to explicitly invoke ContentEntityInterface::addTranslation()
when wishing to add a new translation:
$node = Node::create([
'type' => 'article',
'title' => 'test',
'langcode' => 'en',
]);
$node->addTranslation('it');
$langcode = $node->getTranslation('it')->language()->getId(); // $langcode is 'it'.
$node->getTranslation('fr'); // Will now throw an exception.
Additionally ContentEntityInterface::addTranslation()
has been fixed to throw an exception when invoked on an language-neutral entity or when a system language code not referring to an actual language is specified:
$node = Node::create([
'type' => 'article',
'title' => 'test',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
]);
$node->addTranslation('it'); // Will now throw an exception.
$node = Node::create([
'type' => 'article',
'title' => 'test',
'langcode' => 'en',
]);
$node->addTranslation(LanguageInterface::LANGCODE_NOT_SPECIFIED); // Will now throw an exception.