Reimporting content: where updates are allowed and where to stop

Compare create-only, fill-empty and explicit field updates in MySQL 8.4: preserve manual body and SEO edits, distinguish NULL from an empty string and reject stale approval by revision.

The ornament has a clear boundary around the flowers: a field update needs a defined area too.
The ornament has a clear boundary around the flowers: a field update needs a defined area too.

Imagine this: the author has revised the introduction and shortened the SEO description in the editor. Meanwhile, an earlier text package reaches the importer again. It is formally the same article: the key and locale match. Yet “repeat” does not explain whether to preserve the author's changes, fill gaps or apply a new revision.

The ContentImport module runs inside the same application, using only its own isolated synthetic MySQL 8.4/InnoDB schema through native PDO. The mode names define this exercise’s agreement and do not promise identical behavior in the current CMS importer. One call handles one locale of one record, without publication, routes or notifications.

A useful importer answers that question before writing. It accepts a separate policy, reports the actual decision for each field and stops when approval refers to an outdated state. In this example, three modes, a list of approved changes and a record revision establish that boundary.

The external package proposes text; the application decides

For initial demo data, defining a permanent owner for each field is often sufficient: the system updates its fields and the author retains theirs. Reimporting an editorial package is more involved. Sometimes a new SEO description should be accepted while the manually edited body stays. A permanent ban on all changes will not help; the specific operation needs narrowly scoped approval.

The teaching model's package contains sourceKey, locale and proposed body and seo_description values. A trusted caller supplies the mode, expected revision and approved fields separately. A force flag inside an uploaded file cannot itself authorize a change. In a real interface, the caller first checks access and shows the author a diff.

What “empty” actually means

State Meaning in this model
The package omits a key The package proposes nothing for that field.
The database stores NULL The field has not been populated.
The database stores '' The author deliberately left an empty string.
The package supplies null Invalid package: reject the operation.

This distinction matters more than the name fill-empty. An empty() or trim($value) === '' check would erase the boundary between an absent value and deliberate clearing. Here, only SQL NULL can be filled; a whitespace string remains a string too. Another system may choose a different convention, but it must declare and test it.

An omitted key does not trigger deletion. On initial creation, an omitted field becomes NULL; on reimport, it does not enter the decision at all. This example has no separate “reset to NULL” operation.

Mode Record absent Record already exists
create-only Create a draft. Preserve the entire record.
fill-empty Return missing. Fill only supplied fields whose stored value is NULL.
explicit-update Return missing. With a matching revision, change only approved fields.

The next step in the shared project

Continue the same Symfony project, article_demo, built from the official skeleton. Run commands from its root and preserve earlier routes, services and data. Requirements are PHP 8.4+, Composer 2, PDO MySQL and MySQL 8.4. This synthetic scenario uses the previously introduced shared App\Infrastructure\MysqlLab and guarded disposable MySQL fixture with its fixtures/mysql_labs/run.sh wrapper, which supplies server configuration for the lab run.

composer require 'ext-pdo:*' 'ext-pdo_mysql:*' --no-interaction
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/ContentImport src/Command tests/ContentImport

After installation, retain composer.lock and symfony.lock: the 8.1.* constraint selects a branch, while Composer's resolved dependencies establish the exact installed versions. The following blocks contain the complete files.

src/ContentImport/ImportMode.php:

<?php

declare(strict_types=1);

namespace App\ContentImport;

enum ImportMode: string
{
    case CreateOnly = 'create-only';
    case FillEmpty = 'fill-empty';
    case ExplicitUpdate = 'explicit-update';
}

src/ContentImport/ContentPackage.php:

<?php

declare(strict_types=1);

namespace App\ContentImport;

use InvalidArgumentException;

final readonly class ContentPackage
{
    public const FIELDS = ['body', 'seo_description'];

    /** @param array<string, string> $fields */
    public function __construct(public string $sourceKey, public string $locale, public array $fields)
    {
        if (preg_match('/\A[a-z][a-z0-9-]{0,63}\z/', $sourceKey) !== 1) {
            throw new InvalidArgumentException('Invalid source key.');
        }

        if (!in_array($locale, ['uk', 'ru', 'en'], true) || $fields === []) {
            throw new InvalidArgumentException('Locale and at least one field are required.');
        }

        foreach ($fields as $name => $value) {
            if (!in_array($name, self::FIELDS, true) || !is_string($value)) {
                throw new InvalidArgumentException('Unknown field or non-string value.');
            }
        }
    }
}

