Search by

adachsoft / data-backup

Arkadiusz Adach

Framework-independent backup and restore orchestration for PHP applications.

Package info

gitlab.com/a.adach/data-backup

Issues

pkg:composer/adachsoft/data-backup

Statistics

Installs: 24

Dependents: 1

Suggesters: 0

Stars: 0

v0.3.0 2026-11-25 13:38 UTC

This package is auto-updated.

Last update: 2026-11-25 12:39:16 UTC


README

adachsoft/data-backup provides framework-free backup and restore orchestration for PHP applications. Applications expose their data through data sources; the core resolves dependencies, validates archives, transfers archive parts, applies retention, and reports backup and restore events.

Installation

composer require adachsoft/data-backup
composer require nyholm/psr7

The contracts package is installed as a dependency. The PSR-7 implementation is required by the example below; applications may use another PSR-17 stream factory.

Requirements

  • PHP 8.3 or later.
  • Composer for dependency installation.
  • A PSR-17 stream factory implementation, such as nyholm/psr7, when creating streams for the provided archive format and storage implementations.

Components

  • LocalBackupTarget exposes a system's registered data sources for in-process export and import. It supports an optional consistency guard, schema migrator, and archive ID generator.
  • BackupService copies archive parts into the configured format, saves them to an archive storage, applies retention for the matching system and instance, and emits backup or restore events.
  • JsonArchiveFormat is a stream-based JSON archive format with per-part integrity checks. An optional clock supplies the manifest's UTC creation time; without one, the format uses the current UTC time.
  • InMemoryArchiveStorage stores archives in process memory. It is useful for tests and examples, but it is not durable storage.
  • Dependency resolution, validation, ID mapping, and retention policies are provided by the core package.

Archive formats and storage implementations are independent: the format serializes archive bytes, while storage keeps those bytes and their manifest.

Manifest serialization

AdachSoft\DataBackup\Serialization\ArchiveManifestCodec converts an ArchiveManifest to and from PHP arrays and JSON independently of the archive byte format or storage. Use encode() and decode() to persist manifest JSON alongside archive bytes; malformed JSON or manifest data raises InvalidManifestException.

Usage

Minimal wiring

Replace ApplicationDataSourceRegistry with the registry implementation for your application. The in-memory storage in this example does not persist data after the process exits.

use AdachSoft\DataBackup\InMemory\InMemoryArchiveStorage;
use AdachSoft\DataBackup\InMemory\JsonArchiveFormat;
use AdachSoft\DataBackup\Service\BackupService;
use AdachSoft\DataBackup\Target\LocalBackupTarget;
use AdachSoft\DataBackupContracts\Collection\DataSourceIdCollection;
use AdachSoft\DataBackupContracts\Dto\ExportRequest;
use AdachSoft\DataBackupContracts\ValueObject\LabelMap;
use DateTimeImmutable;
use DateTimeZone;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Clock\ClockInterface;

$streamFactory = new Psr17Factory();
$clock = new class implements ClockInterface {
    public function now(): DateTimeImmutable
    {
        return new DateTimeImmutable('now', new DateTimeZone('UTC'));
    }
};

$registry = new ApplicationDataSourceRegistry();
$format = new JsonArchiveFormat($streamFactory, $clock);
$target = new LocalBackupTarget(
    $registry,
    $format,
    $streamFactory,
    'my-application',
    'production-eu-1',
    '2.4.0',
);
$storage = new InMemoryArchiveStorage('memory', $streamFactory);
$backupService = new BackupService($format, $streamFactory, null, null, $clock);

$archiveRef = $backupService->backup(
    $target,
    $storage,
    new ExportRequest(new DataSourceIdCollection(), new LabelMap()),
);

An empty DataSourceIdCollection requests all registered sources. A non-empty collection requests those sources and their transitive dependencies. Supply labels in ExportRequest to attach metadata such as keep=true to an archive.

Implementing a record data source

