Skip to content

Commit

Permalink
NTR: add monolog channel
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitalij Mik committed Jan 14, 2025
1 parent de914c0 commit 4be9003
Show file tree
Hide file tree
Showing 52 changed files with 849 additions and 430 deletions.
7 changes: 7 additions & 0 deletions .github/actions/run-e2e/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ runs:
docker exec shop bash -c 'php bin/console dal:validate'
# --------------------------------------------------------------------------------------------------------------------------------------
- name: Integration Tests
shell: bash
run: |
docker exec shop bash -c 'cd /var/www/html/custom/plugins/MolliPayments && make phpintegration'
# --------------------------------------------------------------------------------------------------------------------------------------



- name: Install Cypress
if: ${{ inputs.RUN_CYPRESS == 'true' }}
Expand Down
1 change: 1 addition & 0 deletions .php_cs.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

$finder = \PhpCsFixer\Finder::create()->in([
__DIR__ . '/src',
__DIR__ . '/shopware',
__DIR__.'/tests/PHPUnit',
]);

Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Features
- Return over Shopware Commercial plugins is now transfered to Mollie when the Return status is set to "Done" and can be cancelled with the "Cancelled" status. Please note that the refund cannot be cancelled after two hours.
### Changes
- Minimum Supported Shopware version is now 6.4.5.0
- Minimum Supported Shopware version is now 6.4.5.0
- Add new monolog channel "mollie". You can now add custom handler and assign them to the mollie channel
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,15 @@
},
"autoload": {
"psr-4": {
"Mollie\\Shopware\\": "shopware/",
"Kiener\\MolliePayments\\": "src/",
"Mollie\\Api\\": "vendor_manual/mollie/mollie-api-php/src/"
}
},
"autoload-dev": {
"psr-4": {
"Mollie\\Unit\\": "tests/Unit/",
"Mollie\\Integration\\": "tests/Integration/",
"MolliePayments\\Tests\\": "tests/PHPUnit/",
"MolliePayments\\PHPStan\\": "tests/PHPStan/",
"MolliePayments\\Fixtures\\": "tests/Fixtures/"
Expand All @@ -70,7 +73,7 @@
"shopware/elasticsearch": "*"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"phpunit/phpunit": "^9",
"phpstan/phpstan": "1.10.0",
"friendsofphp/php-cs-fixer": "^2.18",
"phpcompatibility/php-compatibility": "^9.3",
Expand Down
8 changes: 6 additions & 2 deletions makefile
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,13 @@ stan: ##2 Starts the PHPStan Analyser
@php vendor/bin/phpstan analyse -c ./.phpstan.neon

phpunit: ##2 Starts all PHPUnit Tests
@XDEBUG_MODE=coverage php vendor/bin/phpunit --configuration=phpunit.xml --coverage-html ./.reports/phpunit/coverage
@XDEBUG_MODE=coverage php vendor/bin/phpunit --testsuite unit --configuration=phpunit.xml

phpintergration: ##2 Starts all PHPUnit Tests
@XDEBUG_MODE=coverage cd ../../.. && php vendor/bin/phpunit --testsuite integration --configuration=custom/plugins/MolliePayments/phpunit.xml

infection: ##2 Starts all Infection/Mutation tests
@XDEBUG_MODE=coverage php vendor/bin/infection --configuration=./.infection.json --log-verbosity=all --debug
@XDEBUG_MODE=coverage php vendor/bin/infection --configuration=./.infection.json --log-verbosity=all --debug --test-framework-options="--testsuite=unit --no-coverage"

insights: ##2 Starts the PHPInsights Analyser
@php vendor/bin/phpinsights analyse --no-interaction
Expand Down Expand Up @@ -151,6 +154,7 @@ pr: ##2 Prepares everything for a Pull Request
@make phpmin -B
@make stan -B
@make phpunit -B
@make phpintergration -B
@make jest -B
@make eslint mode=no-dry-run -B
@make stylelint -B
Expand Down
24 changes: 18 additions & 6 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,23 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
bootstrap="./vendor/autoload.php"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.6/phpunit.xsd"
bootstrap="./tests/bootstrap/index.php"
cacheResult="false"
colors="true"
executionOrder="random"
resolveDependencies="true"
>
<php>
<ini name="error_reporting" value="-1"/>
<server name="KERNEL_CLASS" value="Shopware\Core\Kernel"/>
<env name="APP_ENV" value="test"/>
<env name="APP_DEBUG" value="1"/>
<env name="SYMFONY_DEPRECATIONS_HELPER" value="weak"/>
</php>

<testsuites>
<testsuite name="MolliePayments Tests">
<testsuite name="unit">
<directory>./tests/PHPUnit</directory>
<directory>./tests/Unit</directory>
</testsuite>
<testsuite name="integration">
<directory>./tests/Integration</directory>
</testsuite>
</testsuites>

<coverage>
<coverage processUncoveredFiles="true">
<include>
<directory>./src</directory>
<directory suffix=".php">./src</directory>
<directory suffix=".php">./shopware</directory>
</include>
</coverage>


</phpunit>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare(strict_types=1);

namespace Shopware\Core\Content\Flow\Dispatching\Aware;

use Shopware\Core\Framework\Event\IsFlowEventAware;
use Shopware\Core\Framework\Log\Package;

#[Package('services-settings')]
#[IsFlowEventAware]
interface ScalarValuesAware
{
public const STORE_VALUES = 'store_values';

/**
* @return array<string, scalar|array<mixed>|null>
*/
public function getValues(): array;
}
83 changes: 83 additions & 0 deletions shopware/Component/Logger/PluginSettingsHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);

namespace Mollie\Shopware\Component\Logger;

use Doctrine\DBAL\Connection;
use Mollie\Shopware\Component\Settings\AbstractSettingsService;
use Monolog\Handler\AbstractHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Level;
use Monolog\LogRecord;
use Psr\Log\LogLevel;

final class PluginSettingsHandler extends AbstractHandler
{
private const LOG_CHANNEL = 'mollie';
private ?AbstractHandler $fileHandler = null;
private Connection $connection;
private string $filePath;
private ?bool $connectedCache = null;

private AbstractSettingsService $settingsService;

/**
* @param AbstractSettingsService $settingsService
* @param Connection $connection
* @param string $filePath
* @param int|Level|string $level
* @param bool $bubble
*/
public function __construct(AbstractSettingsService $settingsService, Connection $connection, string $filePath, bool $bubble = true)
{
parent::__construct(LogLevel::DEBUG, $bubble);
$this->connection = $connection;
$this->filePath = $filePath;
$this->settingsService = $settingsService;
}

/**
* We need to define types here because shopware 6.4 uses old monologger where LogRecord does not exists.
* @param array|LogRecord $record
* @return bool
*/
public function handle($record): bool
{
if ($this->isConnected() === false) {
return false;
}

$channel = $record['channel'] ?? null;
if ($channel !== self::LOG_CHANNEL) {
return false;
}


if ($this->fileHandler === null) {
$this->fileHandler = $this->initializeHandler();
}

$this->fileHandler->handle($record);

return $this->bubble === false;
}

private function isConnected(): bool
{
if ($this->connectedCache !== null) {
return $this->connectedCache;
}

$this->connectedCache = $this->connection->isConnected();
return $this->connectedCache;
}

private function initializeHandler(): AbstractHandler
{
$loggerSettings = $this->settingsService->getLoggerSettings();

$logLevel = $loggerSettings->isDebugMode() ? LogLevel::DEBUG : LogLevel::INFO;
$maxFiles = $loggerSettings->getLogFileDays();
return new RotatingFileHandler($this->filePath, $maxFiles, $logLevel);
}
}
49 changes: 49 additions & 0 deletions shopware/Component/Logger/RecordAnonymizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);

