View source
<?php
namespace Drupal\social_demo;
use Drupal\file\FileInterface;
use Drupal\image_widget_crop\ImageWidgetCropManager;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drush\Log\LogLevel;
use Drupal\crop\Entity\CropType;
abstract class DemoFile extends DemoContent {
protected $imageWidgetCropManager;
protected $entityTypeManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, DemoContentParserInterface $parser, ImageWidgetCropManager $image_widget_crop_manager, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->parser = $parser;
$this->imageWidgetCropManager = $image_widget_crop_manager;
$this->entityTypeManager = $entity_type_manager;
}
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('image_widget_crop.manager'), $container
->get('entity_type.manager'));
}
public function createContent() {
$data = $this
->fetchData();
foreach ($data as $uuid => $item) {
if ($uuid !== $item['uuid']) {
drush_log(dt("File with uuid: {$uuid} has a different uuid in content."), LogLevel::ERROR);
continue;
}
$files = $this->entityStorage
->loadByProperties([
'uuid' => $uuid,
]);
if ($files) {
drush_log(dt("File with uuid: {$uuid} already exists."), LogLevel::WARNING);
continue;
}
$item['uri'] = file_unmanaged_copy($this->parser
->getPath($item['path'], $this
->getModule(), $this
->getProfile()), $item['uri'], FILE_EXISTS_REPLACE);
$item['uid'] = NULL;
$entry = $this
->getEntry($item);
$entity = $this->entityStorage
->create($entry);
$entity
->save();
if (!$entity
->id()) {
continue;
}
$this->content[$entity
->id()] = $entity;
if (!empty($item['crops'])) {
$this
->applyCrops($item, $entity);
}
}
return $this->content;
}
protected function getEntry(array $item) {
$entry = [
'uuid' => $item['uuid'],
'langcode' => $item['langcode'],
'uid' => $item['uid'],
'status' => $item['status'],
'uri' => $item['uri'],
];
return $entry;
}
protected function applyCrops(array $item, FileInterface $entity) {
foreach ($item['crops'] as $crop_name => $data) {
$crop_type = $this->entityTypeManager
->getStorage('crop_type')
->load($crop_name);
if (!empty($crop_type) && $crop_type instanceof CropType) {
$this->imageWidgetCropManager
->applyCrop($data, [
'file-uri' => $item['uri'],
'file-id' => $entity
->id(),
], $crop_type);
}
}
}
}