The key restriction makes identity explicit; it is not a URL generator. The locale list is deliberately short. Field validation rejects accidental publish_at or publication_state input before SQL. An empty array is rejected too: an empty delivery does not count as a meaningful operation.

The schema keeps publication outside the package's authority

src/ContentImport/LabDatabase.php:

<?php

declare(strict_types=1);

namespace App\ContentImport;

use App\Infrastructure\MysqlLab;
use PDO;

final class LabDatabase
{
    public static function connect(): PDO
    {
        return self::createFixture()->runtime();
    }

    public static function createFixture(): MysqlLab
    {
        $fixture = MysqlLab::create('content_import');
        try {
            $fixture->migrator()->exec(<<<'SQL'
                CREATE TABLE content (
                    id BIGINT SIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    source_key VARCHAR(64) NOT NULL,
                    locale VARCHAR(2) NOT NULL CHECK (locale IN ('uk', 'ru', 'en')),
                    revision BIGINT SIGNED NOT NULL DEFAULT 1 CHECK (revision > 0),
                    body LONGTEXT NULL,
                    seo_description LONGTEXT NULL,
                    public_path LONGTEXT NULL,
                    publication_state LONGTEXT NOT NULL DEFAULT ('draft'),
                    publish_at BIGINT SIGNED NULL,
                    UNIQUE (source_key, locale)
                ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin
                SQL);
            return $fixture;
        } catch (\Throwable $error) {
            $fixture->close();
            throw $error;
        }
    }
}

The unique source_key, locale pair connects repeated deliveries without mixing translations. The revision belongs to that locale's entire record. URL, state and date are separate columns that the package does not accept. A new record remains a draft without an address or publication time; the demonstration's update of an already published record is not an instruction to republish it.

LabDatabase::createFixture() creates a separate temporary schema through MysqlLab::create('content_import'). A separate migrator connection executes DDL before business transactions; the runtime connection has only DML privileges and cannot execute CREATE, ALTER or DROP. The table uses InnoDB, CHECK constraints for the locale and positive revision, VARCHAR identities with utf8mb4_0900_bin, and LONGTEXT text fields. This creates a clean teaching schema rather than atomically upgrading an existing one: MySQL DDL can cause an implicit commit. It does not automatically copy data from the old SQLite database. A real application also needs its own authorization, body formatting and metadata validation rules.

Approval is checked twice

src/ContentImport/ContentImporter.php:

<?php

declare(strict_types=1);

namespace App\ContentImport;

use InvalidArgumentException;
use LogicException;
use PDO;
use PDOException;

final readonly class ContentImporter
{
    public function __construct(private PDO $pdo)
    {
        if ($pdo->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'mysql'
            || (int) $pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION
            || (bool) $pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES)
            || (int) $pdo->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE) !== PDO::FETCH_ASSOC) {
            throw new InvalidArgumentException('MySQL with native prepares, exception mode and associative fetch is required.');
        }
    }

    /** @return array<string, mixed>|null */
    public function find(string $sourceKey, string $locale): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT * FROM content WHERE source_key = :key AND locale = :locale'
        );
        $statement->execute(['key' => $sourceKey, 'locale' => $locale]);
        $row = $statement->fetch();
        $statement->closeCursor();

        return $row === false ? null : $row;
    }

    /**
     * @param list<string> $approvedFields
     * @return array{status: string, revision: ?int, fields: array<string, string>}
     */
    public function apply(
        ContentPackage $package,
        ImportMode $mode,
        ?int $expectedRevision = null,
        array $approvedFields = [],
    ): array {
        if ($this->pdo->inTransaction()) {
            throw new LogicException('This importer owns its transaction.');
        }

        if ($mode === ImportMode::ExplicitUpdate) {
            if ($expectedRevision === null || $expectedRevision < 1 || $approvedFields === []) {
                throw new InvalidArgumentException('Explicit update requires revision and fields.');
            }

            foreach ($approvedFields as $field) {
                if (!is_string($field) || !array_key_exists($field, $package->fields)) {
                    throw new InvalidArgumentException('Approve only fields present in the package.');
                }
            }

            if (!array_is_list($approvedFields) || count(array_unique($approvedFields)) !== count($approvedFields)) {
                throw new InvalidArgumentException('Approved fields must be a distinct list.');
            }
        } elseif ($expectedRevision !== null || $approvedFields !== []) {
            throw new InvalidArgumentException('Approval arguments belong to explicit update.');
        }

        $this->pdo->beginTransaction();
        try {
            $result = $this->applyLocked($package, $mode, $expectedRevision, $approvedFields);
            $this->pdo->commit();
            return $result;
        } catch (\Throwable $error) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            throw $error;
        }
    }

    /** @param list<string> $approvedFields
     * @return array{status: string, revision: ?int, fields: array<string, string>}
     */
    private function applyLocked(ContentPackage $package, ImportMode $mode, ?int $expectedRevision, array $approvedFields): array
    {
        if ($mode === ImportMode::CreateOnly) {
            $statement = $this->pdo->prepare(<<<'SQL'
                INSERT INTO content (source_key, locale, body, seo_description)
                VALUES (:key, :locale, :body, :seo)
                SQL);
            $created = true;
            try {
                $statement->execute([
                    'key' => $package->sourceKey,
                    'locale' => $package->locale,
                    'body' => $package->fields['body'] ?? null,
                    'seo' => $package->fields['seo_description'] ?? null,
                ]);
            } catch (PDOException $error) {
                // Only the business identity unique constraint can duplicate here.
                // InnoDB rolls back this statement, not our transaction.
                if ((int) ($error->errorInfo[1] ?? 0) !== 1062) {
                    throw $error;
                }
                $created = false;
            }
            return [
                'status' => $created ? 'created' : 'exists',
                'revision' => $created ? 1 : null,
                'fields' => array_fill_keys(array_keys($package->fields), $created ? 'created' : 'preserved'),
            ];
        }

        // A locking current read, not a repeatable-read snapshot. The lock spans
        // field policy evaluation and the revision-guarded write.
        $read = $this->pdo->prepare('SELECT * FROM content WHERE source_key = ? AND locale = ? FOR UPDATE');
        $read->execute([$package->sourceKey, $package->locale]);
        $current = $read->fetch();
        $read->closeCursor();
        if ($current === false) {
            return ['status' => 'missing', 'revision' => null, 'fields' => []];
        }

        $observedRevision = (int) $current['revision'];
        if ($mode === ImportMode::ExplicitUpdate && $observedRevision !== $expectedRevision) {
            return ['status' => 'conflict', 'revision' => $observedRevision, 'fields' => []];
        }

        $changes = [];
        $actions = [];
        foreach ($package->fields as $field => $value) {
            $selected = $mode === ImportMode::FillEmpty
                ? $current[$field] === null
                : in_array($field, $approvedFields, true);
            if (!$selected) {
                $actions[$field] = 'preserved';
            } elseif ($current[$field] === $value) {
                $actions[$field] = 'unchanged';
            } else {
                $changes[$field] = $value;
                $actions[$field] = 'applied';
            }
        }
        if ($changes === []) {
            return ['status' => 'unchanged', 'revision' => $observedRevision, 'fields' => $actions];
        }

        $assignments = [];
        $parameters = [
            'key' => $package->sourceKey,
            'locale' => $package->locale,
            'revision' => $observedRevision,
        ];
        foreach ($changes as $field => $value) {
            $assignments[] = $field.' = :value_'.$field;
            $parameters['value_'.$field] = $value;
        }
        $statement = $this->pdo->prepare(
            'UPDATE content SET '.implode(', ', $assignments).', revision = revision + 1'
            .' WHERE source_key = :key AND locale = :locale AND revision = :revision'
        );
        $statement->execute($parameters);
        if ($statement->rowCount() !== 1) {
            return ['status' => 'conflict', 'revision' => null, 'fields' => []];
        }
        return ['status' => 'updated', 'revision' => $observedRevision + 1, 'fields' => $actions];
    }
}

