Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions Build/phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2844,12 +2844,6 @@ parameters:
count: 1
path: ../Classes/EventListener/Mail/AttachmentFromTypoScript.php

-
message: '#^Binary operation "\+" between mixed and 1 results in an error\.$#'
identifier: binaryOp.invalid
count: 1
path: ../Classes/EventListener/Order/Create/Number.php

-
message: '#^Cannot cast mixed to int\.$#'
identifier: cast.int
Expand Down
141 changes: 141 additions & 0 deletions Classes/Domain/Order/Number/NumberCounter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Domain\Order\Number;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use RuntimeException;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;

/**
* Increments the counters of the order, invoice and delivery numbers.
*
* The counters are stored in the sys_registry with the namespace "tx_cart",
* like the TYPO3 Registry does, so existing counters are continued. Unlike
* the Registry, the counter is read and written in one transaction and the
* row is locked (SELECT ... FOR UPDATE, on SQLite by a write first), so
* concurrent requests never get the same number. The Registry is not used
* because it caches the entries of a namespace for the whole request.
*/
final readonly class NumberCounter
{
private const TABLE = 'sys_registry';

private const NAMESPACE = 'tx_cart';

private const MAX_ATTEMPTS = 3;

public function __construct(
private ConnectionPool $connectionPool,
) {
}

/**
* @return positive-int the incremented counter, 1 for a new counter
*/
public function increment(string $key): int
{
$connection = $this->connectionPool->getConnectionForTable(self::TABLE);

for ($attempt = 1; ; $attempt++) {
try {
return $connection->transactional(
static fn (Connection $connection): int => self::incrementInTransaction($connection, $key)
);
} catch (UniqueConstraintViolationException $exception) {
// a concurrent request created the counter, it is locked by SELECT ... FOR UPDATE now
if ($attempt >= self::MAX_ATTEMPTS) {
throw new RuntimeException(
'The counter "' . $key . '" could not be created.',
1795506001,
$exception
);
}
}
}
}

/**
* @return positive-int
*/
private static function incrementInTransaction(Connection $connection, string $key): int
{
$identifier = ['entry_namespace' => self::NAMESPACE, 'entry_key' => $key];
$isSqlite = $connection->getDatabasePlatform() instanceof SQLitePlatform;
if ($isSqlite) {
// SQLite does not support SELECT ... FOR UPDATE, a write locks the database until the commit
$connection->executeStatement(
'UPDATE ' . $connection->quoteIdentifier(self::TABLE)
. ' SET ' . $connection->quoteIdentifier('entry_value') . ' = ' . $connection->quoteIdentifier('entry_value')
. ' WHERE ' . $connection->quoteIdentifier('entry_namespace') . ' = ?'
. ' AND ' . $connection->quoteIdentifier('entry_key') . ' = ?',
array_values($identifier)
);
}

$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->getRestrictions()->removeAll();
$queryBuilder
->select('entry_value')
->from(self::TABLE)
->where(
$queryBuilder->expr()->eq('entry_namespace', $queryBuilder->createNamedParameter(self::NAMESPACE)),
$queryBuilder->expr()->eq('entry_key', $queryBuilder->createNamedParameter($key))
)
;
if (!$isSqlite) {
$queryBuilder->getConcreteQueryBuilder()->forUpdate();
}

$storedValue = $queryBuilder->executeQuery()->fetchOne();

if ($storedValue === false) {
$connection->insert(
self::TABLE,
[
'entry_namespace' => self::NAMESPACE,
'entry_key' => $key,
'entry_value' => serialize(1),
],
['entry_value' => Connection::PARAM_LOB]
);

return 1;
}

$number = max(0, self::unserializeCounter($storedValue)) + 1;

$connection->update(
self::TABLE,
['entry_value' => serialize($number)],
$identifier,
['entry_value' => Connection::PARAM_LOB]
);

return $number;
}

private static function unserializeCounter(mixed $storedValue): int
{
if (is_resource($storedValue)) {
$storedValue = stream_get_contents($storedValue);
}
if (!is_string($storedValue)) {
return 0;
}

$value = unserialize($storedValue, ['allowed_classes' => false]);

return is_numeric($value) ? (int) $value : 0;
}
}
14 changes: 7 additions & 7 deletions Classes/EventListener/Order/Create/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,23 @@
* LICENSE file that was distributed with this source code.
*/

use Extcode\Cart\Domain\Order\Number\NumberCounter;
use Extcode\Cart\Domain\Repository\Order\ItemRepository as OrderItemRepository;
use Extcode\Cart\Event\Order\NumberGeneratorEventInterface;
use TYPO3\CMS\Core\Registry;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;

abstract class Number
{
private readonly NumberCounter $numberCounter;

public function __construct(
protected PersistenceManager $persistenceManager,
protected OrderItemRepository $orderItemRepository,
protected array $options = []
protected array $options = [],
?NumberCounter $numberCounter = null
) {
$this->numberCounter = $numberCounter ?? GeneralUtility::makeInstance(NumberCounter::class);
}

abstract public function __invoke(NumberGeneratorEventInterface $event): void;
Expand All @@ -32,11 +36,7 @@ abstract protected function getRegistryName(NumberGeneratorEventInterface $event

protected function generateNumber(NumberGeneratorEventInterface $event): string
{
$registry = GeneralUtility::makeInstance(Registry::class);

$numberInRegistry = $registry->get('tx_cart', $this->getRegistryName($event));
$numberInRegistry = $numberInRegistry ? $numberInRegistry + 1 : 1;
$registry->set('tx_cart', $this->getRegistryName($event), $numberInRegistry);
$numberInRegistry = $this->numberCounter->increment($this->getRegistryName($event));

$format = $this->options['format'] ?? '%d';
$numberInRegistryWithOffset = $numberInRegistry + (int) ($this->options['offset'] ?? 0);
Expand Down
111 changes: 111 additions & 0 deletions Tests/Functional/Domain/Order/Number/NumberCounterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Tests\Functional\Domain\Order\Number;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use Extcode\Cart\Domain\Order\Number\NumberCounter;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use TYPO3\CMS\Core\Registry;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\TestingFramework\Core\Functional\FunctionalTestCase;

#[CoversClass(NumberCounter::class)]
final class NumberCounterTest extends FunctionalTestCase
{
protected array $testExtensionsToLoad = [
'extcode/cart',
];

private NumberCounter $subject;

protected function setUp(): void
{
parent::setUp();

$this->subject = new NumberCounter($this->getConnectionPool());
}

#[Test]
public function newCounterStartsWithOne(): void
{
self::assertSame(1, $this->subject->increment('lastInvoice_1'));
self::assertSame(2, $this->subject->increment('lastInvoice_1'));
self::assertSame(3, $this->subject->increment('lastInvoice_1'));
}

#[Test]
public function countersAreIndependentOfEachOther(): void
{
self::assertSame(1, $this->subject->increment('lastInvoice_1'));
self::assertSame(1, $this->subject->increment('lastInvoice_2'));
self::assertSame(1, $this->subject->increment('lastOrder_1'));
self::assertSame(2, $this->subject->increment('lastInvoice_1'));
}

#[Test]
public function continuesCounterWrittenByTheRegistry(): void
{
GeneralUtility::makeInstance(Registry::class)->set('tx_cart', 'lastInvoice_1', 41);

self::assertSame(42, $this->subject->increment('lastInvoice_1'));
}

#[Test]
public function storesCounterReadableByTheRegistry(): void
{
$this->subject->increment('lastInvoice_1');
$this->subject->increment('lastInvoice_1');

self::assertSame(2, $this->getStoredValue('tx_cart', 'lastInvoice_1'));
}

#[Test]
public function readsCurrentValueEvenIfTheRegistryCachedAnOlderOne(): void
{
$registry = GeneralUtility::makeInstance(Registry::class);
$registry->set('tx_cart', 'lastInvoice_1', 5);

// another request increments the counter in the meantime
$this->getConnectionPool()
->getConnectionForTable('sys_registry')
->update(
'sys_registry',
['entry_value' => serialize(7)],
['entry_namespace' => 'tx_cart', 'entry_key' => 'lastInvoice_1']
)
;
self::assertSame(5, $registry->get('tx_cart', 'lastInvoice_1'));

self::assertSame(8, $this->subject->increment('lastInvoice_1'));
}

#[Test]
public function doesNotChangeEntriesOfOtherNamespaces(): void
{
GeneralUtility::makeInstance(Registry::class)->set('tx_other', 'lastInvoice_1', 100);

self::assertSame(1, $this->subject->increment('lastInvoice_1'));
self::assertSame(100, $this->getStoredValue('tx_other', 'lastInvoice_1'));
}

private function getStoredValue(string $namespace, string $key): mixed
{
$storedValue = $this->getConnectionPool()
->getConnectionForTable('sys_registry')
->select(['entry_value'], 'sys_registry', ['entry_namespace' => $namespace, 'entry_key' => $key])
->fetchOne()
;
self::assertIsString($storedValue);

return unserialize($storedValue, ['allowed_classes' => false]);
}
}
Loading