Skip to content
Closed
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
46 changes: 35 additions & 11 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,35 @@ jobs:
fail-fast: false
matrix:
php:
- '7.4'
- '8.0'
- '8.1'
- '8.2'
composer:
- ''
- '--prefer-lowest'
- '8.3'
- '8.4'
symfony_version:
- '4.4.*'
- '5.4.*'
- '6.0.*'
- '6.1.*'
- '6.2.*'
- '6.3.*'
- '6.4.*'
exclude:
# symfony 6.1+ requires PHP 8.1+
- php: '8.0'
symfony_version: '6.1.*'
- php: '8.0'
symfony_version: '6.2.*'
- php: '8.0'
symfony_version: '6.3.*'
- php: '8.0'
symfony_version: '6.4.*'
# deps:
# - 'highest'
# - 'lowest'

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Use PHP
uses: shivammathur/setup-php@v2
Expand All @@ -37,23 +56,28 @@ jobs:
working-directory: ./

- name: cache dependencies
id: cache-dependencies
uses: actions/cache@v3
id: angular-dependencies
uses: actions/cache@v4
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-${{ matrix.php }}-${{ matrix.composer }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-${{ matrix.php }}-${{ matrix.composer }}-composer-

- name: Set Symfony minor version
run: |
sed -i 's|\("symfony/.*"\): ".*^6\.0"|\1: "${{ matrix.symfony_version }}"|' composer.json
working-directory: ./

- name: Validate composer.json and composer.lock
run: composer validate
working-directory: ./

- name: Install dependencies
env:
COMPOSER_FLAGS: ${{ matrix.composer }}
run: composer update ${COMPOSER_FLAGS} --prefer-source
working-directory: ./
uses: ramsey/composer-install@v3
with:
# dependency-versions: '${{ matrix.deps }}'
working-directory: ./

- name: Run Tests
run: composer run-script ci-test
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
/build/
/composer.lock
/.phpunit.result.cache

var/cache/
2 changes: 1 addition & 1 deletion DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Configuration implements ConfigurationInterface
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('dayspring_logging');
$rootNode = $treeBuilder->getRootNode();
Expand Down
6 changes: 3 additions & 3 deletions DependencyInjection/DayspringLoggingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ public function load(array $configs, ContainerBuilder $container)

foreach ($config['session_request_processor_handlers'] as $handler) {
$definition = new Definition(SessionRequestProcessor::class);
$definition->addTag('monolog.processor', array('handler' => $handler));
$definition->addTag('monolog.processor', ['handler' => $handler]);
$definition->setAutowired(true);

$container->addDefinitions(array(
$container->addDefinitions([
'dayspring_logging.session_request_processor.'.$handler => $definition
));
]);
}
}
}
39 changes: 18 additions & 21 deletions Logger/SessionRequestProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,12 @@

use Exception;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;

class SessionRequestProcessor
{

/** @var SessionInterface $session */
private $session;
/** @var RequestStack $requestStack */
private $requestStack;
/** @var UrlMatcherInterface|RequestMatcherInterface $matcher */
Expand All @@ -26,16 +23,15 @@ class SessionRequestProcessor

protected $extraFields = [];

public function __construct(SessionInterface $session, RequestStack $requestStack, UrlMatcherInterface $matcher)
public function __construct(RequestStack $requestStack, UrlMatcherInterface $matcher)
{
$this->session = $session;
$this->requestStack = $requestStack;
$this->matcher = $matcher;
}

protected function getServerVar($var)
{
return isset($_SERVER[$var]) ? $_SERVER[$var] : null;
return $_SERVER[$var] ?? null;
}

public function setExtraField($key, $value)
Expand All @@ -51,32 +47,33 @@ public function unsetExtraField($key)
public function clearExtraFields()
{
$this->extraFields = [];
}
}

public function __invoke(array $record)
{
if (null === $this->requestId) {
if ('cli' === php_sapi_name()) {
$this->sessionId = getmypid();
} else {
try {
$this->session->start();
$this->sessionId = $this->session->getId();
} catch (\RuntimeException $e) {
$this->sessionId = '????????';
}
}
$this->requestId = substr(uniqid(), -8);
$this->_server = array(
$this->_server = [
'http.url' => ($this->getServerVar('HTTP_HOST')).'/'.($this->getServerVar('REQUEST_URI')),
'http.method' => $this->getServerVar('REQUEST_METHOD'),
'http.useragent' => $this->getServerVar('HTTP_USER_AGENT'),
'http.referer' => $this->getServerVar('HTTP_REFERER'),
'http.x_forwarded_for' => $this->getServerVar('HTTP_X_FORWARDED_FOR')
);
];
$this->_post = $this->clean($_POST);
$this->_get = $this->clean($_GET);
}
if (null === $this->sessionId) {
if (!array_key_exists('SERVER_NAME', $_SERVER)) {
$this->sessionId = getmypid();
} elseif ($this->requestStack->getMainRequest() && $this->requestStack->getMainRequest()->hasSession()) {
try {
$this->sessionId = $this->requestStack->getSession()->getId();
} catch (\RuntimeException $e) {
$this->sessionId = '????????';
}
}
}
$record['http.request_id'] = $this->requestId;
$record['http.session_id'] = $this->sessionId;
$record['http.url'] = $this->_server['http.url'];
Expand All @@ -97,7 +94,7 @@ public function __invoke(array $record)
} else {
$parameters = $this->matcher->match($request->getPathInfo());
}
$context['route'] = isset($parameters['_route']) ? $parameters['_route'] : 'n/a';
$context['route'] = $parameters['_route'] ?? 'n/a';
$context['route_parameters'] = $parameters;
} catch (Exception $e) {
}
Expand Down Expand Up @@ -129,7 +126,7 @@ protected function getMainRequest()