In create-only, the unique source_key, locale pair prevents duplicates. The code executes a plain INSERT and maps only native MySQL error 1062 to exists: this insert does not supply a primary key, so only the business identity can duplicate in this schema. Under InnoDB error-handling rules, that error rolls back the statement rather than the entire transaction. Other SQL errors are not concealed. exists means a skipped insertion, not confirmation that the new text was accepted.

For update modes, the importer starts its own transaction and reads the row with SELECT ... FOR UPDATE. This is an InnoDB locking current read, not an earlier repeatable-read snapshot; the lock spans field selection and writing. For explicit updates, the first check compares the expected revision with the revision read. If the author approved revision 2 but another connection has already saved revision 3, the result is conflict without changes. The article must be read again, its changes inspected and a new decision made.

The second check remains inside UPDATE ... WHERE revision = :revision: the write must change exactly one row. This is compare-and-swap alongside row locking. fill-empty evaluates NULL while holding that lock, so another writer cannot change the same row between policy evaluation and the write. If a manual SEO description was saved earlier, the current read sees and preserves it.

The condition depends on shared write discipline: every change must increment the revision. Deleting a row and recreating the same identity with an initial revision cannot leave old approvals safe. That lifecycle needs a separate immutable identity or generation; the example has no deletion.

Parameters carry values, while column names come exclusively from the validated list. PDO cannot bind a column identifier as a parameter, so adding :column would not replace validation. Building SQL from arbitrary external JSON keys would break the model's boundary.