namespace Mollie\Shopware\Component\Logger;

use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
use Symfony\Component\HttpFoundation\IpUtils;

final class RecordAnonymizer implements ProcessorInterface
{
private const URL_SLUG = '/payment/finalize-transaction';
/**
* @param string $url
* @return string
*/
private function anonymize(string $url): string
{
# we do not want to save the used tokens in our log file
# also, those one time tokens are soooooo long. it's just annoying and fills disk space ;)
if (strpos($url, self::URL_SLUG) !== false) {
$parts = explode(self::URL_SLUG, $url);

$url = str_replace($parts[1], '', $url);
}

return (string)$url;
}
/**
* We need to define types here because shopware 6.4 uses old monologger where LogRecord does not exists.
* @param array|LogRecord $record
* @return array|LogRecord
*/
public function __invoke($record)
{
/** @phpstan-ignore-next-line */
if (isset($record['extra'])) {
if (array_key_exists('ip', $record['extra'])) {
# replace it with our anonymous IP
$record['extra']['ip'] = IpUtils::anonymize(trim($record['extra']['ip']));
}

if (array_key_exists('url', $record['extra'])) {
$record['extra']['url'] = $this->anonymize($record['extra']['url']);
}
}
return $record;
}
}
27 changes: 27 additions & 0 deletions shopware/Component/Logger/Resources/config/services.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
https://symfony.com/schema/dic/services/services-1.0.xsd">

