Skip to content

Commit

Permalink
update CI allow usage of custom user class and methods to be add in e…
Browse files Browse the repository at this point in the history
…xtra info + tests (#4)
  • Loading branch information
Deamon committed Mar 17, 2017
1 parent f9859c9 commit de651c1
Show file tree
Hide file tree
Showing 9 changed files with 340 additions and 59 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -1 +1,2 @@
/vendor
composer.lock
2 changes: 1 addition & 1 deletion .travis.yml
Expand Up @@ -15,4 +15,4 @@ before_script:
- if [ "$deps" == "low" ]; then composer update --prefer-source --prefer-lowest --prefer-stable; fi
- if [ "$deps" != "low" ]; then composer install --prefer-source; fi

script: composer test
script: ./vendor/bin/phpunit
18 changes: 13 additions & 5 deletions DependencyInjection/Configuration.php
Expand Up @@ -29,13 +29,24 @@ public function getConfigTreeBuilder()
->arrayNode('handlers')->isRequired()
->beforeNormalization()
->ifString()
->then(function ($v) { return array($v); })
->then(function ($v) {
return array($v);
})
->end()
->prototype('scalar')->isRequired()->cannotBeEmpty()->end()
->end()
->arrayNode('config')->isRequired()->addDefaultsIfNotSet()
->children()
->scalarNode('channel_prefix')->defaultNull()->cannotBeEmpty()->end()
->scalarNode('channel_prefix')->defaultNull()->end()
->scalarNode('user_class')->defaultValue('\Symfony\Component\Security\Core\User\UserInterface')->end()
->arrayNode('user_methods')
->useAttributeAsKey('value')
->normalizeKeys(false)
->defaultValue(array(
'user_name' => 'getUsername',
))
->prototype('scalar')->end()
->end()
->arrayNode('display')->addDefaultsIfNotSet()
->children()
->booleanNode('env')->defaultTrue()->end()
Expand All @@ -47,9 +58,6 @@ public function getConfigTreeBuilder()
->booleanNode('accept_encoding')->defaultTrue()->end()
->booleanNode('client_ip')->defaultTrue()->end()
->booleanNode('user')->defaultTrue()->end()
->booleanNode('user_id')->defaultTrue()->end()
->booleanNode('user_email')->defaultTrue()->end()
->booleanNode('user_name')->defaultTrue()->end()
->booleanNode('global_channel')->defaultTrue()->end()
->end()
->end()
Expand Down
61 changes: 43 additions & 18 deletions Processors/Monolog/DeamonLoggerExtraWebProcessor.php
Expand Up @@ -3,15 +3,14 @@
namespace Deamon\LoggerExtraBundle\Processors\Monolog;

use Symfony\Bridge\Monolog\Processor\WebProcessor as BaseWebProcessor;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class DeamonLoggerExtraWebProcessor extends BaseWebProcessor
{
/**
* @var Container
* @var ContainerInterface
*/
private $container = null;

Expand All @@ -25,17 +24,25 @@ class DeamonLoggerExtraWebProcessor extends BaseWebProcessor
*/
private $channelPrefix;

/** @var string */
private $userClass;

/** @var array */
private $userMethods;

/**
* @var array
*/
private $record;

public function __construct($container = null, array $config = null)
public function __construct(ContainerInterface $container = null, array $config = null)
{
parent::__construct();
$this->container = $container;
$this->channelPrefix = $config['channel_prefix'];
$this->displayConfig = $config['display'];
$this->userClass = $config['user_class'];
$this->userMethods = $config['user_methods'];
}

/**
Expand All @@ -59,11 +66,9 @@ public function __invoke(array $record)
return $this->record;
}

public function setContainer($container)
{
$this->container = $container;
}

/**
* Add extra info about the context of the generated log.
*/
private function addContextInfo()
{
$this->addInfo('env', $this->container->get('kernel')->getEnvironment());
Expand All @@ -76,6 +81,9 @@ private function addContextInfo()
}
}

/**
* Add extra info about the request generating the log.
*/
private function addRequestInfo()
{
if (null !== $request_stack = $this->container->get('request_stack')) {
Expand All @@ -90,24 +98,29 @@ private function addRequestInfo()
}
}

/**
* Add extra info on the user generating the log.
*/
private function addUserInfo()
{
if ($this->configShowExtraInfo('user')) {
if (!class_exists($this->userClass) && !interface_exists($this->userClass)) {
return;
}
$token = $this->container->get('security.token_storage')->getToken();
if (($token instanceof TokenInterface) && ($token->getUser() instanceof UserInterface) && null !== $user = $token->getUser()) {
if ($this->configShowExtraInfo('user_id') && method_exists($user, 'getId')) {
$this->record['extra']['user_id'] = $user->getId();
}
if ($this->configShowExtraInfo('user_email') && method_exists($user, 'getEmail')) {
$this->record['extra']['user_email'] = $user->getEmail();
}
if ($this->configShowExtraInfo('user_name') && method_exists($user, 'getUsername')) {
$this->record['extra']['user_name'] = $user->getUsername();
if (($token instanceof TokenInterface) && ($token->getUser() instanceof $this->userClass) && null !== $user = $token->getUser()) {
foreach ($this->userMethods as $name => $method) {
if (method_exists($user, $method)) {
$this->record['extra'][$name] = $user->$method();
}
}
}
}
}

/**
* Add channel info to ease the log interpretation.
*/
private function addChannelInfo()
{
$this->addInfo('global_channel', $this->record['channel']);
Expand All @@ -118,6 +131,8 @@ private function addChannelInfo()
}

/**
* Add the extra info if configured to.
*
* @param string $key
* @param mixed $value
*/
Expand All @@ -129,6 +144,8 @@ private function addInfo($key, $value)
}

/**
* Tells if the config to display the extra info is enabled or not.
*
* @param string $extraInfo
*
* @return bool
Expand All @@ -137,4 +154,12 @@ private function configShowExtraInfo($extraInfo)
{
return isset($this->displayConfig[$extraInfo]) && $this->displayConfig[$extraInfo];
}

/**
* @param ContainerInterface $container
*/
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}
}
39 changes: 25 additions & 14 deletions README.md
Expand Up @@ -48,23 +48,34 @@ deamon_logger_extra:

