From afd683bc8489a226e4192e562a27b6e9b7784932 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurynas=20Grici=C5=ABnas?= Date: Fri, 31 Mar 2023 09:12:01 +0300 Subject: [PATCH 1/2] Full update. --- .phpunit.cache/test-results | 1 + CHANGELOG.md | 7 ++ composer.json | 32 ++++----- phpunit.xml.dist | 32 ++++----- src/DependencyInjection/Configuration.php | 11 +-- src/Listener/CorrelationIdListener.php | 13 ++-- src/Listener/IterationEndListener.php | 12 ++-- src/Resources/config/services/processors.xml | 6 -- src/Service/CorrelationIdProvider.php | 6 +- src/Service/Formatter/FormatterTrait.php | 20 +++--- .../Handler/SentryExtraInformationHandler.php | 14 ++-- .../Processor/CorrelationIdProcessor.php | 9 ++- .../Processor/GroupExceptionsProcessor.php | 9 +-- .../Processor/RemoveRootPrefixProcessor.php | 28 -------- .../Processor/SentryContextProcessor.php | 4 +- .../Fixtures/Controller/TestController.php | 4 +- .../Fixtures/Entity/PersistedEntity.php | 19 ++--- .../Fixtures/Handler/TestGraylogHandler.php | 11 ++- .../Fixtures/Handler/TestSentryTransport.php | 9 ++- .../Fixtures/Logger/TestDbalLogger.php | 9 +-- .../Fixtures/Service/TestTransportFactory.php | 8 +-- tests/Functional/Fixtures/TestKernel.php | 11 +-- tests/Functional/Fixtures/config/common.yml | 17 ++--- tests/Functional/Fixtures/config/routes.yml | 3 + tests/Functional/Fixtures/config/routing.yml | 3 - .../FunctionalCorrelationIdListenerTest.php | 11 ++- tests/Functional/FunctionalFormattersTest.php | 47 +++++------- tests/Functional/FunctionalHandlersTest.php | 72 ++++++------------- .../FunctionalMonologConfigurationTest.php | 34 +++------ tests/Functional/FunctionalTestCase.php | 20 ++---- 30 files changed, 172 insertions(+), 310 deletions(-) create mode 100644 .phpunit.cache/test-results delete mode 100644 src/Service/Processor/RemoveRootPrefixProcessor.php create mode 100644 tests/Functional/Fixtures/config/routes.yml delete mode 100644 tests/Functional/Fixtures/config/routing.yml diff --git a/.phpunit.cache/test-results b/.phpunit.cache/test-results new file mode 100644 index 0000000..f4be5b0 --- /dev/null +++ b/.phpunit.cache/test-results @@ -0,0 +1 @@ +{"version":1,"defects":{"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalCorrelationIdListenerTest::testResponseHeaders":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalFormattersTest::testWithDoctrineEntity":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testSentryGetsContextValues":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testCorrelationId":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testRootPrefix":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testIntrospection":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testExceptionGrouping":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylog":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithError":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfInfoMessages":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfDebugMessages":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testSentry":8},"times":{"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalCorrelationIdListenerTest::testResponseHeaders":0.014,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalFormattersTest::testWithDoctrineEntity":0.023,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testSentryGetsContextValues":0.01,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testCorrelationId":0.004,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testRootPrefix":0.009,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testIntrospection":0.005,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testExceptionGrouping":0.007,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylog":0.004,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithError":0.005,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfInfoMessages":0.023,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfDebugMessages":0.012,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testSentry":0.004}} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 5741245..c267493 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.0.0] - 2023-03-31 +### Removed +- Dropped support for versions below PHP 8.1 and Symfony 5. +- Root prefix processor as messages can no longer be altered as the record is now an entity instead of array, and the `message` field is read-only. +### Changed +- Changed some logic to fit the new versions of the used libraries. + ## [2.1.0] - 2023-03-29 ### Added - Added Symfony ^5 support. diff --git a/composer.json b/composer.json index d3e1da9..6b76194 100755 --- a/composer.json +++ b/composer.json @@ -15,25 +15,25 @@ } }, "require": { - "php": "^7.2 || ^8.0", + "php": ">=8.0", "ext-json": "*", - "graylog2/gelf-php": "^1.4.2", - "monolog/monolog": "^1.24 || ^2.0", - "sentry/sdk": "^3.1", - "sentry/sentry": "^3.1", - "sentry/sentry-symfony": "^4.0", - "symfony/config": "^3.4|^4.0|^5.0", - "symfony/dependency-injection": "^3.4|^4.0|^5.0", - "symfony/framework-bundle": "^3.4.26|^4.2.7|^5.0", - "symfony/http-kernel": "^3.4|^4.0|^5.0", - "symfony/monolog-bundle": "^3.4|^5.0" + "graylog2/gelf-php": "^2.0", + "monolog/monolog": "^3.3", + "sentry/sdk": "^3.3", + "sentry/sentry": "^3.17", + "sentry/sentry-symfony": "^4.7", + "symfony/config": "^5.0", + "symfony/dependency-injection": "^5.0", + "symfony/framework-bundle": "^5.0", + "symfony/http-kernel": "^5.0", + "symfony/monolog-bundle": "^3.4" }, "require-dev": { - "doctrine/annotations": "^1.14", - "doctrine/doctrine-bundle": "~2.6.0", - "doctrine/orm": "^2.10", - "phpunit/phpunit": "^8.5", - "symfony/yaml": "^4.3" + "doctrine/annotations": "^2.0", + "doctrine/doctrine-bundle": "^2.9", + "doctrine/orm": "^2.14", + "phpunit/phpunit": "^10.0", + "symfony/yaml": "^5.0" }, "config": { "bin-dir": "bin", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 0b108bc..e17721e 100755 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,26 +1,22 @@ - - - + + + + ./src + + tests - - - - ./src - - diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index d679554..eff9609 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -9,15 +9,10 @@ class Configuration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { - if (method_exists(TreeBuilder::class, 'getRootNode')) { - $treeBuilder = new TreeBuilder('paysera_logging_extra'); - $rootNode = $treeBuilder->getRootNode(); - } else { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('paysera_logging_extra'); - } + $treeBuilder = new TreeBuilder('paysera_logging_extra'); + $rootNode = $treeBuilder->getRootNode(); $children = $rootNode->children(); $children->scalarNode('application_name')->isRequired(); diff --git a/src/Listener/CorrelationIdListener.php b/src/Listener/CorrelationIdListener.php index 70418a2..7fd6f00 100644 --- a/src/Listener/CorrelationIdListener.php +++ b/src/Listener/CorrelationIdListener.php @@ -5,23 +5,20 @@ namespace Paysera\LoggingExtraBundle\Listener; use Paysera\LoggingExtraBundle\Service\CorrelationIdProvider; -use Symfony\Component\HttpKernel\Event\FilterResponseEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; class CorrelationIdListener { - const HEADER_NAME = 'Paysera-Correlation-Id'; + public const HEADER_NAME = 'Paysera-Correlation-Id'; - private $correlationIdProvider; - - public function __construct(CorrelationIdProvider $correlationIdProvider) + public function __construct(private CorrelationIdProvider $correlationIdProvider) { - $this->correlationIdProvider = $correlationIdProvider; } - public function onKernelResponse(FilterResponseEvent $event) + public function onKernelResponse(ResponseEvent $event): void { - if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { + if (HttpKernelInterface::MAIN_REQUEST !== $event->getRequestType()) { return; } diff --git a/src/Listener/IterationEndListener.php b/src/Listener/IterationEndListener.php index dc55473..4240b68 100644 --- a/src/Listener/IterationEndListener.php +++ b/src/Listener/IterationEndListener.php @@ -15,22 +15,18 @@ */ class IterationEndListener { - private $correlationIdProvider; - private $sentryClient; + private ?ClientInterface $sentryClient; public function __construct( - CorrelationIdProvider $correlationIdProvider, + private CorrelationIdProvider $correlationIdProvider, ClientInterface $sentryClient = null ) { - $this->correlationIdProvider = $correlationIdProvider; $this->sentryClient = $sentryClient instanceof ClientInterface ? $sentryClient : null; } - public function afterIteration() + public function afterIteration(): void { $this->correlationIdProvider->incrementIdentifier(); - if ($this->sentryClient !== null) { - $this->sentryClient->flush(); - } + $this->sentryClient?->flush(); } } diff --git a/src/Resources/config/services/processors.xml b/src/Resources/config/services/processors.xml index 07ed16c..63ec16a 100644 --- a/src/Resources/config/services/processors.xml +++ b/src/Resources/config/services/processors.xml @@ -19,12 +19,6 @@ ERROR - - - %kernel.root_dir%/.. - - diff --git a/src/Service/CorrelationIdProvider.php b/src/Service/CorrelationIdProvider.php index e538d2c..012a323 100644 --- a/src/Service/CorrelationIdProvider.php +++ b/src/Service/CorrelationIdProvider.php @@ -6,8 +6,8 @@ class CorrelationIdProvider { - private $correlationId; - private $increment; + private string $correlationId; + private int $increment; public function __construct(string $systemName) { @@ -24,7 +24,7 @@ public function getCorrelationId(): string return sprintf('%s_%s', $this->correlationId, $this->increment); } - public function incrementIdentifier() + public function incrementIdentifier(): void { $this->increment++; } diff --git a/src/Service/Formatter/FormatterTrait.php b/src/Service/Formatter/FormatterTrait.php index f820bba..e53a238 100644 --- a/src/Service/Formatter/FormatterTrait.php +++ b/src/Service/Formatter/FormatterTrait.php @@ -5,25 +5,21 @@ namespace Paysera\LoggingExtraBundle\Service\Formatter; use DateTimeInterface; -use Doctrine\Common\Persistence\Proxy as LegacyProxy; use Doctrine\Persistence\Proxy; use Doctrine\ORM\PersistentCollection; use Monolog\Utils; use Throwable; -/** - * To be used on classes extending NormalizerFormatter - */ trait FormatterTrait { - protected function normalize($data, $depth = 0) + protected function normalize(mixed $data, $depth = 0): mixed { - $prenormalizedData = $this->prenormalizeData($data, $depth); + $prenormalizedData = $this->preNormalizeData($data, $depth); return parent::normalize($prenormalizedData, $depth); } - private function prenormalizeData($data, $depth) + private function preNormalizeData($data, $depth) { if ($depth > 2) { return $this->getScalarRepresentation($data); @@ -33,7 +29,7 @@ private function prenormalizeData($data, $depth) return $data->isInitialized() ? iterator_to_array($data) : get_class($data); } - if ($data instanceof Proxy || $data instanceof LegacyProxy) { + if ($data instanceof Proxy) { return $this->normalizeProxy($data); } @@ -48,7 +44,7 @@ private function prenormalizeData($data, $depth) return $data; } - private function getScalarRepresentation($data) + private function getScalarRepresentation(mixed $data): mixed { if (is_scalar($data) || $data === null) { return $data; @@ -61,13 +57,13 @@ private function getScalarRepresentation($data) return gettype($data); } - private function normalizeObject($data) + private function normalizeObject(mixed $data): array { $result = []; foreach ((array)$data as $key => $value) { $parts = explode("\0", $key); $fixedKey = end($parts); - if (substr($fixedKey, 0, 2) === '__') { + if (str_starts_with($fixedKey, '__')) { continue; } @@ -77,7 +73,7 @@ private function normalizeObject($data) return $result; } - private function normalizeProxy(Proxy $data) + private function normalizeProxy(Proxy $data): array|string { if ($data->__isInitialized()) { return $this->normalizeObject($data); diff --git a/src/Service/Handler/SentryExtraInformationHandler.php b/src/Service/Handler/SentryExtraInformationHandler.php index d2e6398..0381ca7 100644 --- a/src/Service/Handler/SentryExtraInformationHandler.php +++ b/src/Service/Handler/SentryExtraInformationHandler.php @@ -6,14 +6,16 @@ use Monolog\Handler\HandlerWrapper; use Monolog\Handler\ProcessableHandlerTrait; +use Monolog\LogRecord; use Sentry\State\Scope; + use function Sentry\withScope; final class SentryExtraInformationHandler extends HandlerWrapper { use ProcessableHandlerTrait; - public function handle(array $record): bool + public function handle(LogRecord $record): bool { if (!$this->isHandling($record)) { return false; @@ -25,15 +27,15 @@ public function handle(array $record): bool $record['formatted'] = $this->getFormatter()->format($record); withScope(function (Scope $scope) use ($record, &$result): void { - if (isset($record['context']['extra']) && \is_array($record['context']['extra'])) { - foreach ($record['context']['extra'] as $key => $value) { + if (isset($record['context']) && \is_array($record['context'])) { + foreach ($record['context'] as $key => $value) { $scope->setExtra((string) $key, $value); } } - if (isset($record['context']['tags']) && \is_array($record['context']['tags'])) { - foreach ($record['context']['tags'] as $key => $value) { - $scope->setTag($key, $value); + if (isset($record['extra']) && \is_array($record['extra'])) { + foreach ($record['extra'] as $key => $value) { + $scope->setTag($key, (string)$value); } } diff --git a/src/Service/Processor/CorrelationIdProcessor.php b/src/Service/Processor/CorrelationIdProcessor.php index 5541a63..5b09df5 100644 --- a/src/Service/Processor/CorrelationIdProcessor.php +++ b/src/Service/Processor/CorrelationIdProcessor.php @@ -4,21 +4,20 @@ namespace Paysera\LoggingExtraBundle\Service\Processor; +use Monolog\LogRecord; use Monolog\Processor\ProcessorInterface; use Paysera\LoggingExtraBundle\Service\CorrelationIdProvider; class CorrelationIdProcessor implements ProcessorInterface { - private $correlationIdProvider; - - public function __construct(CorrelationIdProvider $correlationIdProvider) + public function __construct(private CorrelationIdProvider $correlationIdProvider) { - $this->correlationIdProvider = $correlationIdProvider; } - public function __invoke(array $record) + public function __invoke(LogRecord $record): LogRecord { $record['extra']['correlation_id'] = $this->correlationIdProvider->getCorrelationId(); + return $record; } } diff --git a/src/Service/Processor/GroupExceptionsProcessor.php b/src/Service/Processor/GroupExceptionsProcessor.php index 8d3a5ef..fd07d10 100644 --- a/src/Service/Processor/GroupExceptionsProcessor.php +++ b/src/Service/Processor/GroupExceptionsProcessor.php @@ -4,24 +4,21 @@ namespace Paysera\LoggingExtraBundle\Service\Processor; +use Monolog\LogRecord; use Monolog\Processor\ProcessorInterface; -use Sentry\SentryBundle\SentryBundle; use Sentry\SentrySdk; use Sentry\State\Scope; -/** - * @php-cs-fixer-ignore Paysera/php_basic_code_style_chained_method_calls - */ class GroupExceptionsProcessor implements ProcessorInterface { - private $exceptionsClassesToGroup; + private array $exceptionsClassesToGroup; public function __construct(array $exceptionsClassesToGroup) { $this->exceptionsClassesToGroup = array_flip($exceptionsClassesToGroup); } - public function __invoke(array $record) + public function __invoke(LogRecord $record): LogRecord { if (!isset($record['context']['exception'])) { return $record; diff --git a/src/Service/Processor/RemoveRootPrefixProcessor.php b/src/Service/Processor/RemoveRootPrefixProcessor.php deleted file mode 100644 index d990f79..0000000 --- a/src/Service/Processor/RemoveRootPrefixProcessor.php +++ /dev/null @@ -1,28 +0,0 @@ -rootPrefix = realpath($rootPrefix); - if ($this->rootPrefix === false) { - throw new InvalidArgumentException('Invalid root prefix specified'); - } - } - - public function __invoke(array $record) - { - $record['message'] = str_replace($this->rootPrefix, '', $record['message']); - - return $record; - } -} diff --git a/src/Service/Processor/SentryContextProcessor.php b/src/Service/Processor/SentryContextProcessor.php index 83f3730..008b260 100644 --- a/src/Service/Processor/SentryContextProcessor.php +++ b/src/Service/Processor/SentryContextProcessor.php @@ -4,11 +4,12 @@ namespace Paysera\LoggingExtraBundle\Service\Processor; +use Monolog\LogRecord; use Monolog\Processor\ProcessorInterface; class SentryContextProcessor implements ProcessorInterface { - public function __invoke(array $record) + public function __invoke(LogRecord $record): LogRecord { $record['context']['extra'] = ($record['context']['extra'] ?? []) + $record['extra'] + $record['context']; if (isset($record['extra']['correlation_id'])) { @@ -16,6 +17,7 @@ public function __invoke(array $record) } unset($record['context']['extra']['tags']); unset($record['context']['extra']['exception']); + return $record; } } diff --git a/tests/Functional/Fixtures/Controller/TestController.php b/tests/Functional/Fixtures/Controller/TestController.php index d385634..a95ac90 100644 --- a/tests/Functional/Fixtures/Controller/TestController.php +++ b/tests/Functional/Fixtures/Controller/TestController.php @@ -1,12 +1,14 @@ children = new ArrayCollection(); } - public function getField(): string - { - return $this->field; - } - public function setField(string $field): self { $this->field = $field; + return $this; } @@ -68,6 +61,7 @@ public function getParent(): ?self public function setParent(?self $parent): self { $this->parent = $parent; + return $this; } @@ -80,6 +74,7 @@ public function addChild(self $child): self { $this->children[] = $child; $child->setParent($this); + return $this; } } diff --git a/tests/Functional/Fixtures/Handler/TestGraylogHandler.php b/tests/Functional/Fixtures/Handler/TestGraylogHandler.php index f36c47c..f136daa 100644 --- a/tests/Functional/Fixtures/Handler/TestGraylogHandler.php +++ b/tests/Functional/Fixtures/Handler/TestGraylogHandler.php @@ -5,23 +5,22 @@ namespace Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\Handler; use Monolog\Handler\GelfHandler; +use Monolog\LogRecord; -/** - * @php-cs-fixer-ignore Paysera/php_basic_code_style_default_values_in_constructor - */ class TestGraylogHandler extends GelfHandler { - private $publishedMessages = []; + private array $publishedMessages = []; - protected function write(array $record): void + protected function write(LogRecord $record): void { $this->publishedMessages[] = $record['formatted']; } - public function flushPublishedMessages() + public function flushPublishedMessages(): array { $messages = $this->publishedMessages; $this->publishedMessages = []; + return $messages; } } diff --git a/tests/Functional/Fixtures/Handler/TestSentryTransport.php b/tests/Functional/Fixtures/Handler/TestSentryTransport.php index 519d1b1..34a2eb8 100644 --- a/tests/Functional/Fixtures/Handler/TestSentryTransport.php +++ b/tests/Functional/Fixtures/Handler/TestSentryTransport.php @@ -7,14 +7,13 @@ use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Promise\PromiseInterface; use Sentry\Event; -use Sentry\Transport\ClosableTransportInterface; use Sentry\Transport\TransportInterface; class TestSentryTransport implements TransportInterface { - private $pendingEvents; - private $events; - private $id; + private array $pendingEvents; + private array $events; + private int $id; public function __construct() { @@ -37,7 +36,7 @@ public function close(?int $timeout = null): PromiseInterface return new FulfilledPromise(true); } - public function getEvents() + public function getEvents(): array { return $this->events; } diff --git a/tests/Functional/Fixtures/Logger/TestDbalLogger.php b/tests/Functional/Fixtures/Logger/TestDbalLogger.php index c56870c..640d554 100644 --- a/tests/Functional/Fixtures/Logger/TestDbalLogger.php +++ b/tests/Functional/Fixtures/Logger/TestDbalLogger.php @@ -6,20 +6,17 @@ use Symfony\Bridge\Doctrine\Logger\DbalLogger; -/** - * @php-cs-fixer-ignore Paysera/php_basic_code_style_default_values_in_constructor - */ class TestDbalLogger extends DbalLogger { - private $queryCount = 0; + private int $queryCount = 0; - public function startQuery($sql, array $params = null, array $types = null) + public function startQuery($sql, array $params = null, array $types = null): void { parent::startQuery($sql, $params, $types); $this->queryCount++; } - public function getQueryCount() + public function getQueryCount(): int { return $this->queryCount; } diff --git a/tests/Functional/Fixtures/Service/TestTransportFactory.php b/tests/Functional/Fixtures/Service/TestTransportFactory.php index 42b3587..8707a45 100644 --- a/tests/Functional/Fixtures/Service/TestTransportFactory.php +++ b/tests/Functional/Fixtures/Service/TestTransportFactory.php @@ -10,14 +10,8 @@ class TestTransportFactory implements TransportFactoryInterface { - /** - * @var TransportInterface - */ - private $transport; - - public function __construct(TransportInterface $transport) + public function __construct(private TransportInterface $transport) { - $this->transport = $transport; } public function create(Options $options): TransportInterface diff --git a/tests/Functional/Fixtures/TestKernel.php b/tests/Functional/Fixtures/TestKernel.php index 0cab384..fe3f586 100644 --- a/tests/Functional/Fixtures/TestKernel.php +++ b/tests/Functional/Fixtures/TestKernel.php @@ -14,17 +14,12 @@ class TestKernel extends Kernel { - private $testCaseFile; - private $commonFile; - - public function __construct(string $testCaseFile, string $commonFile = 'common.yml') + public function __construct(private string $testCaseFile, private string $commonFile = 'common.yml') { parent::__construct((string)crc32($testCaseFile . $commonFile), true); - $this->testCaseFile = $testCaseFile; - $this->commonFile = $commonFile; } - public function registerBundles() + public function registerBundles(): array { return [ new FrameworkBundle(), @@ -35,7 +30,7 @@ public function registerBundles() ]; } - public function registerContainerConfiguration(LoaderInterface $loader) + public function registerContainerConfiguration(LoaderInterface $loader): void { $loader->load(__DIR__ . '/config/' . $this->commonFile); $loader->load(__DIR__ . '/config/cases/' . $this->testCaseFile); diff --git a/tests/Functional/Fixtures/config/common.yml b/tests/Functional/Fixtures/config/common.yml index 6c2bc3a..8ac0e3d 100644 --- a/tests/Functional/Fixtures/config/common.yml +++ b/tests/Functional/Fixtures/config/common.yml @@ -1,13 +1,13 @@ framework: secret: 'secret' router: - resource: '%kernel.root_dir%/config/routing.yml' + resource: '%kernel.project_dir%/tests/Functional/Fixtures/config/routes.yml' doctrine: orm: mappings: main: - dir: "%kernel.root_dir%/Entity" + dir: "%kernel.project_dir%/tests/Functional/Fixtures/Entity" prefix: "Paysera\\LoggingExtraBundle\\Tests\\Functional\\Fixtures\\Entity" type: annotation dbal: @@ -30,21 +30,22 @@ services: public_logger: alias: logger public: true - Sentry\Transport\TransportFactoryInterface: - class: \Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\Service\TestTransportFactory - arguments: - $transport: '@sentry_transport' sentry_transport: class: Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\Handler\TestSentryTransport public: true + Sentry\Transport\TransportFactoryInterface: + class: Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\Service\TestTransportFactory + arguments: + - '@sentry_transport' sentry_client: alias: Sentry\ClientInterface public: true dbal_logger: - decorates: doctrine.dbal.logger - parent: doctrine.dbal.logger class: Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\Logger\TestDbalLogger public: true public_correlation_id_provider: alias: 'paysera_logging_extra.correlation_id_provider' public: true + annotation_reader: + class: Doctrine\Common\Annotations\AnnotationReader + public: true diff --git a/tests/Functional/Fixtures/config/routes.yml b/tests/Functional/Fixtures/config/routes.yml new file mode 100644 index 0000000..7920751 --- /dev/null +++ b/tests/Functional/Fixtures/config/routes.yml @@ -0,0 +1,3 @@ +docs: + path: /index + controller: test_controller:index diff --git a/tests/Functional/Fixtures/config/routing.yml b/tests/Functional/Fixtures/config/routing.yml deleted file mode 100644 index e9d6de2..0000000 --- a/tests/Functional/Fixtures/config/routing.yml +++ /dev/null @@ -1,3 +0,0 @@ -docs: - path: /index - defaults: { _controller: test_controller:index, path: '/' } diff --git a/tests/Functional/FunctionalCorrelationIdListenerTest.php b/tests/Functional/FunctionalCorrelationIdListenerTest.php index fa5bece..2a6faec 100644 --- a/tests/Functional/FunctionalCorrelationIdListenerTest.php +++ b/tests/Functional/FunctionalCorrelationIdListenerTest.php @@ -9,10 +9,7 @@ class FunctionalCorrelationIdListenerTest extends FunctionalTestCase { - /** - * @var CorrelationIdProvider - */ - private $correlationIdProvider; + private CorrelationIdProvider $correlationIdProvider; protected function setUp(): void { @@ -22,11 +19,11 @@ protected function setUp(): void $this->correlationIdProvider = $container->get('public_correlation_id_provider'); } - public function testResponseHeaders() + public function testResponseHeaders(): void { $response = $this->makeGetRequest('/index'); - $this->assertTrue($response->headers->has(CorrelationIdListener::HEADER_NAME)); - $this->assertEquals( + static::assertTrue($response->headers->has(CorrelationIdListener::HEADER_NAME)); + static::assertEquals( $response->headers->get(CorrelationIdListener::HEADER_NAME), $this->correlationIdProvider->getCorrelationId() ); diff --git a/tests/Functional/FunctionalFormattersTest.php b/tests/Functional/FunctionalFormattersTest.php index 5a38fb3..bfd8584 100644 --- a/tests/Functional/FunctionalFormattersTest.php +++ b/tests/Functional/FunctionalFormattersTest.php @@ -12,30 +12,12 @@ use Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\Logger\TestDbalLogger; use Psr\Log\LoggerInterface; -/** - * @php-cs-fixer-ignore Paysera/php_basic_code_style_splitting_in_several_lines - */ class FunctionalFormattersTest extends FunctionalTestCase { - /** - * @var TestGraylogHandler - */ - private $graylogHandler; - - /** - * @var FingersCrossedHandler - */ - private $mainHandler; - - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var TestDbalLogger - */ - private $dbalLogger; + private TestGraylogHandler $graylogHandler; + private FingersCrossedHandler $mainHandler; + private LoggerInterface $logger; + private TestDbalLogger $dbalLogger; protected function setUp(): void { @@ -48,7 +30,7 @@ protected function setUp(): void $this->dbalLogger = $container->get('dbal_logger'); } - public function testWithDoctrineEntity() + public function testWithDoctrineEntity(): void { $this->setUpDatabase(); @@ -83,6 +65,7 @@ public function testWithDoctrineEntity() $manager->persist($entity); $manager->flush(); $manager->clear(); + $this->graylogHandler->flushPublishedMessages(); /** @var PersistedEntity $child */ $child = $manager->find(PersistedEntity::class, $child->getId()); @@ -120,9 +103,9 @@ public function testWithDoctrineEntity() $messages = $this->assertWithoutQueries(function () { return $this->getGraylogMessages(); }); - $this->assertCount(5, $messages, 'Probably an error in normalization'); + static::assertCount(5, $messages, 'Probably an error in normalization'); - $this->assertSame( + static::assertSame( json_encode([ 'id' => 6, 'field' => '1.2', @@ -131,13 +114,13 @@ public function testWithDoctrineEntity() ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $messages[0]->getAdditional('ctxt_entity') ); - $this->assertSame( + static::assertSame( json_encode([ 'id' => 1, ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $messages[1]->getAdditional('ctxt_entity') ); - $this->assertSame( + static::assertSame( json_encode([ 'id' => 1, 'field' => 'Modified', @@ -146,7 +129,7 @@ public function testWithDoctrineEntity() ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $messages[2]->getAdditional('ctxt_entity') ); - $this->assertSame( + static::assertSame( json_encode([ 'id' => 1, 'field' => 'Modified', @@ -158,7 +141,7 @@ public function testWithDoctrineEntity() ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $messages[3]->getAdditional('ctxt_entity') ); - $this->assertSame( + static::assertSame( json_encode([ 'id' => 6, 'field' => '1.2', @@ -180,14 +163,16 @@ public function testWithDoctrineEntity() private function getGraylogMessages(): array { $this->mainHandler->close(); + return $this->graylogHandler->flushPublishedMessages(); } - private function assertWithoutQueries(Closure $closure) + private function assertWithoutQueries(Closure $closure): mixed { $count = $this->dbalLogger->getQueryCount(); $result = $closure(); - $this->assertSame($count, $this->dbalLogger->getQueryCount(), 'No queries must be made by logger'); + static::assertSame($count, $this->dbalLogger->getQueryCount(), 'No queries must be made by logger'); + return $result; } } diff --git a/tests/Functional/FunctionalHandlersTest.php b/tests/Functional/FunctionalHandlersTest.php index ece0c39..39cd520 100644 --- a/tests/Functional/FunctionalHandlersTest.php +++ b/tests/Functional/FunctionalHandlersTest.php @@ -15,30 +15,11 @@ class FunctionalHandlersTest extends FunctionalTestCase { - /** - * @var TestGraylogHandler - */ - private $graylogHandler; - - /** - * @var TestSentryTransport - */ - private $sentryTransport; - - /** - * @var ClientInterface - */ - private $sentryClient; - - /** - * @var FingersCrossedHandler - */ - private $mainHandler; - - /** - * @var LoggerInterface - */ - private $logger; + private TestGraylogHandler $graylogHandler; + private TestSentryTransport $sentryTransport; + private ClientInterface $sentryClient; + private FingersCrossedHandler $mainHandler; + private LoggerInterface $logger; protected function setUp(): void { @@ -52,68 +33,58 @@ protected function setUp(): void $this->sentryClient = $container->get('sentry_client'); } - public function testSentryGetsContextValues() + public function testSentryGetsContextValues(): void { $this->logger->error('Hello world', ['param1' => 'value1']); $event = $this->getSingleSentryEvent(); - $this->assertSame('value1', $event->getExtra()['param1'] ?? null); + static::assertSame('value1', $event->getExtra()['param1'] ?? null); } - public function testCorrelationId() + public function testCorrelationId(): void { $this->logger->debug('debug'); $this->logger->info('info'); $this->logger->error('error'); $correlationId = $this->getSingleSentryEvent()->getTags()['correlation_id']; - $this->assertStringStartsWith('test-application-name', $correlationId); + static::assertStringStartsWith('test-application-name', $correlationId); $correlationIds = array_map(function (Message $message) { return $message->getAdditional('correlation_id'); }, $this->getGraylogMessages()); - $this->assertSame(array_fill(0, 3, $correlationId), $correlationIds); + static::assertSame(array_fill(0, 4, $correlationId), $correlationIds); } - public function testRootPrefix() - { - $this->logger->error(sprintf('Hey from %s. Over', __FILE__)); - - $this->assertSame( - 'Hey from /FunctionalHandlersTest.php. Over', - $this->getSingleSentryEvent()->getMessage() - ); - } - - public function testIntrospection() + public function testIntrospection(): void { $this->logger->info('Info'); $this->logger->error('Err'); $messages = $this->getGraylogMessages(); - $this->assertArrayNotHasKey( + static::assertArrayNotHasKey( 'function', - $messages[0]->getAllAdditionals(), + $messages[1]->getAllAdditionals(), 'Introspection works only for errors' ); - $allAdditionals = $messages[1]->getAllAdditionals(); + $allAdditional = $messages[2]->getAllAdditionals(); - $this->assertSame('testIntrospection', $allAdditionals['function'] ?? null); - $this->assertSame(__CLASS__, $allAdditionals['class'] ?? null); + static::assertSame('testIntrospection', $allAdditional['function'] ?? null); + static::assertSame(__CLASS__, $allAdditional['class'] ?? null); } - public function testExceptionGrouping() + public function testExceptionGrouping(): void { $this->logger->error('Err 1', ['exception' => new ConnectionException('1')]); $this->logger->error('Err 2', ['exception' => new ConnectionException('2')]); $events = $this->getSentryEvents(); - $this->assertNotEmpty($events[0]->getFingerprint()); - $this->assertSame($events[0]->getFingerprint(), $events[1]->getFingerprint()); + static::assertNotEmpty($events[0]->getFingerprint()); + static::assertSame($events[0]->getFingerprint(), $events[1]->getFingerprint()); } /** @@ -122,13 +93,15 @@ public function testExceptionGrouping() private function getSentryEvents(): array { $this->sentryClient->flush(); + return $this->sentryTransport->getEvents(); } private function getSingleSentryEvent(): Event { $sentryEvents = $this->getSentryEvents(); - $this->assertCount(1, $sentryEvents); + static::assertCount(1, $sentryEvents); + return $sentryEvents[0]; } @@ -138,6 +111,7 @@ private function getSingleSentryEvent(): Event private function getGraylogMessages(): array { $this->mainHandler->close(); + return $this->graylogHandler->flushPublishedMessages(); } } diff --git a/tests/Functional/FunctionalMonologConfigurationTest.php b/tests/Functional/FunctionalMonologConfigurationTest.php index 5e7e2ec..7b30f7a 100644 --- a/tests/Functional/FunctionalMonologConfigurationTest.php +++ b/tests/Functional/FunctionalMonologConfigurationTest.php @@ -14,30 +14,11 @@ class FunctionalMonologConfigurationTest extends FunctionalTestCase { - /** - * @var TestGraylogHandler - */ - private $graylogHandler; - - /** - * @var TestSentryTransport - */ - private $sentryTransport; - - /** - * @var ClientInterface - */ - private $sentryClient; - - /** - * @var FingersCrossedHandler - */ - private $mainHandler; - - /** - * @var LoggerInterface - */ - private $logger; + private TestGraylogHandler $graylogHandler; + private TestSentryTransport $sentryTransport; + private ClientInterface $sentryClient; + private FingersCrossedHandler $mainHandler; + private LoggerInterface $logger; protected function setUp(): void { @@ -49,9 +30,11 @@ protected function setUp(): void $this->graylogHandler = $container->get('graylog_handler'); $this->sentryTransport = $container->get('sentry_transport'); $this->sentryClient = $container->get('sentry_client'); + + $this->graylogHandler->flushPublishedMessages(); } - public function testGraylog() + public function testGraylog(): void { $this->logger->debug('DEBUG'); $this->logger->info('INFO', ['param1' => 'value1']); @@ -143,7 +126,6 @@ private function assertSameGraylogMessages(array $expectations, array $published } $this->assertSame('test-application-name', $message->getHost()); - $this->assertSame('app', $message->getFacility()); } } diff --git a/tests/Functional/FunctionalTestCase.php b/tests/Functional/FunctionalTestCase.php index 08148a7..f72d0ff 100644 --- a/tests/Functional/FunctionalTestCase.php +++ b/tests/Functional/FunctionalTestCase.php @@ -9,7 +9,6 @@ use Paysera\LoggingExtraBundle\Tests\Functional\Fixtures\TestKernel; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\ResettableContainerInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -17,30 +16,19 @@ abstract class FunctionalTestCase extends TestCase { - /** - * @var TestKernel - */ - protected $kernel; + protected TestKernel $kernel; - /** - * @param string $testCase - * @param string $commonFile - * @return ContainerInterface - */ - protected function setUpContainer($testCase, $commonFile = 'common.yml') + protected function setUpContainer(string $testCase, string $commonFile = 'common.yml'): ContainerInterface { $this->kernel = new TestKernel($testCase, $commonFile); $this->kernel->boot(); + return $this->kernel->getContainer(); } protected function tearDown(): void { - $container = $this->kernel->getContainer(); $this->kernel->shutdown(); - if ($container instanceof ResettableContainerInterface) { - $container->reset(); - } $filesystem = new Filesystem(); $filesystem->remove($this->kernel->getCacheDir()); } @@ -78,7 +66,7 @@ protected function handleRequest(Request $request): Response } } - protected function setUpDatabase() + protected function setUpDatabase(): void { $entityManager = $this->getEntityManager(); $metadata = $entityManager->getMetadataFactory()->getAllMetadata(); From a42a8e0655ee4fa3581937be1ebba85d3286178f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurynas=20Grici=C5=ABnas?= Date: Fri, 31 Mar 2023 09:13:12 +0300 Subject: [PATCH 2/2] remove IDE generated files --- .phpunit.cache/test-results | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .phpunit.cache/test-results diff --git a/.phpunit.cache/test-results b/.phpunit.cache/test-results deleted file mode 100644 index f4be5b0..0000000 --- a/.phpunit.cache/test-results +++ /dev/null @@ -1 +0,0 @@ -{"version":1,"defects":{"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalCorrelationIdListenerTest::testResponseHeaders":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalFormattersTest::testWithDoctrineEntity":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testSentryGetsContextValues":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testCorrelationId":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testRootPrefix":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testIntrospection":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testExceptionGrouping":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylog":8,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithError":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfInfoMessages":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfDebugMessages":7,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testSentry":8},"times":{"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalCorrelationIdListenerTest::testResponseHeaders":0.014,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalFormattersTest::testWithDoctrineEntity":0.023,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testSentryGetsContextValues":0.01,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testCorrelationId":0.004,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testRootPrefix":0.009,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testIntrospection":0.005,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalHandlersTest::testExceptionGrouping":0.007,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylog":0.004,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithError":0.005,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfInfoMessages":0.023,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testGraylogWithLotsOfDebugMessages":0.012,"Paysera\\LoggingExtraBundle\\Tests\\Functional\\FunctionalMonologConfigurationTest::testSentry":0.004}} \ No newline at end of file