An application implements RecordDataSourceInterface for each record-based part. The example below omits application-specific repository and report construction details:

use AdachSoft\DataBackupContracts\Collection\DataSourceIdCollection;
use AdachSoft\DataBackupContracts\Contract\RecordDataSourceInterface;
use AdachSoft\DataBackupContracts\Contract\RecordReaderInterface;
use AdachSoft\DataBackupContracts\Contract\RecordWriterInterface;
use AdachSoft\DataBackupContracts\Dto\ImportContext;
use AdachSoft\DataBackupContracts\Dto\SourceImportReport;
use AdachSoft\DataBackupContracts\Enum\ImportModeEnum;
use AdachSoft\DataBackupContracts\Enum\PartKindEnum;
use AdachSoft\DataBackupContracts\ValueObject\DataSourceId;

final class AccountDataSource implements RecordDataSourceInterface
{
    public function __construct(private AccountRepository $repository)
    {
    }

    public function getId(): DataSourceId
    {
        return new DataSourceId('auth.accounts');
    }

    public function getSchemaVersion(): int
    {
        return 1;
    }

    public function getKind(): PartKindEnum
    {
        return PartKindEnum::RECORDS;
    }

    public function getDependencies(): DataSourceIdCollection
    {
        return new DataSourceIdCollection();
    }

    public function exportRecords(RecordWriterInterface $writer): void
    {
        foreach ($this->repository->iterateRecords() as $record) {
            $writer->write($record);
        }
    }

    public function importRecords(RecordReaderInterface $reader, ImportContext $context): SourceImportReport
    {
        if (!$context->dryRun && $context->mode === ImportModeEnum::REPLACE) {
            $this->repository->clear();
        }

        foreach ($reader as $record) {
            // Validate in dry-run mode; only persist when dryRun is false.
            $newId = $this->repository->importOrPreviewId($record, $context);
            $context->idMap->record($this->getId(), $record->id, $newId);
        }

        return $this->repository->createImportReport($this->getId(), $context);
    }
}

REPLACE clearing and dryRun behavior are the source's responsibility. A source must not change application data when ImportContext::$dryRun is true. It should still validate records and, when dependent sources need the mappings, provide the per-import target IDs through ImportContext::$idMap without persisting changes.

When importing a parent source, record each archived identifier's target identifier with idMap->record($parentSourceId, $oldId, $newId). A dependent source resolves references with idMap->resolve($parentSourceId, $oldId) before storing them. All sources in one import share the same IdMapInterface instance.

File-based systems

DirectoryBlobDataSource exposes a directory tree as a blob-based data source. Each regular file is exported with its relative path as the blob ID, using / separators and deterministic ordering. Symbolic links and non-regular files are skipped; a missing source directory produces no blobs.

use AdachSoft\DataBackup\Source\DirectoryBlobDataSource;
use AdachSoft\DataBackup\Source\StringCollection;
use AdachSoft\DataBackupContracts\ValueObject\DataSourceId;
use Nyholm\Psr7\Factory\Psr17Factory;

$files = new DirectoryBlobDataSource(
    new DataSourceId('app.files'),
    '/var/www/app/var/data',
    new Psr17Factory(),
    new StringCollection(['*.lock', 'auth/sessions.json']),
);

Exclusion patterns use fnmatch() with FNM_PATHNAME against the relative path. A pattern without /, such as *.lock, also matches the basename at any directory depth. Imports reject unsafe blob paths and write each file through a temporary file in its destination directory before an atomic rename. MERGE honors the selected conflict policy; REPLACE removes files absent from the archive and removes directories left empty, while excluded files remain untouched. Dry runs report the same import counts without changing the filesystem.

The source does not freeze application writes while it reads or replaces files. Coordinate consistency through the caller's ConsistencyGuardInterface when the application may be changing the directory during backup or restore.

Contracts

The shared interfaces, value objects, DTOs, enums, and immutable collections are documented in adachsoft/data-backup-contracts.