Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use typo3 core YamlFileLoader #54

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
47 changes: 15 additions & 32 deletions Classes/Configuration/ConfigurationFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,15 @@
use Brotkrueml\MatomoWidgets\Extension;
use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Yaml;
use TYPO3\CMS\Core\Configuration\Loader\YamlFileLoader;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
* @internal
*/
final class ConfigurationFinder
{
/**
* Regex pattern for allowed characters in environment variables
* @see https://regex101.com/r/hIXvef/1
* @see https://stackoverflow.com/questions/2821043/allowed-characters-in-linux-environment-variable-names
*/
private const ENV_VAR_REGEX = '/^%env\(([a-zA-Z_]\w*)\)%$/';
private static YamlFileLoader $yamlFileLoader;

public static function buildConfigurations(string $configPath, bool $isMatomoIntegrationAvailable): Configurations
{
Expand All @@ -39,7 +34,7 @@ public static function buildConfigurations(string $configPath, bool $isMatomoInt
if ($realFile === false) {
continue;
}
$siteConfiguration = Yaml::parseFile($realFile);
$siteConfiguration = self::getYamlFileLoader()->load(GeneralUtility::fixWindowsFilePath($realFile));

$considerMatomoIntegration = $isMatomoIntegrationAvailable
&& ($siteConfiguration['matomoWidgetsConsiderMatomoIntegration'] ?? false);
Expand All @@ -51,8 +46,7 @@ public static function buildConfigurations(string $configPath, bool $isMatomoInt
$url = $siteConfiguration['matomoWidgetsUrl'] ?? '';
$idSite = (string) ($siteConfiguration['matomoWidgetsIdSite'] ?? 0);
}
$url = self::resolveEnvironmentVariable($url);
$idSite = (int) self::resolveEnvironmentVariable($idSite);
$idSite = (int) $idSite;
if ($url === '') {
continue;
}
Expand All @@ -65,10 +59,9 @@ public static function buildConfigurations(string $configPath, bool $isMatomoInt
} else {
$pagesNotFoundTemplate = $siteConfiguration['matomoWidgetsPagesNotFoundTemplate'] ?? '';
}
$pagesNotFoundTemplate = self::resolveEnvironmentVariable($pagesNotFoundTemplate);

$siteTitle = self::resolveEnvironmentVariable($siteConfiguration['matomoWidgetsTitle'] ?? '');
$tokenAuth = self::resolveEnvironmentVariable($siteConfiguration['matomoWidgetsTokenAuth'] ?? '');
$siteTitle = $siteConfiguration['matomoWidgetsTitle'] ?? '';
$tokenAuth = $siteConfiguration['matomoWidgetsTokenAuth'] ?? '';

$pathSegments = \explode('/', $file->getPath());
$identifier = \end($pathSegments);
Expand All @@ -80,7 +73,7 @@ public static function buildConfigurations(string $configPath, bool $isMatomoInt

$activeWidgets = GeneralUtility::trimExplode(
',',
self::resolveEnvironmentVariable($siteConfiguration['matomoWidgetsActiveWidgets'] ?? ''),
$siteConfiguration['matomoWidgetsActiveWidgets'] ?? '',
true,
);
$customDimensions = self::buildCustomDimensions($siteConfiguration['matomoWidgetsCustomDimensions'] ?? []);
Expand Down Expand Up @@ -109,6 +102,7 @@ private static function getConfigurationFiles(string $configPath): array
$siteFiles = \iterator_to_array(
Finder::create()
->in($configPath . '/sites/*')
->depth(0)
->name('config.yaml'),
);
} catch (DirectoryNotFoundException) {
Expand All @@ -128,24 +122,6 @@ private static function getConfigurationFiles(string $configPath): array
return [...$siteFiles, ...$additionalFiles];
}

/**
* This method is necessary as environment variables are not resolved when configuration
* is available in controllers.
*/
private static function resolveEnvironmentVariable(string $value): string
{
if (\preg_match(self::ENV_VAR_REGEX, $value, $matches) !== 1) {
return $value;
}

$resolvedValue = \getenv($matches[1]);
if ($resolvedValue === false) {
return '';
}

return $resolvedValue;
}

/**
* @param list<array{scope: string, idDimension: int|string, title?: string, description?: string}> $configurations
* @return CustomDimension[]
Expand All @@ -166,4 +142,11 @@ private static function buildCustomDimensions(array $configurations): array

return $customDimensions;
}

private static function getYamlFileLoader(): YamlFileLoader
{
self::$yamlFileLoader ??= GeneralUtility::makeInstance(YamlFileLoader::class);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I shy away from using GeneralUtility::makeInstance() at this point: when the ConfigurationFinder is utilized, there is no dependency injection container available. This might work now (haven't tested it), but won't bet on it for future TYPO3 versions. Better would be to instantiate manually:

new YamlFileLoader(new NullLogger());

But: as TYPO3 uses here dependency injection already for the logger, this might cause problems in future versions, when other dependencies might be injected. Then this may result in removing this feature and using the plain Symfony YamlFileLoader again.

Another possibility will be to copy the import functionality over to this extension (or the whole class without the logging).

What do you think? @tbal


return self::$yamlFileLoader;
}
}
20 changes: 20 additions & 0 deletions Tests/Unit/Configuration/ConfigurationFinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,35 @@
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use TYPO3\CMS\Core\Configuration\ConfigurationManager;
use TYPO3\CMS\Core\Configuration\Loader\YamlFileLoader;
use TYPO3\CMS\Core\Core\ApplicationContext;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Log\Logger;
use TYPO3\CMS\Core\Utility\GeneralUtility;

#[CoversClass(ConfigurationFinder::class)]
#[RunTestsInSeparateProcesses]
final class ConfigurationFinderTest extends TestCase
{
private static string $configPath;

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

$configurationManager = new ConfigurationManager();
$GLOBALS['TYPO3_CONF_VARS'] = $configurationManager->getDefaultConfiguration();

GeneralUtility::addInstance(
YamlFileLoader::class,
GeneralUtility::makeInstance(
YamlFileLoader::class,
$this->createMock(Logger::class),
),
);
Comment on lines +40 to +46
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@brotkrueml This may could be done more elegant..
I got errors when running the phpunit test because of missing argument (Logger) for YamlFileLoader class (is instantiated in ConfigurationFinder.php L148. I was struggeling with the dependency injection of the LoggerAwareInterface for the YamlFileLoader class here and that was the solution i found which satisfied the test cases :)

}

public static function setUpBeforeClass(): void
{
Environment::initialize(
Expand Down