LingotekContentMetadataFieldItemList.php in Lingotek Translation 3.1.x
File
src/Plugin/Field/LingotekContentMetadataFieldItemList.php
View source
<?php
namespace Drupal\lingotek\Plugin\Field;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\lingotek\Entity\LingotekContentMetadata;
class LingotekContentMetadataFieldItemList extends EntityReferenceFieldItemList {
protected function getContentMetadata() {
$entity = $this
->getEntity();
$config_service = \Drupal::service('lingotek.configuration');
if (!$config_service
->isEnabled($entity
->getEntityTypeId(), $entity
->bundle())) {
return NULL;
}
if ($entity
->id()) {
$metadata_result = \Drupal::entityTypeManager()
->getStorage('lingotek_content_metadata')
->getQuery()
->condition('content_entity_type_id', $entity
->getEntityTypeId())
->condition('content_entity_id', $entity
->id())
->execute();
if ($metadata_id = key($metadata_result)) {
$metadata = \Drupal::entityTypeManager()
->getStorage('lingotek_content_metadata')
->load($metadata_id);
return $metadata;
}
}
$metadata = LingotekContentMetadata::create();
if ($entity
->id()) {
$metadata
->setEntity($entity);
$metadata
->save();
}
}
public function get($index) {
if ($index !== 0) {
throw new \InvalidArgumentException('An entity can not have multiple moderation states at the same time.');
}
if (isset($this->list[$index]) && !$this->list[$index]
->isEmpty()) {
return $this->list[$index];
}
$this
->computeLingotekMetadataFieldItemList();
return isset($this->list[$index]) ? $this->list[$index] : NULL;
}
public function getIterator() {
$this
->computeLingotekMetadataFieldItemList();
return parent::getIterator();
}
protected function computeLingotekMetadataFieldItemList() {
$index = 0;
if (!isset($this->list[$index]) || $this->list[$index]
->isEmpty()) {
$metadata = $this
->getContentMetadata();
if ($metadata) {
$this->list[$index] = $this
->createItem($index, [
'entity' => $metadata,
]);
}
}
}
public function preSave() {
$metadata = $this
->getContentMetadata();
if ($metadata && !$metadata
->getContentEntityId()) {
$metadata
->setEntity($this
->getEntity());
}
parent::preSave();
}
}