The report describes a decision, not the delivery's contents

An operation returns created, exists, missing, unchanged, updated or conflict. Within fields, created, applied, preserved or unchanged describe the fields considered. Current body and SEO text are deliberately excluded: a technical log needs the decision, while content comparison belongs in an appropriately authorized interface.

Successful creation returns the initial revision, 1. After an update, the code checks rowCount() === 1 and returns the revision read under the lock plus one; it does not use SQL RETURNING. An expected-revision conflict returns the observed value, while a failed conditional UPDATE returns null. exists does not declare a current revision either. New approval requires a fresh read.

A read result does not guarantee that the state will remain unchanged forever. Even unchanged describes the state observed during the operation. Driver errors, including deadlocks and lock-wait timeouts, remain exceptions rather than editorial conflict results. The importer rolls back its own active transaction and propagates the error; it does not retry automatically.

The importer requires PDO MySQL with native prepares, exception mode and associative fetching. After a read, PDOStatement::closeCursor releases the cursor but does not complete the transaction. apply() returns its result only after its own commit() succeeds; a write or commit error does not become a successful report. An existing caller transaction is rejected without committing or rolling it back. The atomic boundary covers one locale of one record, not an entire multilingual package; DDL is outside that boundary.

A sequence that can be checked

Symfony Console provides a separate command for the experiment. src/Command/ImportModesCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\ContentImport\ContentImporter;
use App\ContentImport\ContentPackage;
use App\ContentImport\ImportMode;
use App\ContentImport\LabDatabase;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:content-import-demo', description: 'Compare editorial import modes in an isolated MySQL fixture.')]
final class ImportModesCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $fixture = LabDatabase::createFixture();
        try {
            $pdo = $fixture->runtime();
            $importer = new ContentImporter($pdo);
            $created = $importer->apply(
                new ContentPackage('note-one', 'uk', ['body' => 'Initial body']),
                ImportMode::CreateOnly,
            );
            $pdo->exec(<<<'SQL'
                UPDATE content SET body = 'Hand edited', revision = revision + 1,
                    public_path = '/notes/retained', publication_state = 'published',
                    publish_at = 1900000000
                WHERE source_key = 'note-one' AND locale = 'uk'
                SQL);
            $incoming = new ContentPackage('note-one', 'uk', [
                'body' => 'Incoming body',
                'seo_description' => 'Incoming SEO',
            ]);
            $exists = $importer->apply($incoming, ImportMode::CreateOnly);
            $filled = $importer->apply($incoming, ImportMode::FillEmpty);
            $stale = $importer->apply($incoming, ImportMode::ExplicitUpdate, 2, ['body']);
            $updated = $importer->apply(
                new ContentPackage('note-one', 'uk', [
                    'body' => 'Still not approved',
                    'seo_description' => 'Approved SEO',
                ]),
                ImportMode::ExplicitUpdate,
                3,
                ['seo_description'],
            );
            $row = $importer->find('note-one', 'uk');
            $ok = array_column([$created, $exists, $filled, $stale, $updated], 'status')
                    === ['created', 'exists', 'updated', 'conflict', 'updated']
                && $row !== null
                && $row['body'] === 'Hand edited'
                && $row['seo_description'] === 'Approved SEO'
                && (int) $row['revision'] === 4
                && $row['public_path'] === '/notes/retained'
                && $row['publication_state'] === 'published'
                && (int) $row['publish_at'] === 1900000000;
            $output->writeln(json_encode(
                ['steps' => [$created, $exists, $filled, $stale, $updated], 'final' => $row, 'expected_state' => $ok],
                JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT,
            ));

            return $ok ? Command::SUCCESS : Command::FAILURE;
        } finally {
            $fixture->close();
        }
    }
}

