Skip to content
Snippets Groups Projects
Commit 7b3ea1a0 authored by Erik Petra's avatar Erik Petra Committed by Martin Giessing
Browse files

Issue #3412075 by erik_petra: File size for Media transform

parent 8cdb7940
No related branches found
No related tags found
1 merge request!3Add Media file URL and size transform
<?php
namespace Drupal\transform_api\Plugin\Transform\Field;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\File\FileUrlGenerator;
use Drupal\file\Entity\File;
use Drupal\transform_api\FieldTransformBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Transform field plugin for file field types as Urls.
*
* @FieldTransform(
* id = "file_url_size",
* label = @Translation("File URL and Size"),
* field_types = {
* "file"
* }
* )
*/
class FileUrlSizeTransform extends FieldTransformBase {
/**
* File url generator.
*
* @var \Drupal\Core\File\FileUrlGenerator
*/
protected $fileUrlGenerator;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $transform_mode, array $third_party_settings, FileUrlGenerator $file_url_generator) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $transform_mode, $third_party_settings);
$this->fileUrlGenerator = $file_url_generator;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['transform_mode'], $configuration['third_party_settings'], $container->get('file_url_generator'));
}
/**
* {@inheritdoc}
*/
public function transformElements(FieldItemListInterface $items, $langcode) {
$values = [];
/** @var \Drupal\Core\Field\FieldItemInterface $item */
foreach ($items as $item) {
if (!empty($item->getValue()['target_id'])) {
// File ID.
$fid = $item->getValue()['target_id'];
// Load file.
$file = File::load($fid);
$file_uri = $file->getFileUri();
$values[] = [
'url' => $this->fileUrlGenerator->generateString($file_uri),
'filesize' => $file->getSize(),
];
}
else {
$values[] = NULL;
}
}
return $values;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment