ContentEntityBase.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Core\Entity\Plugin\DataType\EntityReference;
  5. use Drupal\Core\Field\BaseFieldDefinition;
  6. use Drupal\Core\Language\Language;
  7. use Drupal\Core\Language\LanguageInterface;
  8. use Drupal\Core\Session\AccountInterface;
  9. use Drupal\Core\StringTranslation\TranslatableMarkup;
  10. use Drupal\Core\TypedData\TranslationStatusInterface;
  11. use Drupal\Core\TypedData\TypedDataInterface;
  12. /**
  13. * Implements Entity Field API specific enhancements to the Entity class.
  14. *
  15. * @ingroup entity_api
  16. */
  17. abstract class ContentEntityBase extends EntityBase implements \IteratorAggregate, ContentEntityInterface, TranslationStatusInterface {
  18. use EntityChangesDetectionTrait {
  19. getFieldsToSkipFromTranslationChangesCheck as traitGetFieldsToSkipFromTranslationChangesCheck;
  20. }
  21. use SynchronizableEntityTrait;
  22. /**
  23. * The plain data values of the contained fields.
  24. *
  25. * This always holds the original, unchanged values of the entity. The values
  26. * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
  27. * is used for values in default language.
  28. *
  29. * @todo: Add methods for getting original fields and for determining
  30. * changes.
  31. * @todo: Provide a better way for defining default values.
  32. *
  33. * @var array
  34. */
  35. protected $values = [];
  36. /**
  37. * The array of fields, each being an instance of FieldItemListInterface.
  38. *
  39. * @var array
  40. */
  41. protected $fields = [];
  42. /**
  43. * Local cache for field definitions.
  44. *
  45. * @see ContentEntityBase::getFieldDefinitions()
  46. *
  47. * @var array
  48. */
  49. protected $fieldDefinitions;
  50. /**
  51. * Local cache for the available language objects.
  52. *
  53. * @var \Drupal\Core\Language\LanguageInterface[]
  54. */
  55. protected $languages;
  56. /**
  57. * The language entity key.
  58. *
  59. * @var string
  60. */
  61. protected $langcodeKey;
  62. /**
  63. * The default langcode entity key.
  64. *
  65. * @var string
  66. */
  67. protected $defaultLangcodeKey;
  68. /**
  69. * Language code identifying the entity active language.
  70. *
  71. * This is the language field accessors will use to determine which field
  72. * values manipulate.
  73. *
  74. * @var string
  75. */
  76. protected $activeLangcode = LanguageInterface::LANGCODE_DEFAULT;
  77. /**
  78. * Local cache for the default language code.
  79. *
  80. * @var string
  81. */
  82. protected $defaultLangcode;
  83. /**
  84. * An array of entity translation metadata.
  85. *
  86. * An associative array keyed by translation language code. Every value is an
  87. * array containing the translation status and the translation object, if it has
  88. * already been instantiated.
  89. *
  90. * @var array
  91. */
  92. protected $translations = [];
  93. /**
  94. * A flag indicating whether a translation object is being initialized.
  95. *
  96. * @var bool
  97. */
  98. protected $translationInitialize = FALSE;
  99. /**
  100. * Boolean indicating whether a new revision should be created on save.
  101. *
  102. * @var bool
  103. */
  104. protected $newRevision = FALSE;
  105. /**
  106. * Indicates whether this is the default revision.
  107. *
  108. * @var bool
  109. */
  110. protected $isDefaultRevision = TRUE;
  111. /**
  112. * Holds untranslatable entity keys such as the ID, bundle, and revision ID.
  113. *
  114. * @var array
  115. */
  116. protected $entityKeys = [];
  117. /**
  118. * Holds translatable entity keys such as the label.
  119. *
  120. * @var array
  121. */
  122. protected $translatableEntityKeys = [];
  123. /**
  124. * Whether entity validation was performed.
  125. *
  126. * @var bool
  127. */
  128. protected $validated = FALSE;
  129. /**
  130. * Whether entity validation is required before saving the entity.
  131. *
  132. * @var bool
  133. */
  134. protected $validationRequired = FALSE;
  135. /**
  136. * The loaded revision ID before the new revision was set.
  137. *
  138. * @var int
  139. */
  140. protected $loadedRevisionId;
  141. /**
  142. * The revision translation affected entity key.
  143. *
  144. * @var string
  145. */
  146. protected $revisionTranslationAffectedKey;
  147. /**
  148. * Whether the revision translation affected flag has been enforced.
  149. *
  150. * An array, keyed by the translation language code.
  151. *
  152. * @var bool[]
  153. */
  154. protected $enforceRevisionTranslationAffected = [];
  155. /**
  156. * Local cache for fields to skip from the checking for translation changes.
  157. *
  158. * @var array
  159. */
  160. protected static $fieldsToSkipFromTranslationChangesCheck = [];
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
  165. $this->entityTypeId = $entity_type;
  166. $this->entityKeys['bundle'] = $bundle ? $bundle : $this->entityTypeId;
  167. $this->langcodeKey = $this->getEntityType()->getKey('langcode');
  168. $this->defaultLangcodeKey = $this->getEntityType()->getKey('default_langcode');
  169. $this->revisionTranslationAffectedKey = $this->getEntityType()->getKey('revision_translation_affected');
  170. foreach ($values as $key => $value) {
  171. // If the key matches an existing property set the value to the property
  172. // to set properties like isDefaultRevision.
  173. // @todo: Should this be converted somehow?
  174. if (property_exists($this, $key) && isset($value[LanguageInterface::LANGCODE_DEFAULT])) {
  175. $this->$key = $value[LanguageInterface::LANGCODE_DEFAULT];
  176. }
  177. }
  178. $this->values = $values;
  179. foreach ($this->getEntityType()->getKeys() as $key => $field_name) {
  180. if (isset($this->values[$field_name])) {
  181. if (is_array($this->values[$field_name])) {
  182. // We store untranslatable fields into an entity key without using a
  183. // langcode key.
  184. if (!$this->getFieldDefinition($field_name)->isTranslatable()) {
  185. if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
  186. if (is_array($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT])) {
  187. if (isset($this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'])) {
  188. $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT][0]['value'];
  189. }
  190. }
  191. else {
  192. $this->entityKeys[$key] = $this->values[$field_name][LanguageInterface::LANGCODE_DEFAULT];
  193. }
  194. }
  195. }
  196. else {
  197. // We save translatable fields such as the publishing status of a node
  198. // into an entity key array keyed by langcode as a performance
  199. // optimization, so we don't have to go through TypedData when we
  200. // need these values.
  201. foreach ($this->values[$field_name] as $langcode => $field_value) {
  202. if (is_array($this->values[$field_name][$langcode])) {
  203. if (isset($this->values[$field_name][$langcode][0]['value'])) {
  204. $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode][0]['value'];
  205. }
  206. }
  207. else {
  208. $this->translatableEntityKeys[$key][$langcode] = $this->values[$field_name][$langcode];
  209. }
  210. }
  211. }
  212. }
  213. }
  214. }
  215. // Initialize translations. Ensure we have at least an entry for the default
  216. // language.
  217. // We determine if the entity is new by checking in the entity values for
  218. // the presence of the id entity key, as the usage of ::isNew() is not
  219. // possible in the constructor.
  220. $data = isset($values[$this->getEntityType()->getKey('id')]) ? ['status' => static::TRANSLATION_EXISTING] : ['status' => static::TRANSLATION_CREATED];
  221. $this->translations[LanguageInterface::LANGCODE_DEFAULT] = $data;
  222. $this->setDefaultLangcode();
  223. if ($translations) {
  224. foreach ($translations as $langcode) {
  225. if ($langcode != $this->defaultLangcode && $langcode != LanguageInterface::LANGCODE_DEFAULT) {
  226. $this->translations[$langcode] = $data;
  227. }
  228. }
  229. }
  230. if ($this->getEntityType()->isRevisionable()) {
  231. // Store the loaded revision ID the entity has been loaded with to
  232. // keep it safe from changes.
  233. $this->updateLoadedRevisionId();
  234. }
  235. }
  236. /**
  237. * {@inheritdoc}
  238. */
  239. protected function getLanguages() {
  240. if (empty($this->languages)) {
  241. $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL);
  242. // If the entity references a language that is not or no longer available,
  243. // we return a mock language object to avoid disrupting the consuming
  244. // code.
  245. if (!isset($this->languages[$this->defaultLangcode])) {
  246. $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
  247. }
  248. }
  249. return $this->languages;
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function postCreate(EntityStorageInterface $storage) {
  255. $this->newRevision = TRUE;
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. public function setNewRevision($value = TRUE) {
  261. if (!$this->getEntityType()->hasKey('revision')) {
  262. throw new \LogicException("Entity type {$this->getEntityTypeId()} does not support revisions.");
  263. }
  264. if ($value && !$this->newRevision) {
  265. // When saving a new revision, set any existing revision ID to NULL so as
  266. // to ensure that a new revision will actually be created.
  267. $this->set($this->getEntityType()->getKey('revision'), NULL);
  268. }
  269. elseif (!$value && $this->newRevision) {
  270. // If ::setNewRevision(FALSE) is called after ::setNewRevision(TRUE) we
  271. // have to restore the loaded revision ID.
  272. $this->set($this->getEntityType()->getKey('revision'), $this->getLoadedRevisionId());
  273. }
  274. $this->newRevision = $value;
  275. }
  276. /**
  277. * {@inheritdoc}
  278. */
  279. public function getLoadedRevisionId() {
  280. return $this->loadedRevisionId;
  281. }
  282. /**
  283. * {@inheritdoc}
  284. */
  285. public function updateLoadedRevisionId() {
  286. $this->loadedRevisionId = $this->getRevisionId() ?: $this->loadedRevisionId;
  287. return $this;
  288. }
  289. /**
  290. * {@inheritdoc}
  291. */
  292. public function isNewRevision() {
  293. return $this->newRevision || ($this->getEntityType()->hasKey('revision') && !$this->getRevisionId());
  294. }
  295. /**
  296. * {@inheritdoc}
  297. */
  298. public function isDefaultRevision($new_value = NULL) {
  299. $return = $this->isDefaultRevision;
  300. if (isset($new_value)) {
  301. $this->isDefaultRevision = (bool) $new_value;
  302. }
  303. // New entities should always ensure at least one default revision exists,
  304. // creating an entity without a default revision is an invalid state.
  305. return $this->isNew() || $return;
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. public function wasDefaultRevision() {
  311. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
  312. $entity_type = $this->getEntityType();
  313. if (!$entity_type->isRevisionable()) {
  314. return TRUE;
  315. }
  316. $revision_default_key = $entity_type->getRevisionMetadataKey('revision_default');
  317. $value = $this->isNew() || $this->get($revision_default_key)->value;
  318. return $value;
  319. }
  320. /**
  321. * {@inheritdoc}
  322. */
  323. public function isLatestRevision() {
  324. /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
  325. $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
  326. return $this->getLoadedRevisionId() == $storage->getLatestRevisionId($this->id());
  327. }
  328. /**
  329. * {@inheritdoc}
  330. */
  331. public function isLatestTranslationAffectedRevision() {
  332. /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
  333. $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
  334. return $this->getLoadedRevisionId() == $storage->getLatestTranslationAffectedRevisionId($this->id(), $this->language()->getId());
  335. }
  336. /**
  337. * {@inheritdoc}
  338. */
  339. public function isRevisionTranslationAffected() {
  340. return $this->hasField($this->revisionTranslationAffectedKey) ? $this->get($this->revisionTranslationAffectedKey)->value : TRUE;
  341. }
  342. /**
  343. * {@inheritdoc}
  344. */
  345. public function setRevisionTranslationAffected($affected) {
  346. if ($this->hasField($this->revisionTranslationAffectedKey)) {
  347. $this->set($this->revisionTranslationAffectedKey, $affected);
  348. }
  349. return $this;
  350. }
  351. /**
  352. * {@inheritdoc}
  353. */
  354. public function isRevisionTranslationAffectedEnforced() {
  355. return !empty($this->enforceRevisionTranslationAffected[$this->activeLangcode]);
  356. }
  357. /**
  358. * {@inheritdoc}
  359. */
  360. public function setRevisionTranslationAffectedEnforced($enforced) {
  361. $this->enforceRevisionTranslationAffected[$this->activeLangcode] = $enforced;
  362. return $this;
  363. }
  364. /**
  365. * {@inheritdoc}
  366. */
  367. public function isDefaultTranslation() {
  368. return $this->activeLangcode === LanguageInterface::LANGCODE_DEFAULT;
  369. }
  370. /**
  371. * {@inheritdoc}
  372. */
  373. public function getRevisionId() {
  374. return $this->getEntityKey('revision');
  375. }
  376. /**
  377. * {@inheritdoc}
  378. */
  379. public function isTranslatable() {
  380. // Check the bundle is translatable, the entity has a language defined, and
  381. // the site has more than one language.
  382. $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->entityTypeId);
  383. return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
  384. }
  385. /**
  386. * {@inheritdoc}
  387. */
  388. public function preSave(EntityStorageInterface $storage) {
  389. // An entity requiring validation should not be saved if it has not been
  390. // actually validated.
  391. if ($this->validationRequired && !$this->validated) {
  392. // @todo Make this an assertion in https://www.drupal.org/node/2408013.
  393. throw new \LogicException('Entity validation was skipped.');
  394. }
  395. else {
  396. $this->validated = FALSE;
  397. }
  398. parent::preSave($storage);
  399. }
  400. /**
  401. * {@inheritdoc}
  402. */
  403. public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
  404. }
  405. /**
  406. * {@inheritdoc}
  407. */
  408. public function postSave(EntityStorageInterface $storage, $update = TRUE) {
  409. parent::postSave($storage, $update);
  410. // Update the status of all saved translations.
  411. $removed = [];
  412. foreach ($this->translations as $langcode => &$data) {
  413. if ($data['status'] == static::TRANSLATION_REMOVED) {
  414. $removed[$langcode] = TRUE;
  415. }
  416. else {
  417. $data['status'] = static::TRANSLATION_EXISTING;
  418. }
  419. }
  420. $this->translations = array_diff_key($this->translations, $removed);
  421. // Reset the new revision flag.
  422. $this->newRevision = FALSE;
  423. // Reset the enforcement of the revision translation affected flag.
  424. $this->enforceRevisionTranslationAffected = [];
  425. }
  426. /**
  427. * {@inheritdoc}
  428. */
  429. public function validate() {
  430. $this->validated = TRUE;
  431. $violations = $this->getTypedData()->validate();
  432. return new EntityConstraintViolationList($this, iterator_to_array($violations));
  433. }
  434. /**
  435. * {@inheritdoc}
  436. */
  437. public function isValidationRequired() {
  438. return (bool) $this->validationRequired;
  439. }
  440. /**
  441. * {@inheritdoc}
  442. */
  443. public function setValidationRequired($required) {
  444. $this->validationRequired = $required;
  445. return $this;
  446. }
  447. /**
  448. * Clear entity translation object cache to remove stale references.
  449. */
  450. protected function clearTranslationCache() {
  451. foreach ($this->translations as &$translation) {
  452. unset($translation['entity']);
  453. }
  454. }
  455. /**
  456. * {@inheritdoc}
  457. */
  458. public function __sleep() {
  459. // Get the values of instantiated field objects, only serialize the values.
  460. foreach ($this->fields as $name => $fields) {
  461. foreach ($fields as $langcode => $field) {
  462. $this->values[$name][$langcode] = $field->getValue();
  463. }
  464. }
  465. $this->fields = [];
  466. $this->fieldDefinitions = NULL;
  467. $this->languages = NULL;
  468. $this->clearTranslationCache();
  469. return parent::__sleep();
  470. }
  471. /**
  472. * {@inheritdoc}
  473. */
  474. public function id() {
  475. return $this->getEntityKey('id');
  476. }
  477. /**
  478. * {@inheritdoc}
  479. */
  480. public function bundle() {
  481. return $this->getEntityKey('bundle');
  482. }
  483. /**
  484. * {@inheritdoc}
  485. */
  486. public function uuid() {
  487. return $this->getEntityKey('uuid');
  488. }
  489. /**
  490. * {@inheritdoc}
  491. */
  492. public function hasField($field_name) {
  493. return (bool) $this->getFieldDefinition($field_name);
  494. }
  495. /**
  496. * {@inheritdoc}
  497. */
  498. public function get($field_name) {
  499. if (!isset($this->fields[$field_name][$this->activeLangcode])) {
  500. return $this->getTranslatedField($field_name, $this->activeLangcode);
  501. }
  502. return $this->fields[$field_name][$this->activeLangcode];
  503. }
  504. /**
  505. * Gets a translated field.
  506. *
  507. * @return \Drupal\Core\Field\FieldItemListInterface
  508. */
  509. protected function getTranslatedField($name, $langcode) {
  510. if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
  511. throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
  512. }
  513. // Populate $this->fields to speed-up further look-ups and to keep track of
  514. // fields objects, possibly holding changes to field values.
  515. if (!isset($this->fields[$name][$langcode])) {
  516. $definition = $this->getFieldDefinition($name);
  517. if (!$definition) {
  518. throw new \InvalidArgumentException("Field $name is unknown.");
  519. }
  520. // Non-translatable fields are always stored with
  521. // LanguageInterface::LANGCODE_DEFAULT as key.
  522. $default = $langcode == LanguageInterface::LANGCODE_DEFAULT;
  523. if (!$default && !$definition->isTranslatable()) {
  524. if (!isset($this->fields[$name][LanguageInterface::LANGCODE_DEFAULT])) {
  525. $this->fields[$name][LanguageInterface::LANGCODE_DEFAULT] = $this->getTranslatedField($name, LanguageInterface::LANGCODE_DEFAULT);
  526. }
  527. $this->fields[$name][$langcode] = &$this->fields[$name][LanguageInterface::LANGCODE_DEFAULT];
  528. }
  529. else {
  530. $value = NULL;
  531. if (isset($this->values[$name][$langcode])) {
  532. $value = $this->values[$name][$langcode];
  533. }
  534. $field = \Drupal::service('plugin.manager.field.field_type')->createFieldItemList($this->getTranslation($langcode), $name, $value);
  535. if ($default) {
  536. // $this->defaultLangcode might not be set if we are initializing the
  537. // default language code cache, in which case there is no valid
  538. // langcode to assign.
  539. $field_langcode = isset($this->defaultLangcode) ? $this->defaultLangcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
  540. }
  541. else {
  542. $field_langcode = $langcode;
  543. }
  544. $field->setLangcode($field_langcode);
  545. $this->fields[$name][$langcode] = $field;
  546. }
  547. }
  548. return $this->fields[$name][$langcode];
  549. }
  550. /**
  551. * {@inheritdoc}
  552. */
  553. public function set($name, $value, $notify = TRUE) {
  554. // Assign the value on the child and overrule notify such that we get
  555. // notified to handle changes afterwards. We can ignore notify as there is
  556. // no parent to notify anyway.
  557. $this->get($name)->setValue($value, TRUE);
  558. return $this;
  559. }
  560. /**
  561. * {@inheritdoc}
  562. */
  563. public function getFields($include_computed = TRUE) {
  564. $fields = [];
  565. foreach ($this->getFieldDefinitions() as $name => $definition) {
  566. if ($include_computed || !$definition->isComputed()) {
  567. $fields[$name] = $this->get($name);
  568. }
  569. }
  570. return $fields;
  571. }
  572. /**
  573. * {@inheritdoc}
  574. */
  575. public function getTranslatableFields($include_computed = TRUE) {
  576. $fields = [];
  577. foreach ($this->getFieldDefinitions() as $name => $definition) {
  578. if (($include_computed || !$definition->isComputed()) && $definition->isTranslatable()) {
  579. $fields[$name] = $this->get($name);
  580. }
  581. }
  582. return $fields;
  583. }
  584. /**
  585. * {@inheritdoc}
  586. */
  587. public function getIterator() {
  588. return new \ArrayIterator($this->getFields());
  589. }
  590. /**
  591. * {@inheritdoc}
  592. */
  593. public function getFieldDefinition($name) {
  594. if (!isset($this->fieldDefinitions)) {
  595. $this->getFieldDefinitions();
  596. }
  597. if (isset($this->fieldDefinitions[$name])) {
  598. return $this->fieldDefinitions[$name];
  599. }
  600. }
  601. /**
  602. * {@inheritdoc}
  603. */
  604. public function getFieldDefinitions() {
  605. if (!isset($this->fieldDefinitions)) {
  606. $this->fieldDefinitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($this->entityTypeId, $this->bundle());
  607. }
  608. return $this->fieldDefinitions;
  609. }
  610. /**
  611. * {@inheritdoc}
  612. */
  613. public function toArray() {
  614. $values = [];
  615. foreach ($this->getFields() as $name => $property) {
  616. $values[$name] = $property->getValue();
  617. }
  618. return $values;
  619. }
  620. /**
  621. * {@inheritdoc}
  622. */
  623. public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
  624. if ($operation == 'create') {
  625. return $this->entityTypeManager()
  626. ->getAccessControlHandler($this->entityTypeId)
  627. ->createAccess($this->bundle(), $account, [], $return_as_object);
  628. }
  629. return $this->entityTypeManager()
  630. ->getAccessControlHandler($this->entityTypeId)
  631. ->access($this, $operation, $account, $return_as_object);
  632. }
  633. /**
  634. * {@inheritdoc}
  635. */
  636. public function language() {
  637. $language = NULL;
  638. if ($this->activeLangcode != LanguageInterface::LANGCODE_DEFAULT) {
  639. if (!isset($this->languages[$this->activeLangcode])) {
  640. $this->getLanguages();
  641. }
  642. $language = $this->languages[$this->activeLangcode];
  643. }
  644. else {
  645. // @todo Avoid this check by getting the language from the language
  646. // manager directly in https://www.drupal.org/node/2303877.
  647. if (!isset($this->languages[$this->defaultLangcode])) {
  648. $this->getLanguages();
  649. }
  650. $language = $this->languages[$this->defaultLangcode];
  651. }
  652. return $language;
  653. }
  654. /**
  655. * Populates the local cache for the default language code.
  656. */
  657. protected function setDefaultLangcode() {
  658. // Get the language code if the property exists.
  659. // Try to read the value directly from the list of entity keys which got
  660. // initialized in __construct(). This avoids creating a field item object.
  661. if (isset($this->translatableEntityKeys['langcode'][$this->activeLangcode])) {
  662. $this->defaultLangcode = $this->translatableEntityKeys['langcode'][$this->activeLangcode];
  663. }
  664. elseif ($this->hasField($this->langcodeKey) && ($item = $this->get($this->langcodeKey)) && isset($item->language)) {
  665. $this->defaultLangcode = $item->language->getId();
  666. $this->translatableEntityKeys['langcode'][$this->activeLangcode] = $this->defaultLangcode;
  667. }
  668. if (empty($this->defaultLangcode)) {
  669. // Make sure we return a proper language object, if the entity has a
  670. // langcode field, default to the site's default language.
  671. if ($this->hasField($this->langcodeKey)) {
  672. $this->defaultLangcode = $this->languageManager()->getDefaultLanguage()->getId();
  673. }
  674. else {
  675. $this->defaultLangcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
  676. }
  677. }
  678. // This needs to be initialized manually as it is skipped when instantiating
  679. // the language field object to avoid infinite recursion.
  680. if (!empty($this->fields[$this->langcodeKey])) {
  681. $this->fields[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT]->setLangcode($this->defaultLangcode);
  682. }
  683. }
  684. /**
  685. * Updates language for already instantiated fields.
  686. */
  687. protected function updateFieldLangcodes($langcode) {
  688. foreach ($this->fields as $name => $items) {
  689. if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) {
  690. $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode);
  691. }
  692. }
  693. }
  694. /**
  695. * {@inheritdoc}
  696. */
  697. public function onChange($name) {
  698. // Check if the changed name is the value of any entity keys and if any of
  699. // those values are currently cached, if so, reset it. Exclude the bundle
  700. // from that check, as it ready only and must not change, unsetting it could
  701. // lead to recursions.
  702. foreach (array_keys($this->getEntityType()->getKeys(), $name, TRUE) as $key) {
  703. if ($key != 'bundle') {
  704. if (isset($this->entityKeys[$key])) {
  705. unset($this->entityKeys[$key]);
  706. }
  707. elseif (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
  708. unset($this->translatableEntityKeys[$key][$this->activeLangcode]);
  709. }
  710. // If the revision identifier field is being populated with the original
  711. // value, we need to make sure the "new revision" flag is reset
  712. // accordingly.
  713. if ($key === 'revision' && $this->getRevisionId() == $this->getLoadedRevisionId() && !$this->isNew()) {
  714. $this->newRevision = FALSE;
  715. }
  716. }
  717. }
  718. switch ($name) {
  719. case $this->langcodeKey:
  720. if ($this->isDefaultTranslation()) {
  721. // Update the default internal language cache.
  722. $this->setDefaultLangcode();
  723. if (isset($this->translations[$this->defaultLangcode])) {
  724. $message = new FormattableMarkup('A translation already exists for the specified language (@langcode).', ['@langcode' => $this->defaultLangcode]);
  725. throw new \InvalidArgumentException($message);
  726. }
  727. $this->updateFieldLangcodes($this->defaultLangcode);
  728. }
  729. else {
  730. // @todo Allow the translation language to be changed. See
  731. // https://www.drupal.org/node/2443989.
  732. $items = $this->get($this->langcodeKey);
  733. if ($items->value != $this->activeLangcode) {
  734. $items->setValue($this->activeLangcode, FALSE);
  735. $message = new FormattableMarkup('The translation language cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
  736. throw new \LogicException($message);
  737. }
  738. }
  739. break;
  740. case $this->defaultLangcodeKey:
  741. // @todo Use a standard method to make the default_langcode field
  742. // read-only. See https://www.drupal.org/node/2443991.
  743. if (isset($this->values[$this->defaultLangcodeKey]) && $this->get($this->defaultLangcodeKey)->value != $this->isDefaultTranslation()) {
  744. $this->get($this->defaultLangcodeKey)->setValue($this->isDefaultTranslation(), FALSE);
  745. $message = new FormattableMarkup('The default translation flag cannot be changed (@langcode).', ['@langcode' => $this->activeLangcode]);
  746. throw new \LogicException($message);
  747. }
  748. break;
  749. case $this->revisionTranslationAffectedKey:
  750. // If the revision translation affected flag is being set then enforce
  751. // its value.
  752. $this->setRevisionTranslationAffectedEnforced(TRUE);
  753. break;
  754. }
  755. }
  756. /**
  757. * {@inheritdoc}
  758. */
  759. public function getTranslation($langcode) {
  760. // Ensure we always use the default language code when dealing with the
  761. // original entity language.
  762. if ($langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode == $this->defaultLangcode) {
  763. $langcode = LanguageInterface::LANGCODE_DEFAULT;
  764. }
  765. // Populate entity translation object cache so it will be available for all
  766. // translation objects.
  767. if (!isset($this->translations[$this->activeLangcode]['entity'])) {
  768. $this->translations[$this->activeLangcode]['entity'] = $this;
  769. }
  770. // If we already have a translation object for the specified language we can
  771. // just return it.
  772. if (isset($this->translations[$langcode]['entity'])) {
  773. $translation = $this->translations[$langcode]['entity'];
  774. }
  775. // Otherwise if an existing translation language was specified we need to
  776. // instantiate the related translation.
  777. elseif (isset($this->translations[$langcode])) {
  778. $translation = $this->initializeTranslation($langcode);
  779. $this->translations[$langcode]['entity'] = $translation;
  780. }
  781. if (empty($translation)) {
  782. throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
  783. }
  784. return $translation;
  785. }
  786. /**
  787. * {@inheritdoc}
  788. */
  789. public function getUntranslated() {
  790. return $this->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
  791. }
  792. /**
  793. * Instantiates a translation object for an existing translation.
  794. *
  795. * The translated entity will be a clone of the current entity with the
  796. * specified $langcode. All translations share the same field data structures
  797. * to ensure that all of them deal with fresh data.
  798. *
  799. * @param string $langcode
  800. * The language code for the requested translation.
  801. *
  802. * @return \Drupal\Core\Entity\EntityInterface
  803. * The translation object. The content properties of the translation object
  804. * are stored as references to the main entity.
  805. */
  806. protected function initializeTranslation($langcode) {
  807. // If the requested translation is valid, clone it with the current language
  808. // as the active language. The $translationInitialize flag triggers a
  809. // shallow (non-recursive) clone.
  810. $this->translationInitialize = TRUE;
  811. $translation = clone $this;
  812. $this->translationInitialize = FALSE;
  813. $translation->activeLangcode = $langcode;
  814. // Ensure that changes to fields, values and translations are propagated
  815. // to all the translation objects.
  816. // @todo Consider converting these to ArrayObject.
  817. $translation->values = &$this->values;
  818. $translation->fields = &$this->fields;
  819. $translation->translations = &$this->translations;
  820. $translation->enforceIsNew = &$this->enforceIsNew;
  821. $translation->newRevision = &$this->newRevision;
  822. $translation->entityKeys = &$this->entityKeys;
  823. $translation->translatableEntityKeys = &$this->translatableEntityKeys;
  824. $translation->translationInitialize = FALSE;
  825. $translation->typedData = NULL;
  826. $translation->loadedRevisionId = &$this->loadedRevisionId;
  827. $translation->isDefaultRevision = &$this->isDefaultRevision;
  828. $translation->enforceRevisionTranslationAffected = &$this->enforceRevisionTranslationAffected;
  829. $translation->isSyncing = &$this->isSyncing;
  830. return $translation;
  831. }
  832. /**
  833. * {@inheritdoc}
  834. */
  835. public function hasTranslation($langcode) {
  836. if ($langcode == $this->defaultLangcode) {
  837. $langcode = LanguageInterface::LANGCODE_DEFAULT;
  838. }
  839. return !empty($this->translations[$langcode]['status']);
  840. }
  841. /**
  842. * {@inheritdoc}
  843. */
  844. public function isNewTranslation() {
  845. return $this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_CREATED;
  846. }
  847. /**
  848. * {@inheritdoc}
  849. */
  850. public function addTranslation($langcode, array $values = []) {
  851. // Make sure we do not attempt to create a translation if an invalid
  852. // language is specified or the entity cannot be translated.
  853. $this->getLanguages();
  854. if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
  855. throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
  856. }
  857. if ($this->languages[$this->defaultLangcode]->isLocked()) {
  858. throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
  859. }
  860. // Initialize the translation object.
  861. /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
  862. $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
  863. $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
  864. return $storage->createTranslation($this, $langcode, $values);
  865. }
  866. /**
  867. * {@inheritdoc}
  868. */
  869. public function removeTranslation($langcode) {
  870. if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
  871. foreach ($this->getFieldDefinitions() as $name => $definition) {
  872. if ($definition->isTranslatable()) {
  873. unset($this->values[$name][$langcode]);
  874. unset($this->fields[$name][$langcode]);
  875. }
  876. }
  877. // If removing a translation which has not been saved yet, then we have
  878. // to remove it completely so that ::getTranslationStatus returns the
  879. // proper status.
  880. if ($this->translations[$langcode]['status'] == static::TRANSLATION_CREATED) {
  881. unset($this->translations[$langcode]);
  882. }
  883. else {
  884. if ($this->translations[$langcode]['status'] == static::TRANSLATION_EXISTING) {
  885. $this->translations[$langcode]['status_existed'] = TRUE;
  886. }
  887. $this->translations[$langcode]['status'] = static::TRANSLATION_REMOVED;
  888. }
  889. }
  890. else {
  891. throw new \InvalidArgumentException("The specified translation ($langcode) cannot be removed.");
  892. }
  893. }
  894. /**
  895. * {@inheritdoc}
  896. */
  897. public function getTranslationStatus($langcode) {
  898. if ($langcode == $this->defaultLangcode) {
  899. $langcode = LanguageInterface::LANGCODE_DEFAULT;
  900. }
  901. return isset($this->translations[$langcode]) ? $this->translations[$langcode]['status'] : NULL;
  902. }
  903. /**
  904. * {@inheritdoc}
  905. */
  906. public function getTranslationLanguages($include_default = TRUE) {
  907. $translations = array_filter($this->translations, function ($translation) {
  908. return $translation['status'];
  909. });
  910. unset($translations[LanguageInterface::LANGCODE_DEFAULT]);
  911. if ($include_default) {
  912. $translations[$this->defaultLangcode] = TRUE;
  913. }
  914. // Now load language objects based upon translation langcodes.
  915. return array_intersect_key($this->getLanguages(), $translations);
  916. }
  917. /**
  918. * Updates the original values with the interim changes.
  919. */
  920. public function updateOriginalValues() {
  921. if (!$this->fields) {
  922. return;
  923. }
  924. foreach ($this->getFieldDefinitions() as $name => $definition) {
  925. if (!$definition->isComputed() && !empty($this->fields[$name])) {
  926. foreach ($this->fields[$name] as $langcode => $item) {
  927. $item->filterEmptyItems();
  928. $this->values[$name][$langcode] = $item->getValue();
  929. }
  930. }
  931. }
  932. }
  933. /**
  934. * Implements the magic method for getting object properties.
  935. *
  936. * @todo: A lot of code still uses non-fields (e.g. $entity->content in view
  937. * builders) by reference. Clean that up.
  938. */
  939. public function &__get($name) {
  940. // If this is an entity field, handle it accordingly. We first check whether
  941. // a field object has been already created. If not, we create one.
  942. if (isset($this->fields[$name][$this->activeLangcode])) {
  943. return $this->fields[$name][$this->activeLangcode];
  944. }
  945. // Inline getFieldDefinition() to speed things up.
  946. if (!isset($this->fieldDefinitions)) {
  947. $this->getFieldDefinitions();
  948. }
  949. if (isset($this->fieldDefinitions[$name])) {
  950. $return = $this->getTranslatedField($name, $this->activeLangcode);
  951. return $return;
  952. }
  953. // Else directly read/write plain values. That way, non-field entity
  954. // properties can always be accessed directly.
  955. if (!isset($this->values[$name])) {
  956. $this->values[$name] = NULL;
  957. }
  958. return $this->values[$name];
  959. }
  960. /**
  961. * Implements the magic method for setting object properties.
  962. *
  963. * Uses default language always.
  964. */
  965. public function __set($name, $value) {
  966. // Inline getFieldDefinition() to speed things up.
  967. if (!isset($this->fieldDefinitions)) {
  968. $this->getFieldDefinitions();
  969. }
  970. // Handle Field API fields.
  971. if (isset($this->fieldDefinitions[$name])) {
  972. // Support setting values via property objects.
  973. if ($value instanceof TypedDataInterface) {
  974. $value = $value->getValue();
  975. }
  976. // If a FieldItemList object already exists, set its value.
  977. if (isset($this->fields[$name][$this->activeLangcode])) {
  978. $this->fields[$name][$this->activeLangcode]->setValue($value);
  979. }
  980. // If not, create one.
  981. else {
  982. $this->getTranslatedField($name, $this->activeLangcode)->setValue($value);
  983. }
  984. }
  985. // The translations array is unset when cloning the entity object, we just
  986. // need to restore it.
  987. elseif ($name == 'translations') {
  988. $this->translations = $value;
  989. }
  990. // Directly write non-field values.
  991. else {
  992. $this->values[$name] = $value;
  993. }
  994. }
  995. /**
  996. * Implements the magic method for isset().
  997. */
  998. public function __isset($name) {
  999. // "Official" Field API fields are always set. For non-field properties,
  1000. // check the internal values.
  1001. return $this->hasField($name) ? TRUE : isset($this->values[$name]);
  1002. }
  1003. /**
  1004. * Implements the magic method for unset().
  1005. */
  1006. public function __unset($name) {
  1007. // Unsetting a field means emptying it.
  1008. if ($this->hasField($name)) {
  1009. $this->get($name)->setValue([]);
  1010. }
  1011. // For non-field properties, unset the internal value.
  1012. else {
  1013. unset($this->values[$name]);
  1014. }
  1015. }
  1016. /**
  1017. * {@inheritdoc}
  1018. */
  1019. public function createDuplicate() {
  1020. if ($this->translations[$this->activeLangcode]['status'] == static::TRANSLATION_REMOVED) {
  1021. throw new \InvalidArgumentException("The entity object refers to a removed translation ({$this->activeLangcode}) and cannot be manipulated.");
  1022. }
  1023. $duplicate = clone $this;
  1024. $entity_type = $this->getEntityType();
  1025. if ($entity_type->hasKey('id')) {
  1026. $duplicate->{$entity_type->getKey('id')}->value = NULL;
  1027. }
  1028. $duplicate->enforceIsNew();
  1029. // Check if the entity type supports UUIDs and generate a new one if so.
  1030. if ($entity_type->hasKey('uuid')) {
  1031. $duplicate->{$entity_type->getKey('uuid')}->value = $this->uuidGenerator()->generate();
  1032. }
  1033. // Check whether the entity type supports revisions and initialize it if so.
  1034. if ($entity_type->isRevisionable()) {
  1035. $duplicate->{$entity_type->getKey('revision')}->value = NULL;
  1036. $duplicate->loadedRevisionId = NULL;
  1037. }
  1038. return $duplicate;
  1039. }
  1040. /**
  1041. * Magic method: Implements a deep clone.
  1042. */
  1043. public function __clone() {
  1044. // Avoid deep-cloning when we are initializing a translation object, since
  1045. // it will represent the same entity, only with a different active language.
  1046. if ($this->translationInitialize) {
  1047. return;
  1048. }
  1049. // The translation is a different object, and needs its own TypedData
  1050. // adapter object.
  1051. $this->typedData = NULL;
  1052. $definitions = $this->getFieldDefinitions();
  1053. // The translation cache has to be cleared before cloning the fields
  1054. // below so that the call to getTranslation() does not re-use the
  1055. // translation objects of the old entity but instead creates new
  1056. // translation objects from the newly cloned entity. Otherwise the newly
  1057. // cloned field item lists would hold references to the old translation
  1058. // objects in their $parent property after the call to setContext().
  1059. $this->clearTranslationCache();
  1060. // Because the new translation objects that are created below are
  1061. // themselves created by *cloning* the newly cloned entity we need to
  1062. // make sure that the references to property values are properly cloned
  1063. // before cloning the fields. Otherwise calling
  1064. // $items->getEntity()->isNew(), for example, would return the
  1065. // $enforceIsNew value of the old entity.
  1066. // Ensure the translations array is actually cloned by overwriting the
  1067. // original reference with one pointing to a copy of the array.
  1068. $translations = $this->translations;
  1069. $this->translations = &$translations;
  1070. // Ensure that the following properties are actually cloned by
  1071. // overwriting the original references with ones pointing to copies of
  1072. // them: enforceIsNew, newRevision, loadedRevisionId, fields, entityKeys,
  1073. // translatableEntityKeys, values, isDefaultRevision and
  1074. // enforceRevisionTranslationAffected.
  1075. $enforce_is_new = $this->enforceIsNew;
  1076. $this->enforceIsNew = &$enforce_is_new;
  1077. $new_revision = $this->newRevision;
  1078. $this->newRevision = &$new_revision;
  1079. $original_revision_id = $this->loadedRevisionId;
  1080. $this->loadedRevisionId = &$original_revision_id;
  1081. $fields = $this->fields;
  1082. $this->fields = &$fields;
  1083. $entity_keys = $this->entityKeys;
  1084. $this->entityKeys = &$entity_keys;
  1085. $translatable_entity_keys = $this->translatableEntityKeys;
  1086. $this->translatableEntityKeys = &$translatable_entity_keys;
  1087. $values = $this->values;
  1088. $this->values = &$values;
  1089. $default_revision = $this->isDefaultRevision;
  1090. $this->isDefaultRevision = &$default_revision;
  1091. $is_revision_translation_affected_enforced = $this->enforceRevisionTranslationAffected;
  1092. $this->enforceRevisionTranslationAffected = &$is_revision_translation_affected_enforced;
  1093. $is_syncing = $this->isSyncing;
  1094. $this->isSyncing = &$is_syncing;
  1095. foreach ($this->fields as $name => $fields_by_langcode) {
  1096. $this->fields[$name] = [];
  1097. // Untranslatable fields may have multiple references for the same field
  1098. // object keyed by language. To avoid creating different field objects
  1099. // we retain just the original value, as references will be recreated
  1100. // later as needed.
  1101. if (!$definitions[$name]->isTranslatable() && count($fields_by_langcode) > 1) {
  1102. $fields_by_langcode = array_intersect_key($fields_by_langcode, [LanguageInterface::LANGCODE_DEFAULT => TRUE]);
  1103. }
  1104. foreach ($fields_by_langcode as $langcode => $items) {
  1105. $this->fields[$name][$langcode] = clone $items;
  1106. $this->fields[$name][$langcode]->setContext($name, $this->getTranslation($langcode)->getTypedData());
  1107. }
  1108. }
  1109. }
  1110. /**
  1111. * {@inheritdoc}
  1112. */
  1113. public function label() {
  1114. $label = NULL;
  1115. $entity_type = $this->getEntityType();
  1116. if (($label_callback = $entity_type->get('label_callback')) && is_callable($label_callback)) {
  1117. @trigger_error('Entity type ' . $this->getEntityTypeId() . ' defines a label callback. Support for that is deprecated in drupal:8.0.0 and will be removed in drupal:9.0.0. Override the EntityInterface::label() method instead. See https://www.drupal.org/node/3050794', E_USER_DEPRECATED);
  1118. $label = call_user_func($label_callback, $this);
  1119. }
  1120. elseif (($label_key = $entity_type->getKey('label'))) {
  1121. $label = $this->getEntityKey('label');
  1122. }
  1123. return $label;
  1124. }
  1125. /**
  1126. * {@inheritdoc}
  1127. */
  1128. public function referencedEntities() {
  1129. $referenced_entities = [];
  1130. // Gather a list of referenced entities.
  1131. foreach ($this->getFields() as $field_items) {
  1132. foreach ($field_items as $field_item) {
  1133. // Loop over all properties of a field item.
  1134. foreach ($field_item->getProperties(TRUE) as $property) {
  1135. if ($property instanceof EntityReference && $entity = $property->getValue()) {
  1136. $referenced_entities[] = $entity;
  1137. }
  1138. }
  1139. }
  1140. }
  1141. return $referenced_entities;
  1142. }
  1143. /**
  1144. * Gets the value of the given entity key, if defined.
  1145. *
  1146. * @param string $key
  1147. * Name of the entity key, for example id, revision or bundle.
  1148. *
  1149. * @return mixed
  1150. * The value of the entity key, NULL if not defined.
  1151. */
  1152. protected function getEntityKey($key) {
  1153. // If the value is known already, return it.
  1154. if (isset($this->entityKeys[$key])) {
  1155. return $this->entityKeys[$key];
  1156. }
  1157. if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
  1158. return $this->translatableEntityKeys[$key][$this->activeLangcode];
  1159. }
  1160. // Otherwise fetch the value by creating a field object.
  1161. $value = NULL;
  1162. if ($this->getEntityType()->hasKey($key)) {
  1163. $field_name = $this->getEntityType()->getKey($key);
  1164. $definition = $this->getFieldDefinition($field_name);
  1165. $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
  1166. $value = $this->get($field_name)->$property;
  1167. // Put it in the right array, depending on whether it is translatable.
  1168. if ($definition->isTranslatable()) {
  1169. $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
  1170. }
  1171. else {
  1172. $this->entityKeys[$key] = $value;
  1173. }
  1174. }
  1175. else {
  1176. $this->entityKeys[$key] = $value;
  1177. }
  1178. return $value;
  1179. }
  1180. /**
  1181. * {@inheritdoc}
  1182. */
  1183. public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  1184. $fields = [];
  1185. if ($entity_type->hasKey('id')) {
  1186. $fields[$entity_type->getKey('id')] = BaseFieldDefinition::create('integer')
  1187. ->setLabel(new TranslatableMarkup('ID'))
  1188. ->setReadOnly(TRUE)
  1189. ->setSetting('unsigned', TRUE);
  1190. }
  1191. if ($entity_type->hasKey('uuid')) {
  1192. $fields[$entity_type->getKey('uuid')] = BaseFieldDefinition::create('uuid')
  1193. ->setLabel(new TranslatableMarkup('UUID'))
  1194. ->setReadOnly(TRUE);
  1195. }
  1196. if ($entity_type->hasKey('revision')) {
  1197. $fields[$entity_type->getKey('revision')] = BaseFieldDefinition::create('integer')
  1198. ->setLabel(new TranslatableMarkup('Revision ID'))
  1199. ->setReadOnly(TRUE)
  1200. ->setSetting('unsigned', TRUE);
  1201. }
  1202. if ($entity_type->hasKey('langcode')) {
  1203. $fields[$entity_type->getKey('langcode')] = BaseFieldDefinition::create('language')
  1204. ->setLabel(new TranslatableMarkup('Language'))
  1205. ->setDisplayOptions('view', [
  1206. 'region' => 'hidden',
  1207. ])
  1208. ->setDisplayOptions('form', [
  1209. 'type' => 'language_select',
  1210. 'weight' => 2,
  1211. ]);
  1212. if ($entity_type->isRevisionable()) {
  1213. $fields[$entity_type->getKey('langcode')]->setRevisionable(TRUE);
  1214. }
  1215. if ($entity_type->isTranslatable()) {
  1216. $fields[$entity_type->getKey('langcode')]->setTranslatable(TRUE);
  1217. }
  1218. }
  1219. if ($entity_type->hasKey('bundle')) {
  1220. if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
  1221. $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('entity_reference')
  1222. ->setLabel($entity_type->getBundleLabel())
  1223. ->setSetting('target_type', $bundle_entity_type_id)
  1224. ->setRequired(TRUE)
  1225. ->setReadOnly(TRUE);
  1226. }
  1227. else {
  1228. $fields[$entity_type->getKey('bundle')] = BaseFieldDefinition::create('string')
  1229. ->setLabel($entity_type->getBundleLabel())
  1230. ->setRequired(TRUE)
  1231. ->setReadOnly(TRUE);
  1232. }
  1233. }
  1234. return $fields;
  1235. }
  1236. /**
  1237. * {@inheritdoc}
  1238. */
  1239. public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  1240. return [];
  1241. }
  1242. /**
  1243. * Returns an array of field names to skip in ::hasTranslationChanges.
  1244. *
  1245. * @return array
  1246. * An array of field names.
  1247. */
  1248. protected function getFieldsToSkipFromTranslationChangesCheck() {
  1249. $bundle = $this->bundle();
  1250. if (!isset(static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle])) {
  1251. static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle] = $this->traitGetFieldsToSkipFromTranslationChangesCheck($this);
  1252. }
  1253. return static::$fieldsToSkipFromTranslationChangesCheck[$this->entityTypeId][$bundle];
  1254. }
  1255. /**
  1256. * {@inheritdoc}
  1257. */
  1258. public function hasTranslationChanges() {
  1259. if ($this->isNew()) {
  1260. return TRUE;
  1261. }
  1262. // $this->original only exists during save. See
  1263. // \Drupal\Core\Entity\EntityStorageBase::save(). If it exists we re-use it
  1264. // here for performance reasons.
  1265. /** @var \Drupal\Core\Entity\ContentEntityBase $original */
  1266. $original = $this->original ? $this->original : NULL;
  1267. if (!$original) {
  1268. $id = $this->getOriginalId() !== NULL ? $this->getOriginalId() : $this->id();
  1269. $original = $this->entityTypeManager()->getStorage($this->getEntityTypeId())->loadUnchanged($id);
  1270. }
  1271. // If the current translation has just been added, we have a change.
  1272. $translated = count($this->translations) > 1;
  1273. if ($translated && !$original->hasTranslation($this->activeLangcode)) {
  1274. return TRUE;
  1275. }
  1276. // Compare field item current values with the original ones to determine
  1277. // whether we have changes. If a field is not translatable and the entity is
  1278. // translated we skip it because, depending on the use case, it would make
  1279. // sense to mark all translations as changed or none of them. We skip also
  1280. // computed fields as comparing them with their original values might not be
  1281. // possible or be meaningless.
  1282. /** @var \Drupal\Core\Entity\ContentEntityBase $translation */
  1283. $translation = $original->getTranslation($this->activeLangcode);
  1284. $langcode = $this->language()->getId();
  1285. // The list of fields to skip from the comparision.
  1286. $skip_fields = $this->getFieldsToSkipFromTranslationChangesCheck();
  1287. // We also check untranslatable fields, so that a change to those will mark
  1288. // all translations as affected, unless they are configured to only affect
  1289. // the default translation.
  1290. $skip_untranslatable_fields = !$this->isDefaultTranslation() && $this->isDefaultTranslationAffectedOnly();
  1291. foreach ($this->getFieldDefinitions() as $field_name => $definition) {
  1292. // @todo Avoid special-casing the following fields. See
  1293. // https://www.drupal.org/node/2329253.
  1294. if (in_array($field_name, $skip_fields, TRUE) || ($skip_untranslatable_fields && !$definition->isTranslatable())) {
  1295. continue;
  1296. }
  1297. $items = $this->get($field_name)->filterEmptyItems();
  1298. $original_items = $translation->get($field_name)->filterEmptyItems();
  1299. if ($items->hasAffectingChanges($original_items, $langcode)) {
  1300. return TRUE;
  1301. }
  1302. }
  1303. return FALSE;
  1304. }
  1305. /**
  1306. * {@inheritdoc}
  1307. */
  1308. public function isDefaultTranslationAffectedOnly() {
  1309. $bundle_name = $this->bundle();
  1310. $bundle_info = \Drupal::service('entity_type.bundle.info')
  1311. ->getBundleInfo($this->getEntityTypeId());
  1312. return !empty($bundle_info[$bundle_name]['untranslatable_fields.default_translation_affected']);
  1313. }
  1314. }