config_preview_deploy-1.0.0-alpha3/src/ConfigExporter.php
src/ConfigExporter.php
<?php
declare(strict_types=1);
namespace Drupal\config_preview_deploy;
use Drupal\Core\Archiver\ArchiveTar;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Component\Serialization\Yaml;
/**
* Exports configuration as a tarball.
*
* This exporter mimics Drupal core's config export functionality
* from ConfigController::downloadExport().
*/
class ConfigExporter {
/**
* The export storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected StorageInterface $exportStorage;
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected FileSystemInterface $fileSystem;
/**
* Constructs a ConfigExporter.
*
* @param \Drupal\Core\Config\StorageInterface $export_storage
* The export storage.
* @param \Drupal\Core\File\FileSystemInterface $file_system
* The file system service.
*/
public function __construct(
StorageInterface $export_storage,
FileSystemInterface $file_system,
) {
$this->exportStorage = $export_storage;
$this->fileSystem = $file_system;
}
/**
* Exports configuration as a tarball.
*
* Uses the same logic as Drupal core's ConfigController::downloadExport()
* to ensure compatibility with core's config import functionality.
*
* @return string
* The tarball content as a binary string.
*
* @throws \Exception
* If export fails.
*/
public function exportConfigTarball(): string {
$tempDir = $this->fileSystem->getTempDirectory();
$tarballPath = $tempDir . '/config-export-' . uniqid() . '.tar.gz';
try {
// Clean up any existing tarball.
if (file_exists($tarballPath)) {
$this->fileSystem->delete($tarballPath);
}
// Create the tarball using core's export logic.
$archiver = new ArchiveTar($tarballPath, 'gz');
// Add all contents of the export storage to the archive.
// This mirrors ConfigController::downloadExport().
foreach ($this->exportStorage->listAll() as $name) {
$archiver->addString("$name.yml", Yaml::encode($this->exportStorage->read($name)));
}
// Get all data from the remaining collections.
foreach ($this->exportStorage->getAllCollectionNames() as $collection) {
$collection_storage = $this->exportStorage->createCollection($collection);
foreach ($collection_storage->listAll() as $name) {
$archiver->addString(str_replace('.', '/', $collection) . "/$name.yml", Yaml::encode($collection_storage->read($name)));
}
}
// Read the tarball content.
$content = file_get_contents($tarballPath);
// Clean up the temporary file.
$this->fileSystem->delete($tarballPath);
if ($content === FALSE) {
throw new \Exception('Failed to read exported config tarball.');
}
return $content;
}
catch (\Exception $e) {
// Clean up on error.
if (file_exists($tarballPath)) {
$this->fileSystem->delete($tarballPath);
}
throw new \Exception('Config export failed: ' . $e->getMessage());
}
}
}