Merge these definitions under the existing services key in config/services.yaml. Preserve earlier registrations, _defaults and imports; keep the rest of the file. DTOs and static factories do not need broad App\ service scanning.

services:
    App\Command\ImportModesCommand: ~

Only the command is registered; data objects and PDO are not automatically constructed as services. The command creates its own temporary MySQL fixture, prepares the schema through the migrator, runs the scenario through the runtime connection and closes the fixture in finally. Run it through the lab wrapper shown below.

The expected sequence is creation at revision 1, a manual edit to 2, skipped creation, SEO filling to 3, rejection of stale revision 2 and an approved SEO replacement to 4. The manual body, address, state and date should survive. The publish_at number is a test constant. The command compares these expectations with the state and returns a nonzero exit code on a mismatch; the code shown is not evidence of a completed run.

Rejections need tests too

tests/ContentImport/ContentImporterTest.php:

<?php

declare(strict_types=1);

namespace App\Tests\ContentImport;

use App\ContentImport\ContentImporter;
use App\ContentImport\ContentPackage;
use App\ContentImport\ImportMode;
use App\ContentImport\LabDatabase;
use App\Infrastructure\MysqlLab;
use InvalidArgumentException;
use LogicException;
use PDO;
use PDOException;
use PHPUnit\Framework\TestCase;

final class ContentImporterTest extends TestCase
{
    private MysqlLab $fixture;
    private PDO $pdo;
    private ContentImporter $importer;

    protected function setUp(): void
    {
        $this->fixture = LabDatabase::createFixture();
        $this->pdo = $this->fixture->runtime();
        $this->importer = new ContentImporter($this->pdo);
    }

    protected function tearDown(): void
    {
        $this->fixture->close();
    }

    public function testCreateOnlyNeverReplacesExistingContent(): void
    {
        $first = $this->importer->apply($this->package(['body' => 'First', 'seo_description' => 'Manual SEO']), ImportMode::CreateOnly);
        $again = $this->importer->apply($this->package(['body' => 'Other', 'seo_description' => 'Incoming SEO']), ImportMode::CreateOnly);

        self::assertSame('created', $first['status']);
        self::assertSame('exists', $again['status']);
        self::assertSame('First', $this->row()['body']);
        self::assertSame('Manual SEO', $this->row()['seo_description']);
        self::assertSame(1, (int) $this->pdo->query('SELECT count(*) FROM content')->fetchColumn());
    }

    public function testFillEmptyMeansNullAndPreservesAnIntentionalEmptyString(): void
    {
        $this->importer->apply($this->package(['body' => '']), ImportMode::CreateOnly);
        $result = $this->importer->apply(
            $this->package(['body' => 'Replacement', 'seo_description' => 'Filled SEO']),
            ImportMode::FillEmpty,
        );

        self::assertSame('', $this->row()['body']);
        self::assertSame('Filled SEO', $this->row()['seo_description']);
        self::assertSame(['body' => 'preserved', 'seo_description' => 'applied'], $result['fields']);
        self::assertSame(2, $result['revision']);
    }

    public function testRepeatedFillDoesNotAdvanceTheRevision(): void
    {
        $this->importer->apply($this->package(['body' => 'Manual']), ImportMode::CreateOnly);
        $package = $this->package(['seo_description' => 'SEO']);
        $this->importer->apply($package, ImportMode::FillEmpty);
        $this->pdo->exec("UPDATE content SET seo_description = 'Manual SEO', revision = revision + 1");
        $before = $this->row();
        $result = $this->importer->apply($package, ImportMode::FillEmpty);

        self::assertSame('unchanged', $result['status']);
        self::assertSame($before, $this->row());
    }