<services>

<service id="Mollie\Shopware\Component\Logger\RecordAnonymizer">
<tag name="monolog.processor"/>
</service>

<service id="Monolog\Processor\WebProcessor">
<tag name="monolog.processor" channel="mollie"/>
</service>

<service id="Monolog\Processor\IntrospectionProcessor">
<tag name="monolog.processor" channel="mollie"/>
</service>

<service id="Mollie\Shopware\Component\Logger\PluginSettingsHandler">
<argument type="service" id="Mollie\Shopware\Component\Settings\SettingsService"/>
<argument type="service" id="Doctrine\DBAL\Connection"/>
<argument>%kernel.logs_dir%/mollie_%kernel.environment%.log</argument>
</service>
</services>
</container>
12 changes: 12 additions & 0 deletions shopware/Component/Settings/AbstractSettingsService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);

namespace Mollie\Shopware\Component\Settings;

use Mollie\Shopware\Component\Settings\Struct\LoggerSettings;

abstract class AbstractSettingsService
{
abstract public function getDecorated(): AbstractSettingsService;
abstract public function getLoggerSettings(?string $salesChannelId = null): LoggerSettings;
}
15 changes: 15 additions & 0 deletions shopware/Component/Settings/Resources/config/services.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
https://symfony.com/schema/dic/services/services-1.0.xsd">

<services>

<service id="Mollie\Shopware\Component\Settings\SettingsService">
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
</service>


</services>
</container>
60 changes: 60 additions & 0 deletions shopware/Component/Settings/SettingsService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);

namespace Mollie\Shopware\Component\Settings;

use Mollie\Shopware\Component\Settings\Struct\LoggerSettings;
use Shopware\Core\Framework\Plugin\Exception\DecorationPatternException;
use Shopware\Core\System\SystemConfig\SystemConfigService;

final class SettingsService extends AbstractSettingsService
{
public const SYSTEM_CONFIG_DOMAIN = 'MolliePayments.config';
private const CACHE_KEY_LOGGER = 'logger';
private const CACHE_KEY_SHOPWARE = 'shopware';

private SystemConfigService $systemConfigService;

private array $settingsCache = [];



public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}

public function getDecorated(): AbstractSettingsService
{
throw new DecorationPatternException(self::class);
}

public function getLoggerSettings(?string $salesChannelId = null): LoggerSettings
{
$cacheKey = self::CACHE_KEY_LOGGER . '_' . ($salesChannelId ?? 'all');

if (isset($this->settingsCache[$cacheKey])) {
return $this->settingsCache[$cacheKey];
}


$shopwareSettings = $this->getShopwareSettings($salesChannelId);
$loggerSettings = LoggerSettings::createFromShopwareArray($shopwareSettings);
$this->settingsCache[$cacheKey] = $loggerSettings;

return $loggerSettings;
}

private function getShopwareSettings(?string $salesChannelId = null): array
{
$cacheKey = self::CACHE_KEY_SHOPWARE . '_' . ($salesChannelId ?? 'all');

if (isset($this->settingsCache[$cacheKey])) {
return $this->settingsCache[$cacheKey];
}

$shopwareSettingsArray = $this->systemConfigService->get(self::SYSTEM_CONFIG_DOMAIN, $salesChannelId);
$this->settingsCache[$cacheKey] = $shopwareSettingsArray;
return $shopwareSettingsArray;
}
}
Loading

0 comments on commit 4be9003

Please sign in to comment.