```
deamon_logger_extra:
application:
application:
name: "loc-deamonfront" #default to null
handlers: [default_info] #the only required field
config:
channel_prefix: "v0.1" #default to null
user_class: "\Symfony\Component\Security\Core\User\UserInterface"
user_methods:
user_name: getUsername
display:
env: boolean default to true
locale: boolean default to true
application_name: boolean default to true
url: boolean default to true
route: boolean default to true
user_agent: boolean default to true
accept_encoding: boolean default to true
client_ip: boolean default to true
user: boolean default to true
user_id: boolean default to true
user_email: boolean default to true
user_name: boolean default to true
global_channel: boolean default to true
env: true
locale: boolean #default to true
application_name: boolean #default to true
url: boolean #default to true
route: boolean #default to true
user_agent: boolean #default to true
accept_encoding: boolean #default to true
client_ip: boolean #default to true
user: boolean #default to true
user_id: boolean #default to true
user_email: boolean #default to true
user_name: boolean #default to true
global_channel: boolean #default to true
```
## Minimal configuration

```
deamon_logger_extra:
application: ~
handlers: 'main'
config: ~
```
158 changes: 158 additions & 0 deletions Tests/DependencyInjection/DeamonLoggerExtraExtensionTest.php
@@ -0,0 +1,158 @@
<?php

namespace DependencyInjection;

use Deamon\LoggerExtraBundle\DependencyInjection\DeamonLoggerExtraExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class DeamonLoggerExtraExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DeamonLoggerExtraExtension
*/
private $extension;

/**
* @var string
*/
private $root;

/**
* @var ContainerBuilder
*/
private $container;

public function setUp()
{
parent::setUp();

$this->extension = new DeamonLoggerExtraExtension();
$this->root = 'deamon_logger_extra';
$this->container = new ContainerBuilder();
}

public function testLoad()
{
$configs = [
$this->getValidConfigFull(),
];
$this->extension->load($configs, $this->container);

$this->assertTrue($this->container->hasDefinition('deamon.logger_extra.context'));
$this->assertTrue($this->container->hasDefinition('deamon.logger_extra.processors.web_processor'));

$definition1 = $this->container->getDefinition('deamon.logger_extra.context');
$this->assertEquals('foo', $definition1->getArgument(1));

$definition2 = $this->container->getDefinition('deamon.logger_extra.processors.web_processor');
$this->assertEquals($configs[0]['config'], $definition2->getArgument(1));

$this->assertTrue($definition2->hasTag('monolog.processor'));
$tag = $definition2->getTag('monolog.processor');
$this->assertCount(1, $tag);
$this->assertEquals('bar', $tag[0]['handler']);
}

public function testDefaultValue()
{
$configs = [
$this->getValidConfigMin(),
];

$defaultConfigValues = [
'channel_prefix' => null,
'user_class' => '\Symfony\Component\Security\Core\User\UserInterface',
'user_methods' => [
'user_name' => 'getUsername',
],
'display' => [
'env' => true,
'locale' => true,
'application_name' => true,
'url' => true,
'route' => true,
'user_agent' => true,
'accept_encoding' => true,
'client_ip' => true,
'user' => true,
'global_channel' => true,
],
];
$this->extension->load($configs, $this->container);

$this->assertTrue($this->container->hasDefinition('deamon.logger_extra.context'));
$this->assertTrue($this->container->hasDefinition('deamon.logger_extra.processors.web_processor'));

$definition1 = $this->container->getDefinition('deamon.logger_extra.context');
$this->assertNull($definition1->getArgument(1));

$definition2 = $this->container->getDefinition('deamon.logger_extra.processors.web_processor');
$this->assertEquals($defaultConfigValues, $definition2->getArgument(1));
}

public function testConvertStringHandlerToArray()
{
$configs = [
[
'application' => null,
'handlers' => 'bar',
'config' => null,
],
];
$this->extension->load($configs, $this->container);

$this->assertTrue($this->container->hasDefinition('deamon.logger_extra.context'));
$this->assertTrue($this->container->hasDefinition('deamon.logger_extra.processors.web_processor'));

$definition = $this->container->getDefinition('deamon.logger_extra.processors.web_processor');

$this->assertTrue($definition->hasTag('monolog.processor'));
$tag = $definition->getTag('monolog.processor');
$this->assertCount(1, $tag);
$this->assertEquals('bar', $tag[0]['handler']);
}

/**
* @return array
*/
private function getValidConfigFull()
{
return [
'application' => [
'name' => 'foo',
],
'handlers' => ['bar'],
'config' => [
'channel_prefix' => 'barPrefix',
'user_class' => '\Symfony\Component\Security\Core\User\UserInterface',
'user_methods' => [
'user_name' => 'getUsername',
],
'display' => [
'env' => true,
'locale' => true,
'application_name' => true,
'url' => true,
'route' => true,
'user_agent' => true,
'accept_encoding' => true,
'client_ip' => true,
'user' => true,
'global_channel' => true,
],
],
];
}

/**
* @return array
*/
private function getValidConfigMin()
{
return [
'application' => null,
'handlers' => ['bar'],
'config' => null,
];
}
}

0 comments on commit de651c1

Please sign in to comment.