    public function testExplicitUpdateChangesOnlyApprovedFields(): void
    {
        $this->importer->apply(
            $this->package(['body' => 'Manual body', 'seo_description' => 'Manual SEO']),
            ImportMode::CreateOnly,
        );
        $this->pdo->exec("UPDATE content SET public_path = '/keep', publication_state = 'published', publish_at = 1900000000, revision = revision + 1");
        $result = $this->importer->apply(
            $this->package(['body' => 'Unapproved', 'seo_description' => 'Approved SEO']),
            ImportMode::ExplicitUpdate,
            2,
            ['seo_description'],
        );

        self::assertSame('updated', $result['status']);
        self::assertSame('Manual body', $this->row()['body']);
        self::assertSame('Approved SEO', $this->row()['seo_description']);
        self::assertSame('/keep', $this->row()['public_path']);
        self::assertSame('published', $this->row()['publication_state']);
        self::assertSame(1900000000, (int) $this->row()['publish_at']);
    }

    public function testAStaleRevisionProducesConflictWithoutWriting(): void
    {
        $this->importer->apply($this->package(['body' => 'Old']), ImportMode::CreateOnly);
        $this->importer->apply($this->package(['body' => 'New']), ImportMode::ExplicitUpdate, 1, ['body']);
        $before = $this->row();
        $result = $this->importer->apply(
            $this->package(['body' => 'Stale body', 'seo_description' => 'Stale SEO']),
            ImportMode::ExplicitUpdate,
            1,
            ['body', 'seo_description'],
        );

        self::assertSame('conflict', $result['status']);
        self::assertSame(2, $result['revision']);
        self::assertSame([], $result['fields']);
        self::assertSame($before, $this->row());
    }

    public function testUpdateModesDoNotCreateMissingRecords(): void
    {
        $package = $this->package(['body' => 'Text']);
        self::assertSame('missing', $this->importer->apply($package, ImportMode::FillEmpty)['status']);
        self::assertSame('missing', $this->importer->apply($package, ImportMode::ExplicitUpdate, 1, ['body'])['status']);
        self::assertNull($this->importer->find('note-one', 'uk'));
    }

    public function testOneLocaleDoesNotModifyAnother(): void
    {
        $this->importer->apply($this->package(['body' => 'UK']), ImportMode::CreateOnly);
        $this->importer->apply(new ContentPackage('note-one', 'en', ['body' => 'EN']), ImportMode::CreateOnly);
        $this->importer->apply($this->package(['body' => 'UK revised']), ImportMode::ExplicitUpdate, 1, ['body']);

        self::assertSame('UK revised', $this->row()['body']);
        self::assertSame('EN', $this->importer->find('note-one', 'en')['body']);
    }

    public function testMissingApprovalFailsBeforeAnyWrite(): void
    {
        $this->importer->apply($this->package(['body' => 'Keep']), ImportMode::CreateOnly);
        $before = $this->row();

        try {
            $this->importer->apply($this->package(['body' => 'Replace']), ImportMode::ExplicitUpdate, 1);
            self::fail('Expected missing approval rejection.');
        } catch (InvalidArgumentException) {
            self::assertSame($before, $this->row());
        }
    }

    public function testUnknownFieldsAndNullPayloadsAreRejected(): void
    {
        foreach ([['publication_state' => 'published'], ['body' => null]] as $fields) {
            try {
                $this->package($fields);
                self::fail('Expected package validation failure.');
            } catch (InvalidArgumentException) {
                self::assertSame(0, (int) $this->pdo->query('SELECT count(*) FROM content')->fetchColumn());
            }
        }
    }

    public function testCallerTransactionIsNotCommittedOrRolledBack(): void
    {
        $this->pdo->beginTransaction();

        try {
            try {
                $this->importer->apply($this->package(['body' => 'Text']), ImportMode::CreateOnly);
                self::fail('Expected transaction ownership rejection.');
            } catch (LogicException) {
                self::assertTrue($this->pdo->inTransaction());
            }
        } finally {
            $this->pdo->rollBack();
        }
    }

