View source
<?php
namespace Drupal\config_actions\Plugin\ConfigActionsSource;
use Drupal\config_actions\ConfigActionsSourceBase;
use Drupal\config_actions\ConfigActionsServiceInterface;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\File\FileSystem;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ConfigActionsFile extends ConfigActionsSourceBase {
const CONFIG_TEMPLATE_DIRECTORY = 'config/templates';
protected $fileSystem;
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigActionsServiceInterface $config_action_service, FileSystem $file_system) {
$this->fileSystem = $file_system;
parent::__construct($configuration, $plugin_id, $plugin_definition, $config_action_service);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$config_action_service = $container
->get('config_actions');
$file_system = $container
->get('file_system');
return new static($configuration, $plugin_id, $plugin_definition, $config_action_service, $file_system);
}
public function detect($source) {
$extension = '.' . FileStorage::getFileExtension();
return is_string($source) && substr($source, -strlen($extension)) === $extension;
}
protected function filePath($source, $base = '') {
$filepath = $this->fileSystem
->dirname($source);
$filename = $this->fileSystem
->basename($source, '.' . FileStorage::getFileExtension());
if (empty($filepath) || $filepath == '.') {
$base = !empty($base) ? $base : dirname(__FILE__);
$filepath = $base . '/' . self::CONFIG_TEMPLATE_DIRECTORY;
}
elseif (!empty($base)) {
$filepath = $base . '/' . $filepath;
}
return [
$filepath,
$filename,
];
}
public function doLoad() {
$this
->setMerge(TRUE);
list($filepath, $filename) = $this
->filePath($this->sourceId, $this->sourceBase);
$template_storage = new FileStorage($filepath, StorageInterface::DEFAULT_COLLECTION);
return $template_storage
->read($filename);
}
public function doSave($data) {
list($filepath, $filename) = $this
->filePath($this->sourceId, $this->sourceBase);
$template_storage = new FileStorage($filepath, StorageInterface::DEFAULT_COLLECTION);
return $template_storage
->write($filename, $data);
}
}