View source
<?php
namespace Drupal\feeds\Feeds\Fetcher;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\feeds\FeedInterface;
use Drupal\feeds\Plugin\Type\Fetcher\FetcherInterface;
use Drupal\feeds\Plugin\Type\PluginBase;
use Drupal\feeds\Result\FetcherResult;
use Drupal\feeds\StateInterface;
use Drupal\file\FileUsage\FileUsageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UploadFetcher extends PluginBase implements FetcherInterface, ContainerFactoryPluginInterface {
protected $fileUsage;
protected $fileStorage;
protected $streamWrapperManager;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, FileUsageInterface $file_usage, EntityTypeManagerInterface $entity_type_manager, StreamWrapperManagerInterface $stream_wrapper_manager) {
$this->fileUsage = $file_usage;
$this->fileStorage = $entity_type_manager
->getStorage('file');
$this->streamWrapperManager = $stream_wrapper_manager;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('file.usage'), $container
->get('entity_type.manager'), $container
->get('stream_wrapper_manager'));
}
public function fetch(FeedInterface $feed, StateInterface $state) {
$file = $feed
->getSource();
if (is_file($file) && is_readable($file)) {
return new FetcherResult($file);
}
throw new \RuntimeException(new FormattableMarkup('Resource is not a file: %source', [
'%source' => $file,
]));
}
public function defaultFeedConfiguration() {
return [
'fid' => 0,
'usage_id' => '',
];
}
public function onFeedDeleteMultiple(array $feeds) {
foreach ($feeds as $feed) {
$feed_config = $feed
->getConfigurationFor($this);
if ($feed_config['fid']) {
$this
->deleteFile($feed_config['fid'], $feed_config['usage_id']);
}
}
}
public function defaultConfiguration() {
$schemes = $this
->getSchemes();
$scheme = in_array('private', $schemes) ? 'private' : reset($schemes);
return [
'allowed_extensions' => 'txt csv tsv xml opml',
'directory' => $scheme . '://feeds',
];
}
protected function deleteFile($file_id, $uuid) {
if ($file = $this->fileStorage
->load($file_id)) {
$this->fileUsage
->delete($file, 'feeds', $this
->pluginType(), $uuid);
}
}
protected function getSchemes() {
return array_keys($this->streamWrapperManager
->getWrappers(StreamWrapperInterface::WRITE_VISIBLE));
}
}