    public function testDatabaseFailureIsNotDisguisedAsAnUnchangedResult(): void
    {
        $this->importer->apply($this->package(['body' => 'Keep']), ImportMode::CreateOnly);
        $before = $this->row();
        $this->fixture->migrator()->exec(<<<'SQL'
            CREATE TRIGGER reject_update BEFORE UPDATE ON content FOR EACH ROW
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'test_update_blocked'
            SQL);

        try {
            $this->importer->apply($this->package(['body' => 'Replace']), ImportMode::ExplicitUpdate, 1, ['body']);
            self::fail('Expected a database error.');
        } catch (PDOException $error) {
            self::assertStringContainsString('test_update_blocked', $error->getMessage());
            self::assertSame($before, $this->row());
            self::assertFalse($this->pdo->inTransaction());
        }
        $this->fixture->migrator()->exec('DROP TRIGGER reject_update');
        self::assertSame('updated', $this->importer->apply($this->package(['body' => 'Retry']), ImportMode::ExplicitUpdate, 1, ['body'])['status']);
    }

    public function testIndependentConnectionSeesCommittedRevisionAndRejectsStaleWrite(): void
    {
        $other = new PDO($this->fixture->runtimeDsn(), $this->fixture->runtimeUser(), $this->fixture->runtimePassword(), [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        $editor = new ContentImporter($other);
        $this->importer->apply($this->package(['body' => 'First']), ImportMode::CreateOnly);
        self::assertSame(1, (int) $editor->find('note-one', 'uk')['revision']);
        $this->importer->apply($this->package(['body' => 'Winner']), ImportMode::ExplicitUpdate, 1, ['body']);
        self::assertSame('conflict', $editor->apply($this->package(['body' => 'Loser']), ImportMode::ExplicitUpdate, 1, ['body'])['status']);
        self::assertSame('Winner', $editor->find('note-one', 'uk')['body']);
    }

    public function testSourceKeyBoundaryIsValidatedBeforeMutation(): void
    {
        $key = 'a'.str_repeat('b', 63);
        self::assertSame('created', $this->importer->apply(new ContentPackage($key, 'uk', ['body' => 'Boundary']), ImportMode::CreateOnly)['status']);
        try {
            new ContentPackage($key.'c', 'uk', ['body' => 'Too long']);
            self::fail('Oversized source key must be rejected.');
        } catch (InvalidArgumentException) {
            self::assertSame(1, (int) $this->pdo->query('SELECT COUNT(*) FROM content')->fetchColumn());
        }
    }

    private function package(array $fields): ContentPackage
    {
        return new ContentPackage('note-one', 'uk', $fields);
    }

    private function row(): array
    {
        return $this->importer->find('note-one', 'uk')
            ?? throw new LogicException('Fixture row is missing.');
    }
}

The tests check repeated creation, manual SEO after filling, NULL versus an empty string, narrow approval, stale revisions, missing records, locale independence, invalid packages, caller transactions and the 64-ASCII-character source-key boundary. A separate native PDO connection sharing the schema sees the committed revision and rejects stale approval. The failure test creates a trigger through the migrator using SIGNAL SQLSTATE '45000', checks that the entire record is unchanged and rollback has completed, then checks a successful retry after removing the trigger. The runtime path executes DML only.

bash fixtures/mysql_labs/run.sh php bin/console app:content-import-demo
APP_ENV=test bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/ContentImport/ContentImporterTest.php --testdox --log-junit content-import-tests.xml

Before running these commands, install the shared MySQL fixture and helper from the earlier chapter, and check PHP, pdo_mysql, Composer platform requirements and the Symfony container in dev and test. The wrapper below selects the guarded disposable lab server; the command and tests create their own schemas through the helper. The exit code and PHPUnit report establish the result of each actual run.

The check using two separate connections is sequential: the first write commits before the stale-revision attempt. It checks commit visibility and stale-approval rejection in MySQL, but it is not an experiment with simultaneous writers. Lock waiting, deadlocks and retry policy require separate controlled concurrency scenarios.

Stopping a repeat can be the correct result. A clear conflict lets the author reconsider changes; a vague “import successful” can conceal either lost text or an entirely unapplied revision. The update boundary must be visible both in code and in the report a person reads.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

  1. Symfony Core Editing a published article: how to avoid losing another edit
  2. Symfony Core Demo data, baselines and user content: preserving manual changes
  3. Editorial An article package for three languages: from the author's chat to the CMS

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article