Skip to content
Snippets Groups Projects
Commit 89ec9cfa authored by Andrii Kondratenko's avatar Andrii Kondratenko
Browse files

Issue #3415772 | Drupal 10 compatibility

parent 7dd3e3d8
Branches
Tags 2.0.0 2.0.0-dev
1 merge request!1Issue #3415772 | Drupal 10 compatibility
Pipeline #85535 passed
Showing
with 410 additions and 159 deletions
################
# DrupalCI GitLabCI template
#
# Gitlab-ci.yml to replicate DrupalCI testing for Contrib
#
# With thanks to:
# * The GitLab Acceleration Initiative participants
# * DrupalSpoons
################
################
# Guidelines
#
# This template is designed to give any Contrib maintainer everything they need to test, without requiring modification. It is also designed to keep up to date with Core Development automatically through the use of include files that can be centrally maintained.
#
# However, you can modify this template if you have additional needs for your project.
################
################
# Includes
#
# Additional configuration can be provided through includes.
# One advantage of include files is that if they are updated upstream, the changes affect all pipelines using that include.
#
# Includes can be overridden by re-declaring anything provided in an include, here in gitlab-ci.yml
# https://docs.gitlab.com/ee/ci/yaml/includes.html#override-included-configuration-values
################
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
# "ref" value can be:
# - Recommended (default) - `ref: $_GITLAB_TEMPLATES_REF` - The Drupal Association will update this value to the recommended tag for contrib.
# - Latest - `ref: main` - Get the latest additions and bug fixes as they are merged into the templates.
# - Minor or Major latests - `ref: 1.x-latest` or `ref: 1.0.x-latest` - Get the latest additions within a minor (mostly bugfixes) or major (bugs and new features).
# - Fixed tag - `ref: 1.0.1` - Set the value to a known tag. This will not get any updates.
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
# EXPERIMENTAL: For Drupal 7, remove the above line and uncomment the below.
# - '/includes/include.drupalci.main-d7.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
variables:
SKIP_PHPUNIT: '1'
# SKIP_ESLINT: '1'
###################################################################################
#
# *
# /(
# ((((,
# /(((((((
# ((((((((((*
# ,(((((((((((((((
# ,(((((((((((((((((((
# ((((((((((((((((((((((((*
# *(((((((((((((((((((((((((((((
# ((((((((((((((((((((((((((((((((((*
# *(((((((((((((((((( .((((((((((((((((((
# ((((((((((((((((((. /(((((((((((((((((*
# /((((((((((((((((( .(((((((((((((((((,
# ,(((((((((((((((((( ((((((((((((((((((
# .(((((((((((((((((((( .(((((((((((((((((
# ((((((((((((((((((((((( ((((((((((((((((/
# (((((((((((((((((((((((((((/ ,(((((((((((((((*
# .((((((((((((((/ /(((((((((((((. ,(((((((((((((((
# *(((((((((((((( ,(((((((((((((/ *((((((((((((((.
# ((((((((((((((, /(((((((((((((. ((((((((((((((,
# (((((((((((((/ ,(((((((((((((* ,(((((((((((((,
# *((((((((((((( .((((((((((((((( ,(((((((((((((
# ((((((((((((/ /((((((((((((((((((. ,((((((((((((/
# ((((((((((((( *(((((((((((((((((((((((* *((((((((((((
# ((((((((((((( ,(((((((((((((..((((((((((((( *((((((((((((
# ((((((((((((, /((((((((((((* /((((((((((((/ ((((((((((((
# ((((((((((((( /((((((((((((/ (((((((((((((* ((((((((((((
# (((((((((((((/ /(((((((((((( ,((((((((((((, *((((((((((((
# (((((((((((((( *(((((((((((/ *((((((((((((. ((((((((((((/
# *((((((((((((((((((((((((((, /(((((((((((((((((((((((((
# ((((((((((((((((((((((((( ((((((((((((((((((((((((,
# .(((((((((((((((((((((((/ ,(((((((((((((((((((((((
# ((((((((((((((((((((((/ ,(((((((((((((((((((((/
# *((((((((((((((((((((( (((((((((((((((((((((,
# ,(((((((((((((((((((((, ((((((((((((((((((((/
# ,(((((((((((((((((((((* /((((((((((((((((((((
# ((((((((((((((((((((((, ,/((((((((((((((((((((,
# ,(((((((((((((((((((((((((((((((((((((((((((((((((((
# .(((((((((((((((((((((((((((((((((((((((((((((
# .((((((((((((((((((((((((((((((((((((,.
# .,(((((((((((((((((((((((((.
#
###################################################################################
name: File Compressor field
type: module
description: Allow users to download multiple file based field items in a single compressed file.
core: 8.x
package: Fields
configure: file_compressor_field.rebuild
name: File Compressor field
type: module
description: Allow users to download multiple file based field items in a single compressed file.
core_version_requirement: ^9 || ^10
package: Fields
configure: file_compressor_field.rebuild
......@@ -5,7 +5,7 @@
* Hook implementations and API functions for File Compressor field module.
*/
use \Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_help().
......@@ -26,10 +26,11 @@ function file_compressor_field_help($path, $arg) {
$output .= '<h3>' . t('Requirements') . '</h3>';
$output .= '<p>' . t('This module provides by default two Compressor plugins, Zip and GZip. This list can be extended using hooks. Each zip provider requires a different PHP library:') . '</p>';
$output .= '<ul>';
$output .= '<li>' . t('<strong>Zip:</strong> php_zip extension. <a href="@link">PHP Zip Documentation</a>', array('@link' =>'http://php.net/manual/es/book.zip.php')) . '</li>';
$output .= '<li>' . t('<strong>GZip:</strong> Archive Tar PEAR package. <a href="@link">Archive Tar Documentation</a>', array('@link' =>'http://pear.php.net/package/Archive_Tar')) . '</li>';
$output .= '<li>' . t('<strong>Zip:</strong> php_zip extension. <a href="@link">PHP Zip Documentation</a>', ['@link' => 'http://php.net/manual/es/book.zip.php']) . '</li>';
$output .= '<li>' . t('<strong>GZip:</strong> Archive Tar PEAR package. <a href="@link">Archive Tar Documentation</a>', ['@link' => 'http://pear.php.net/package/Archive_Tar']) . '</li>';
$output .= '</ul>';
return $output;
case 'file_compressor_field.rebuild':
$output = '<p>' . t('Select Fields you want to rebuild manually using File Compressor field.') . '</p>';
$output .= '<p>' . t('This only should be necessary after creating compress field on existing entities or when modifying the fields to compress.') . '</p>';
......@@ -59,4 +60,4 @@ function file_compressor_field_form_field_ui_field_storage_edit_form_alter(&$for
if ($form['#field']->get('type') == 'file_compressor') {
$form['field_storage']['cardinality_container']['#access'] = FALSE;
}
}
\ No newline at end of file
}
services:
plugin.manager.file_compressor:
class: Drupal\file_compressor_field\Plugin\FileCompressorManager
parent: default_plugin_manager
class: Drupal\file_compressor_field\Plugin\FileCompressorManager
parent: default_plugin_manager
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Annotation\FileCompressor.
*/
namespace Drupal\file_compressor_field\Annotation;
use Drupal\Component\Annotation\Plugin;
......
<?php
/**
* Contains \Drupal\file_compressor_field\Form\FileCompressorRebuildForm.
*/
namespace Drupal\file_compressor_field\Form;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -16,20 +15,40 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
class FileCompressorRebuildForm extends FormBase {
/**
* The entity manager.
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The field manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityManager;
protected $entityFieldManager;
/**
* The field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityTypeBundleInfo;
/**
* Constructs a new FileCompressorRebuildForm.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
*/
public function __construct(EntityManagerInterface $entity_manager) {
$this->entityManager = $entity_manager;
final public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
$this->entityTypeManager = $entity_type_manager;
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
......@@ -37,7 +56,9 @@ class FileCompressorRebuildForm extends FormBase {
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager')
$container->get('entity_type.manager'),
$container->get('entity_field.manager'),
$container->get('entity_type.bundle.info')
);
}
......@@ -52,18 +73,22 @@ class FileCompressorRebuildForm extends FormBase {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$definitions = $this->entityManager->getFieldMapByFieldType('file_compressor');
$definitions = $this->entityFieldManager->getFieldMapByFieldType('file_compressor');
$options = array();
$options = [];
foreach ($definitions as $entity_type_id => $field_definitions) {
$entity_type = $this->entityManager->getDefinition($entity_type_id);
$bundle_info = $this->entityManager->getBundleInfo($entity_type_id);
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$bundle_info = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
foreach ($field_definitions as $field_name => $field_map) {
foreach ($field_map['bundles'] as $bundle) {
$bundle_definitions = $this->entityManager->getFieldDefinitions($entity_type_id, $bundle);
$option_key = implode('|', array($entity_type_id, $bundle));
$bundle_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle);
$option_key = implode('|', [$entity_type_id, $bundle]);
if (!isset($options[$option_key])) {
$options[$option_key] = array($bundle_definitions[$field_name]->getLabel(), $entity_type->getLabel(), $bundle_info[$bundle]['label']);
$options[$option_key] = [
$bundle_definitions[$field_name]->getLabel(),
$entity_type->getLabel(),
$bundle_info[$bundle]['label'],
];
}
else {
$options[$option_key][0] = $options[$option_key][0] . ', ' . $bundle_definitions[$field_name]->getLabel();
......@@ -72,21 +97,21 @@ class FileCompressorRebuildForm extends FormBase {
}
}
$header = array(t('Field Name'), t('Entity type'), t('Bundle'));
$header = [$this->t('Field Name'), $this->t('Entity type'), $this->t('Bundle')];
$form['rebuild'] = array(
$form['rebuild'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#empty' => $this->t('No content available.'),
);
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Rebuild Compressed files'),
'#button_type' => 'primary',
);
];
return $form;
}
......@@ -97,7 +122,7 @@ class FileCompressorRebuildForm extends FormBase {
public function validateForm(array &$form, FormStateInterface $form_state) {
$selected_fields = array_filter($form_state->getValue('rebuild'));
if (empty($selected_fields)) {
$form_state->setErrorByName('rebuild', t('Please select at least one field to update.'));
$form_state->setErrorByName('rebuild', $this->t('Please select at least one field to update.'));
}
}
......@@ -107,16 +132,18 @@ class FileCompressorRebuildForm extends FormBase {
public function submitForm(array &$form, FormStateInterface $form_state) {
$fields = array_filter($form_state->getValue('rebuild'));
foreach ($fields as $field) {
list($entity_type_name, $bundle_name) = explode('|', $field);
$entity_type = $this->entityManager->getDefinition($entity_type_name);
[$entity_type_name, $bundle_name] = explode('|', $field);
$entity_type = $this->entityTypeManager->getDefinition($entity_type_name);
$query = \Drupal::EntityQuery($entity_type_name);
$query = $this->entityTypeManager->getStorage($entity_type_name)->getQuery();
$query->accessCheck(FALSE);
if ($type = $entity_type->getKey('bundle')) {
$query->condition($type, $bundle_name);
}
$result = $query->execute();
if (!empty($result)) {
$entities = entity_load_multiple($entity_type_name, $result);
$storage = $this->entityTypeManager->getStorage($entity_type);
$entities = $storage->loadMultiple($result);
foreach ($entities as $entity) {
$entity->save();
}
......@@ -124,4 +151,4 @@ class FileCompressorRebuildForm extends FormBase {
}
}
}
\ No newline at end of file
}
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\Field\FieldType\FileCompressorFieldItemList.
*/
namespace Drupal\file_compressor_field\Plugin\Field\FieldType;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList;
use Drupal\file_compressor_field\Plugin\FileCompressorPluginInterface;
/**
* Represents a configurable entity file compressor field.
......@@ -20,10 +16,14 @@ class FileCompressorFieldItemList extends FileFieldItemList implements FileCompr
* {@inheritdoc}
*/
public function preSave() {
$langcodes = ($this->getFieldDefinition()->isTranslatable()) ? array($this->getLangcode()) : array_keys(\Drupal::languageManager()->getLanguages());
$langcodes = ($this->getFieldDefinition()->isTranslatable()) ? [$this->getLangcode()] : array_keys(\Drupal::languageManager()->getLanguages());
foreach (array_filter($this->getFieldDefinition()->getSetting('compressed_fields')) as $field_to_compress) {
foreach ($langcodes as $current_langcode) {
$field_items = $this->getEntity()->getTranslation($current_langcode)->{$field_to_compress};
$entity = $this->getEntity();
if (!$entity->hasTranslation($current_langcode)) {
continue;
}
$field_items = $entity->getTranslation($current_langcode)->{$field_to_compress};
if (!$field_items->isEmpty()) {
foreach ($field_items as $field_item) {
if (isset($field_item->target_id) && $field_item->target_id > 0 && !isset($files[$field_item->target_id])) {
......@@ -35,54 +35,65 @@ class FileCompressorFieldItemList extends FileFieldItemList implements FileCompr
}
}
if (!empty($files) && $compressed_file = $this->generateCompressedFile($files) ) {
$item = array(
if (!empty($files) && $compressed_file = $this->generateCompressedFile($files)) {
$item = [
'target_id' => $compressed_file->fid->value,
'display' => 1,
);
];
$this->set(0, $item);
}
}
/**
* Generates a compressed file given a list of URIs,
* Generates a compressed file given a list of URIs.
*
* @param array $files
* Array containing file uris to compress,
* Array containing file uris to compress,.
*
* @return bool|\Drupal\Core\Entity\EntityInterface
* The compressed ile entity, FALSE otherwise.
*/
protected function generateCompressedFile($files) {
$file_compressor_manager = \Drupal::service('plugin.manager.file_compressor');
/** @var FileCompressorPluginInterface $file_compressor */
/** @var \Drupal\file\Entity\FileCompressorPluginInterface $file_compressor */
$file_compressor = $file_compressor_manager->createInstance($this->getSetting('file_compressor'));
$create_compressed_file = $this->isEmpty() || $this->getEntity()->isNewRevision();
$compressed_field_components = empty($this->target_id) ? FALSE : File::load($this->target_id);
$create_compressed_file = $this->isEmpty() || $this->getEntity()->isNewRevision() || !$compressed_field_components;
if ($create_compressed_file) {
$directory_uri = $this->getUploadLocation();
if (!file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY)) {
drupal_set_message('The directory wasn\'t created or was not writable', 'error');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
if (!$file_system->prepareDirectory($directory_uri, FileSystemInterface::CREATE_DIRECTORY)) {
\Drupal::messenger()->addMessage('The directory wasn\'t created or was not writable', 'error');
return FALSE;
}
do {
$file_uri = $file_compressor->generateCompressedFileUri($directory_uri . '/compressed_file_' . user_password(4));
$file_uri = $file_compressor->generateCompressedFileUri($directory_uri . '/compressed_file_' . \Drupal::service('password_generator')->generate(4));
$exists = file_exists($file_uri);
} while ($exists);
}
else {
$compressed_field_components = File::load($this->target_id);
if (!$compressed_field_components) {
\Drupal::logger('file_compressor')->error('File not found: ' . $this->target_id);
return FALSE;
}
$file_uri = $compressed_field_components->getFileUri();
}
if ($file_compressor->generateCompressedFile($file_uri, $files)) {
if ($create_compressed_file) {
$user = \Drupal::currentUser();
$compressed_field_components = entity_create('file', array(
/** @var \Drupal\file\FileStorageInterface $file_storage */
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$compressed_field_components = $file_storage->create([
'uri' => $file_uri,
'uid' => $user->id(),
'status' => FILE_STATUS_PERMANENT,
));
drupal_register_shutdown_function(array(get_class($this), 'fileCompressorFieldStore'), $this, $file);
'status' => FileInterface::STATUS_PERMANENT,
]);
drupal_register_shutdown_function([get_class($this), 'fileCompressorFieldStore'], $this, $compressed_field_components);
}
else {
$compressed_field_components->setFileUri($file_uri);
......@@ -91,13 +102,13 @@ class FileCompressorFieldItemList extends FileFieldItemList implements FileCompr
return $compressed_field_components;
}
return FALSE;
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getUploadLocation($data = array()) {
public function getUploadLocation($data = []) {
$settings = $this->getFieldDefinition()->getSettings();
$destination = trim($settings['file_directory'], '/');
......@@ -116,9 +127,12 @@ class FileCompressorFieldItemList extends FileFieldItemList implements FileCompr
* The File entity to move and store.
*/
public static function fileCompressorFieldStore(FileCompressorFieldItemListInterface $field, File $file) {
$entity = \Drupal::entityManager()->loadEntityByUuid($field->getFieldDefinition()->getTargetEntityTypeId(), $field->getEntity()->uuid->value);
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$entity = \Drupal::service('entity.repository')->loadEntityByUuid($field->getFieldDefinition()->getTargetEntityTypeId(), $field->getEntity()->uuid->value);
$file_compressor_manager = \Drupal::service('plugin.manager.file_compressor');
/** @var FileCompressorPluginInterface $file_compressor */
/** @var \Drupal\file\Entity\FileCompressorPluginInterface $file_compressor */
$file_compressor = $file_compressor_manager->createInstance($field->getSetting('file_compressor'));
$values[] = $field->getEntity()->getEntityTypeId();
$values[] = $entity->id();
......@@ -131,11 +145,32 @@ class FileCompressorFieldItemList extends FileFieldItemList implements FileCompr
}
$destination = $field->getUploadLocation() . '/' . implode('-', $values);
$destination = $file_compressor->generateCompressedFileUri($destination);
if ($destination = file_unmanaged_move($file->getFileUri(), $destination, FILE_EXISTS_RENAME)) {
if ($destination = self::fileUnmanagedMove($file->getFileUri(), $destination, FileSystemInterface::EXISTS_RENAME)) {
$file->setFileUri($destination);
$file->setFilename(drupal_basename($destination));
$file->setFilename($file_system->basename($destination));
$file->save();
}
}
/**
* Moves a file to a new location without database changes or hook invocation.
*/
public static function fileUnmanagedMove($source, $destination = NULL, $replace = FileSystemInterface::EXISTS_RENAME) {
try {
$file_system = \Drupal::service('file_system');
// Build a destination URI if necessary.
if (!isset($destination)) {
$uri = \Drupal::config('system.file')->get('default_scheme') . '://' . $file_system->basename($source);
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$destination = $stream_wrapper_manager->normalizeUri($uri);
}
return $file_system->move($source, $destination, $replace);
}
catch (\Exception $e) {
return FALSE;
}
}
}
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\Field\FieldType\FileCompressorFieldItemListInterface.
*/
namespace Drupal\file_compressor_field\Plugin\Field\FieldType;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
......@@ -15,13 +12,14 @@ interface FileCompressorFieldItemListInterface extends EntityReferenceFieldItemL
/**
* Determines the URI for a file field.
*
* @param $data
* @param array $data
* An array of token objects to pass to token_replace().
*
* @return
* @return string
* A file directory URI with tokens replaced.
*
* @see token_replace()
*/
public function getUploadLocation($data = array());
}
\ No newline at end of file
public function getUploadLocation($data = []);
}
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\Field\FieldType\FileCompressorItem.
*/
namespace Drupal\file_compressor_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
......@@ -22,24 +17,27 @@ use Drupal\file\Plugin\Field\FieldType\FileItem;
* description = @Translation("This field stores the ID of a file as an integer value."),
* default_formatter = "file_default",
* list_class = "\Drupal\file_compressor_field\Plugin\Field\FieldType\FileCompressorFieldItemList",
* constraints = {"ValidReference" = {}, "ReferenceAccess" = {}}
* constraints = {"ReferenceAccess" = {}}
* )
*/
class FileCompressorItem extends FileItem {
/**
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return array(
return [
'file_compressor' => 'zip_built_in',
) + parent::defaultStorageSettings();
] + parent::defaultStorageSettings();
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
'compressed_fields' => array(),
) + parent::defaultFieldSettings();
return [
'compressed_fields' => [],
] + parent::defaultFieldSettings();
}
/**
......@@ -58,29 +56,29 @@ class FileCompressorItem extends FileItem {
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$scheme_options = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE);
$element['uri_scheme'] = array(
$element['uri_scheme'] = [
'#type' => 'radios',
'#title' => t('Upload destination'),
'#title' => $this->t('Upload destination'),
'#options' => $scheme_options,
'#default_value' => $this->getSetting('uri_scheme'),
'#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
'#description' => $this->t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
'#disabled' => $has_data,
);
];
$file_compressor_options = array_map(function($item){
$file_compressor_options = array_map(function ($item) {
return $item['admin_label'];
}, \Drupal::service('plugin.manager.file_compressor')->getDefinitions());
$element['file_compressor'] = array(
$element['file_compressor'] = [
'#type' => 'radios',
'#title' => t('File Compressor'),
'#title' => $this->t('File Compressor'),
'#options' => $file_compressor_options,
'#default_value' => $this->getSetting('file_compressor'),
'#description' => t('Select the file compressor to use.'),
'#description' => $this->t('Select the file compressor to use.'),
'#disabled' => $has_data,
);
];
return $element;
return $element;
}
/**
......@@ -88,7 +86,9 @@ class FileCompressorItem extends FileItem {
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = parent::schema($field_definition);
unset($schema['description']);
if (isset($schema['columns']['description'])) {
unset($schema['columns']['description']);
}
return $schema;
}
......@@ -99,21 +99,21 @@ class FileCompressorItem extends FileItem {
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$form = parent::fieldSettingsForm($form, $form_state);
$options = array();
$options = [];
$field_definitions = $this->getEntity()->getFieldDefinitions();
foreach ($field_definitions as $field_name =>$field_definition) {
if ($field_definition instanceof FieldConfigInterface && in_array($field_definition->getType(), array('file', 'image'))) {
foreach ($field_definitions as $field_name => $field_definition) {
if ($field_definition instanceof FieldConfigInterface && in_array($field_definition->getType(), ['file', 'image'])) {
$options[$field_name] = $field_definition->getLabel();
}
}
$form['compressed_fields'] = array(
'#title' => t('Fields to compress'),
$form['compressed_fields'] = [
'#title' => $this->t('Fields to compress'),
'#type' => 'checkboxes',
'#options' => $options,
'#default_value' => $this->getSetting('compressed_fields'),
'#weight' => 10,
);
];
unset($form['file_extensions']);
unset($form['max_filesize']);
......
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\FileCompressor\FileCompressorGZip.
*/
namespace Drupal\file_compressor_field\Plugin\FileCompressor;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Password\PasswordGeneratorInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\file_compressor_field\Plugin\FileCompressorBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Implements GZip compressor for File Compressor field.
......@@ -18,21 +17,75 @@ use Drupal\file_compressor_field\Plugin\FileCompressorBase;
* extension = "tar.gz"
* )
*/
class FileCompressorGZip extends FileCompressorBase {
class FileCompressorGZip extends FileCompressorBase implements ContainerFactoryPluginInterface {
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* The password generator service.
*
* @var \Drupal\Core\Password\PasswordGeneratorInterface
*/
protected $passwordGenerator;
/**
* Constructs a new FileCompressorGZip object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\File\FileSystemInterface $file_system
* The file system service.
* @param \Drupal\Core\Password\PasswordGeneratorInterface $password_generator
* The password generator service.
*/
final public function __construct(array $configuration,
$plugin_id,
$plugin_definition,
FileSystemInterface $file_system,
PasswordGeneratorInterface $password_generator) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->fileSystem = $file_system;
$this->passwordGenerator = $password_generator;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('file_system'),
$container->get('password_generator')
);
}
/**
* @{@inheritdoc}
* {@inheritdoc}
*/
public function generateCompressedFile($file_uri, $files) {
$full_file_uri = drupal_realpath($file_uri);
$full_file_uri = $this->fileSystem->realpath($file_uri);
$tar = new \Archive_Tar($full_file_uri, 'gz');
$tmp = 'temporary://file_compressor_field' . time() . user_password();
drupal_mkdir($tmp);
$tmp = 'temporary://file_compressor_field' . time() . $this->passwordGenerator->generate();
$this->fileSystem->mkdir($tmp);
foreach ($files as $file) {
file_unmanaged_copy($file, $tmp, FILE_EXISTS_REPLACE);
$this->fileSystem->copy($file, $tmp, FileSystemInterface::EXISTS_REPLACE);
}
$tar->createModify($tmp, '', $tmp);
file_unmanaged_delete_recursive($tmp);
$this->fileSystem->deleteRecursive($tmp);
return TRUE;
}
......
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\FileCompressor\FileCompressorZip.
*/
namespace Drupal\file_compressor_field\Plugin\FileCompressor;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\file_compressor_field\Plugin\FileCompressorBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Implements Zip compressor for File Compressor field.
......@@ -18,30 +17,85 @@ use Drupal\file_compressor_field\Plugin\FileCompressorBase;
* extension = "zip"
* )
*/
class FileCompressorZip extends FileCompressorBase {
class FileCompressorZip extends FileCompressorBase implements ContainerFactoryPluginInterface {
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* The logger service.
*
* @var \Drupal\Core\Logger\LoggerChannelInterface
*/
protected $logger;
/**
* @{@inheritdoc}
* Constructs a new FileCompressorZip object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\File\FileSystemInterface $file_system
* The file system service.
* @param \Drupal\Core\Logger\LoggerChannelInterface $logger
* The logger service.
*/
final public function __construct(array $configuration,
$plugin_id,
$plugin_definition,
FileSystemInterface $file_system,
LoggerChannelInterface $logger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->fileSystem = $file_system;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('file_system'),
$container->get('logger.factory')->get('file_compressor_field')
);
}
/**
* {@inheritdoc}
*/
public function generateCompressedFile($file_uri, $files) {
$logger = \Drupal::logger('file_compressor_field');
$zip = new \ZipArchive();
if ($zip_open = $zip->open(drupal_realpath($file_uri), \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE)) {
// Since libzip 1.6.0, a empty file is not a valid archive any longer.
if (!empty($this->fileSystem->realpath($file_uri)) && $zip->open($this->fileSystem->realpath($file_uri), \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE)) {
$zip->setArchiveComment('Generated by File Compressor field for Drupal.');
// http://drupal.org/node/1234282 - duplicate filenames.
foreach ($files as $file) {
$path = drupal_realpath($file);
$path = $this->fileSystem->realpath($file);
if (file_exists($file)) {
if (!$zip->addFile($path, basename($path))) {
$logger->error('Failed to add !file to Zip.', array('!file' => $file));
$this->logger->error('Failed to add !file to Zip.', ['!file' => $file]);
}
}
else {
$logger->error('file_compressor_field', 'Failed to locate !file.', array('!file' => $file));
$this->logger->error('Failed to locate !file.', ['!file' => $file]);
}
}
if (!$zip->close()) {
$logger->error('file_compressor_field', 'Error saving file: !status_string', array('!status_string' => $zip->getStatusString()));
$this->logger->error('Error saving file: !status_string', ['!status_string' => $zip->getStatusString()]);
return FALSE;
}
return TRUE;
......
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\FileCompressorBase.
*/
namespace Drupal\file_compressor_field\Plugin;
use Drupal\Component\Plugin\PluginBase;
/**
* Defines a base class from which other modules providing File Compressor
* backends may extend.
* Defines a base class that providing File Compressor backends may extend.
*
* A complete sample plugin definition should be defined as in this example:
*
......@@ -39,7 +33,7 @@ abstract class FileCompressorBase extends PluginBase implements FileCompressorPl
}
/**
* @{@inheritdoc}
* {@inheritdoc}
*/
public function generateCompressedFileUri($base_uri) {
return $base_uri . '.' . $this->getExtension();
......
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\FileCompressorManager.
*/
namespace Drupal\file_compressor_field\Plugin;
use Drupal\Core\Cache\CacheBackendInterface;
......@@ -17,8 +12,7 @@ use Drupal\Core\Plugin\DefaultPluginManager;
class FileCompressorManager extends DefaultPluginManager {
/**
* Constructs a new \Drupal\file_compressor_field\Plugin\FileCompressorManager
* object.
* Constructs a new file_compressor_field\Plugin\FileCompressorManager object.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
......
<?php
/**
* @file
* Contains \Drupal\file_compressor_field\Plugin\FileCompressorPluginInterface.
*/
namespace Drupal\file_compressor_field\Plugin;
use Drupal\Component\Plugin\PluginInspectionInterface;
......@@ -44,7 +39,7 @@ interface FileCompressorPluginInterface extends PluginInspectionInterface {
/**
* Generates a compressed file given the uri to store and files to archive.
*
* @param $file_uri
* @param string $file_uri
* URI to store the compressed file.
* @param array $files
* Files to archive.
......@@ -53,5 +48,5 @@ interface FileCompressorPluginInterface extends PluginInspectionInterface {
* Boolean indicating if the file has been created properly or not.
*/
public function generateCompressedFile($file_uri, $files);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment