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
16 changes: 16 additions & 0 deletions Classes/Domain/Repository/ApiResourceRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ class ApiResourceRepository
{
protected ?FrontendInterface $cache;

/**
* API resources already read in this process, by cache identifier. `getByEntity()` runs for every serialized
* entity, so reading and unserializing the cache entry on each call would make large collections slow.
*
* @var array<string, ApiResource[]>
*/
protected array $apiResourcesByCacheIdentifier = [];

public function __construct(
protected readonly CacheManager $cacheManager,
protected readonly ReflectionService $reflectionService,
Expand All @@ -32,6 +40,14 @@ public function getAll(): array
{
$cacheIdentifier = $this->buildCacheIdentifier();

return $this->apiResourcesByCacheIdentifier[$cacheIdentifier] ??= $this->loadAll($cacheIdentifier);
}

/**
* @return ApiResource[]
*/
protected function loadAll(string $cacheIdentifier): array
{
$apiResources = $this->cache->get($cacheIdentifier);

if ($apiResources !== false) {
Expand Down
51 changes: 51 additions & 0 deletions Tests/Functional/Dispatcher/ApiResourceCacheDispatcherTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace SourceBroker\T3api\Tests\Functional\Dispatcher;

use PHPUnit\Framework\Attributes\Test;
use SourceBroker\T3api\Tests\Functional\Fixtures\ReadCountingCacheBackend;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;

class ApiResourceCacheDispatcherTest extends AbstractDispatcherTestCase
{
protected array $configurationToUseInTestInstance = [
'SYS' => [
'caching' => [
'cacheConfigurations' => [
't3api' => [
'frontend' => VariableFrontend::class,
'backend' => ReadCountingCacheBackend::class,
'groups' => ['system'],
],
],
],
],
];

protected function setUp(): void
{
parent::setUp();
$this->importCSVDataSet(__DIR__ . '/../Fixtures/products.csv');
$this->importCSVDataSet(__DIR__ . '/../Fixtures/categories.csv');
$this->importCSVDataSet(__DIR__ . '/../Fixtures/tags.csv');
}

#[Test]
public function collectionWithRelatedResourcesReadsApiResourcesFromCacheOnce(): void
{
$this->dispatchGet('https://example.com/_api/products');

self::assertSame(1, $this->getT3apiCacheBackend()->readCount);
}

private function getT3apiCacheBackend(): ReadCountingCacheBackend
{
$backend = $this->get(CacheManager::class)->getCache('t3api')->getBackend();
self::assertInstanceOf(ReadCountingCacheBackend::class, $backend);

return $backend;
}
}
25 changes: 25 additions & 0 deletions Tests/Functional/Fixtures/ReadCountingCacheBackend.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace SourceBroker\T3api\Tests\Functional\Fixtures;

use TYPO3\CMS\Core\Cache\Backend\TransientMemoryBackend;

/**
* Counts reads of cache entries, e.g. to check how often one request reads the API resources.
*/
final class ReadCountingCacheBackend extends TransientMemoryBackend
{
public int $readCount = 0;

/**
* @param string $entryIdentifier
*/
public function get($entryIdentifier): mixed
{
$this->readCount++;

return parent::get($entryIdentifier);
}
}
105 changes: 105 additions & 0 deletions Tests/Unit/Domain/Repository/ApiResourceRepositoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

declare(strict_types=1);

namespace SourceBroker\T3api\Tests\Unit\Domain\Repository;

use PHPUnit\Framework\Attributes\Test;
use SourceBroker\T3api\Domain\Repository\ApiResourceRepository;
use SourceBroker\T3api\Factory\ApiResourceFactory;
use SourceBroker\T3api\Routing\Enhancer\ResourceEnhancer;
use SourceBroker\T3api\Service\ReflectionService;
use SourceBroker\T3api\Service\SiteService;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Http\ServerRequest;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\TestingFramework\Core\Unit\UnitTestCase;

class ApiResourceRepositoryTest extends UnitTestCase
{
/**
* @var string[]
*/
private array $readCacheIdentifiers = [];

private Site $site;

protected function setUp(): void
{
parent::setUp();
SiteService::reset();
$this->site = new Site('test', 1, [
'base' => 'https://example.com/',
'languages' => [
['languageId' => 0, 'title' => 'English', 'base' => '/', 'locale' => 'en_US.UTF-8'],
['languageId' => 1, 'title' => 'German', 'base' => '/de/', 'locale' => 'de_DE.UTF-8'],
],
'routeEnhancers' => [
'T3api' => ['type' => ResourceEnhancer::ENHANCER_NAME, 'basePath' => '_api'],
],
]);
}

protected function tearDown(): void
{
unset($GLOBALS['TYPO3_REQUEST']);
SiteService::reset();
parent::tearDown();
}

#[Test]
public function getByEntityReadsCacheOnlyOnceForManyEntities(): void
{
$this->setCurrentRequestLanguage(0);
$apiResourceRepository = $this->createApiResourceRepository();

$apiResourceRepository->getByEntity(\stdClass::class);
$apiResourceRepository->getByEntity(\stdClass::class);
$apiResourceRepository->getByEntity(\stdClass::class);

self::assertSame(['ApiResourceRepository_getAll_api'], $this->readCacheIdentifiers);
}

#[Test]
public function getAllReadsCacheOncePerApiBasePath(): void
{
$apiResourceRepository = $this->createApiResourceRepository();

foreach ([0, 1, 0, 1] as $languageId) {
$this->setCurrentRequestLanguage($languageId);
$apiResourceRepository->getAll();
}

self::assertSame(
['ApiResourceRepository_getAll_api', 'ApiResourceRepository_getAllde_api'],
$this->readCacheIdentifiers
);
}

private function createApiResourceRepository(): ApiResourceRepository
{
$cache = self::createStub(FrontendInterface::class);
$cache->method('get')->willReturnCallback(function (string $cacheIdentifier): array {
$this->readCacheIdentifiers[] = $cacheIdentifier;

return [];
});
$cacheManager = self::createStub(CacheManager::class);
$cacheManager->method('getCache')->willReturnMap([['t3api', $cache]]);

return new ApiResourceRepository(
$cacheManager,
self::createStub(ReflectionService::class),
self::createStub(ApiResourceFactory::class)
);
}

private function setCurrentRequestLanguage(int $languageId): void
{
$language = $this->site->getLanguageById($languageId);
$GLOBALS['TYPO3_REQUEST'] = (new ServerRequest($language->getBase() . '_api/news/news', 'GET'))
->withAttribute('site', $this->site)
->withAttribute('language', $language);
}
}
Loading