protected function clean($array)
{
$toReturn = array();
$toReturn = [];
foreach (array_keys($array) as $key) {
if (false !== strpos($key, 'password')) {
// Do not add
Expand Down
6 changes: 3 additions & 3 deletions Tests/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ class ConfigurationTest extends TestCase

public function testConfiguration()
{
$config = array();
$config = [];

$processor = new Processor();
$configuration = new Configuration(array());
$config = $processor->processConfiguration($configuration, array($config));
$configuration = new Configuration([]);
$config = $processor->processConfiguration($configuration, [$config]);

$this->assertEquals([
'session_request_processor_handlers' => []
Expand Down
10 changes: 5 additions & 5 deletions Tests/DependencyInjection/ExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public function testLoadEmptyConfiguration()
{
$container = $this->createContainer();
$extension = new DayspringLoggingExtension();
$extension->load(array(), $container);
$extension->load([], $container);
$container->registerExtension($extension);

$this->compileContainer($container);
Expand All @@ -32,19 +32,19 @@ public function testLoadEmptyConfiguration()

private function createContainer()
{
$container = new ContainerBuilder(new ParameterBag(array(
$container = new ContainerBuilder(new ParameterBag([
'kernel.cache_dir' => __DIR__,
'kernel.charset' => 'UTF-8',
'kernel.debug' => false,
)));
]));

return $container;
}

private function compileContainer(ContainerBuilder $container)
{
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->getCompilerPassConfig()->setOptimizationPasses([]);
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->compile();
}
}
96 changes: 92 additions & 4 deletions Tests/Logger/SessionRequestProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,32 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionFactory;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\Routing\Router;
use function var_dump;

class SessionRequestProcessorTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();

$_SERVER['SERVER_NAME'] = 'test';
}

public function testProcessor()
{
$session = new Session();
$request = Request::create('/', 'GET');
$request->setSession(new Session(new MockFileSessionStorage()));

$requestStack = new RequestStack();
$requestStack->push(Request::create('/', 'GET'));
$requestStack->push($request);
$router = $this->createPartialMock(Router::class, ['matchRequest']);
$router->expects($this->once())
->method('matchRequest')
->willReturn(['_route' => 'test']);

$processor = new SessionRequestProcessor($session, $requestStack, $router);
$processor = new SessionRequestProcessor($requestStack, $router);

$handler = new TestHandler();

Expand All @@ -39,5 +48,84 @@ public function testProcessor()
$record = $records[0];
$this->assertEquals('test', $record['context']['route']);
$this->assertEquals('test', $record['context']['route_parameters']['_route']);
$this->assertArrayHasKey('http.session_id', $record);
}

public function testProcessorCli()
{
unset($_SERVER['SERVER_NAME']);

$requestStack = new RequestStack();
$router = $this->createPartialMock(Router::class, ['matchRequest']);

$processor = new SessionRequestProcessor($requestStack, $router);

$handler = new TestHandler();

$logger = new Logger('test', [$handler], [$processor]);

$logger->info('test');

$records = $handler->getRecords();

$this->assertCount(1, $records);
$record = $records[0];
$this->assertArrayHasKey('http.session_id', $record);
$this->assertEquals($record['http.session_id'], getmypid());

}

public function testProcessorNoRequest()
{
$requestStack = new RequestStack();
$router = $this->createPartialMock(Router::class, ['matchRequest']);

$processor = new SessionRequestProcessor($requestStack, $router);

$handler = new TestHandler();

$logger = new Logger('test', [$handler], [$processor]);

$logger->info('test');

$records = $handler->getRecords();

$this->assertCount(1, $records);
$record = $records[0];
$this->assertArrayNotHasKey('route', $record['context']);
$this->assertNull($record['http.session_id']);
}


public function testProcessorRequestAddedLater()
{
$requestStack = new RequestStack();
$router = $this->createPartialMock(Router::class, ['matchRequest']);

$processor = new SessionRequestProcessor($requestStack, $router);

$handler = new TestHandler();

$logger = new Logger('test', [$handler], [$processor]);

$logger->info('test');

$request = Request::create('/', 'GET');
$request->setSession(new Session(new MockFileSessionStorage()));
$requestStack->push($request);

$logger->info('test with session');

$records = $handler->getRecords();

$this->assertCount(2, $records);
$record = $records[0];
$this->assertArrayNotHasKey('route', $record['context']);
$this->assertNull($record['http.session_id']);

$record2 = $records[1];
$this->assertArrayHasKey('route', $record2['context']);
$this->assertNotNull($record2['http.session_id']);
$this->assertEquals($record['http.request_id'], $record2['http.request_id']);
}
}
Loading
Loading