View source
<?php
namespace Drupal\social_demo\Plugin\DemoContent;
use Drupal\social_demo\DemoNode;
use Drupal\taxonomy\TermStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\social_demo\DemoContentParserInterface;
use Drupal\user\UserStorageInterface;
use Drupal\file\FileStorageInterface;
use Drupal\Core\Entity\EntityStorageInterface;
class Topic extends DemoNode {
protected $fileStorage;
protected $termStorage;
public function __construct(array $configuration, $plugin_id, $plugin_definition, DemoContentParserInterface $parser, UserStorageInterface $user_storage, EntityStorageInterface $group_storage, FileStorageInterface $file_storage, TermStorageInterface $term_storage) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $parser, $user_storage, $group_storage);
$this->fileStorage = $file_storage;
$this->termStorage = $term_storage;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('social_demo.yaml_parser'), $container
->get('entity_type.manager')
->getStorage('user'), $container
->get('entity_type.manager')
->getStorage('group'), $container
->get('entity_type.manager')
->getStorage('file'), $container
->get('entity_type.manager')
->getStorage('taxonomy_term'));
}
protected function getEntry(array $item) {
$entry = parent::getEntry($item);
$entry['field_content_visibility'] = $item['field_content_visibility'];
if (!empty($item['field_topic_type'])) {
$entry['field_topic_type'] = $this
->prepareTopicType($item['field_topic_type']);
}
if (!empty($item['image'])) {
$entry['field_topic_image'] = $this
->prepareImage($item['image'], $item['image_alt']);
}
if (!empty($item['field_files'])) {
$entry['field_files'] = $this
->prepareAttachment($item['field_files']);
}
return $entry;
}
protected function prepareAttachment(array $files) {
$attachments = NULL;
foreach ($files as $file) {
$description = '';
if (is_array($file)) {
$uuid = key($file);
$description = current($file);
}
else {
$uuid = $file;
}
$object = $this->fileStorage
->loadByProperties([
'uuid' => $uuid,
]);
if ($object) {
$properties = [
'target_id' => current($object)
->id(),
'description' => $description,
];
$attachments[] = $properties;
}
}
return $attachments;
}
protected function prepareTopicType($name) {
$value = NULL;
$terms = $this->termStorage
->loadByProperties([
'name' => $name,
]);
if ($terms) {
$value = [
[
'target_id' => current($terms)
->id(),
],
];
}
return $value;
}
}