View source
<?php
namespace Drupal\feeds\Feeds\Target;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Utility\Token;
use Drupal\feeds\EntityFinderInterface;
use Drupal\feeds\Exception\EmptyFeedException;
use Drupal\feeds\Exception\TargetValidationException;
use Drupal\feeds\FieldTargetDefinition;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class File extends EntityReference {
protected $client;
protected $fileExtensions;
protected $token;
protected $fileSystem;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ClientInterface $client, Token $token, EntityFieldManagerInterface $entity_field_manager, EntityFinderInterface $entity_finder, FileSystemInterface $file_system) {
$this->client = $client;
$this->token = $token;
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $entity_finder);
$this->fileExtensions = array_filter(explode(' ', $this->settings['file_extensions']));
$this->fileSystem = $file_system;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('http_client'), $container
->get('token'), $container
->get('entity_field.manager'), $container
->get('feeds.entity_finder'), $container
->get('file_system'));
}
protected static function prepareTarget(FieldDefinitionInterface $field_definition) {
return FieldTargetDefinition::createFromFieldDefinition($field_definition)
->addProperty('target_id')
->addProperty('description');
}
protected function prepareValue($delta, array &$values) {
foreach ($values as $column => $value) {
switch ($column) {
case 'description':
$values[$column] = (string) $value;
break;
case 'target_id':
$values[$column] = $this
->getFile($value);
break;
}
}
$values['display'] = (int) $this->settings['display_default'];
}
protected function filterFieldTypes(FieldStorageDefinitionInterface $field) {
$ignore_fields = [
'filesize',
'filemime',
];
return in_array($field
->getName(), $ignore_fields) ? FALSE : parent::filterFieldTypes($field);
}
protected function getEntityType() {
return 'file';
}
protected function getBundles() {
return [];
}
protected function getFile($value) {
if (empty($value)) {
throw new EmptyFeedException('The given file url is empty.');
}
if (FALSE !== ($fid = $this
->findEntity($this->configuration['reference_by'], $value))) {
return $fid;
}
$filepath = $this
->getDestinationDirectory() . '/' . $this
->getFileName($value);
switch ($this->configuration['existing']) {
case FileSystemInterface::EXISTS_ERROR:
if (file_exists($filepath) && ($fid = $this
->findEntity('uri', $filepath))) {
return $fid;
}
if ($file = file_save_data($this
->getContent($value), $filepath, FileSystemInterface::EXISTS_REPLACE)) {
return $file
->id();
}
break;
default:
if ($file = file_save_data($this
->getContent($value), $filepath, $this->configuration['existing'])) {
return $file
->id();
}
}
throw new TargetValidationException($this
->t('There was an error saving the file: %file', [
'%file' => $filepath,
]));
}
protected function getDestinationDirectory() {
$destination = $this->token
->replace($this->settings['uri_scheme'] . '://' . trim($this->settings['file_directory'], '/'));
$this->fileSystem
->prepareDirectory($destination, FileSystemInterface::MODIFY_PERMISSIONS | FileSystemInterface::CREATE_DIRECTORY);
return $destination;
}
protected function getFileName($url) {
$filename = trim(\Drupal::service('file_system')
->basename($url), " \t\n\r\0\v.");
list($filename) = explode('?', $filename);
$extension = substr($filename, strrpos($filename, '.') + 1);
if (!preg_grep('/' . $extension . '/i', $this->fileExtensions)) {
throw new TargetValidationException($this
->t('The file, %url, failed to save because the extension, %ext, is invalid.', [
'%url' => $url,
'%ext' => $extension,
]));
}
return $filename;
}
protected function getContent($url) {
$response = $this->client
->request('GET', $url);
if ($response
->getStatusCode() >= 400) {
$args = [
'%url' => $url,
'@code' => $response
->getStatusCode(),
];
throw new TargetValidationException($this
->t('Download of %url failed with code @code.', $args));
}
return (string) $response
->getBody();
}
public function defaultConfiguration() {
return [
'existing' => FileSystemInterface::EXISTS_ERROR,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$options = [
FileSystemInterface::EXISTS_REPLACE => $this
->t('Replace'),
FileSystemInterface::EXISTS_RENAME => $this
->t('Rename'),
FileSystemInterface::EXISTS_ERROR => $this
->t('Ignore'),
];
$form['existing'] = [
'#type' => 'select',
'#title' => $this
->t('Handle existing files'),
'#options' => $options,
'#default_value' => $this->configuration['existing'],
];
return $form;
}
public function getSummary() {
$summary = parent::getSummary();
switch ($this->configuration['existing']) {
case FileSystemInterface::EXISTS_REPLACE:
$message = 'Replace';
break;
case FileSystemInterface::EXISTS_RENAME:
$message = 'Rename';
break;
case FileSystemInterface::EXISTS_ERROR:
$message = 'Ignore';
break;
}
$summary[] = $this
->t('Existing files: %existing', [
'%existing' => $message,
]);
return $summary;
}
protected function createEntity($value) {
if (!strlen(trim($value))) {
return FALSE;
}
$bundles = $this
->getBundles();
$entity = $this->entityTypeManager
->getStorage($this
->getEntityType())
->create([
$this
->getLabelKey() => $value,
$this
->getBundleKey() => reset($bundles),
'uri' => $value,
]);
$entity
->save();
return $entity
->id();
}
}