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

Possibility to use service as person_fn rather than a static function #93

Open
wants to merge 4 commits into
base: master
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
28 changes: 13 additions & 15 deletions Factories/RollbarHandlerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,33 @@
use Psr\Log\LogLevel;
use Monolog\Handler\RollbarHandler;
use Rollbar\Rollbar;
use Rollbar\Symfony\RollbarBundle\DependencyInjection\RollbarExtension;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Rollbar\Symfony\RollbarBundle\Service\PersonProviderInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Serializer\SerializerInterface;
use Throwable;
use function json_decode;

class RollbarHandlerFactory
{
public function __construct(ContainerInterface $container)
public function __construct(array $config, SerializerInterface $serializer, PersonProviderInterface $personProvider)
{
$config = $container->getParameter(RollbarExtension::ALIAS . '.config');

if (isset($_ENV['ROLLBAR_TEST_TOKEN']) && $_ENV['ROLLBAR_TEST_TOKEN']) {
$config['access_token'] = $_ENV['ROLLBAR_TEST_TOKEN'];
}

if (!empty($config['person_fn']) && is_callable($config['person_fn'])) {
$config['person'] = null;
} elseif (empty($config['person'])) {
$config['person_fn'] = static function () use ($container) {
$config['person_fn'] = static function () use ($personProvider, $serializer) {
try {
$token = $container->get('security.token_storage')->getToken();

if ($token) {
$user = $token->getUser();
$serializer = $container->get('serializer');
return \json_decode($serializer->serialize($user, 'json'), true, 512, JSON_THROW_ON_ERROR);
}
} catch (\Throwable $exception) {
// Ignore
$person = call_user_func([$personProvider, 'getUserInfo']);

return json_decode($serializer->serialize($person, 'json'), true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable) {
// do nothing
}

return [];
};
}

Expand Down
9 changes: 8 additions & 1 deletion Resources/config/services.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
services:
rollbar.person-provider:
class: Rollbar\Symfony\RollbarBundle\Service\PersonProvider
arguments:
- '@security.token_storage'
- '@serializer.normalizer.object'

Rollbar\Symfony\RollbarBundle\Factories\RollbarHandlerFactory:
arguments:
- '@service_container'
- '%rollbar.config%'
- '@serializer'
- '@rollbar.person-provider'

Rollbar\Monolog\Handler\RollbarHandler:
factory: ['@Rollbar\Symfony\RollbarBundle\Factories\RollbarHandlerFactory', createRollbarHandler]
Expand Down
28 changes: 28 additions & 0 deletions Service/PersonProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Rollbar\Symfony\RollbarBundle\Service;

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class PersonProvider implements PersonProviderInterface
{
public function __construct(
private TokenStorageInterface $tokenStorage,
private NormalizerInterface $normalizer,
) {
}

public function getUserInfo(): array|string|int|float|bool|\ArrayObject|null
{
$token = $this->tokenStorage->getToken();

if ($token) {
$user = $token->getUser();

return $this->normalizer->normalize($user, 'json');
}

return null;
}
}
8 changes: 8 additions & 0 deletions Service/PersonProviderInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Rollbar\Symfony\RollbarBundle\Service;

interface PersonProviderInterface
{
public function getUserInfo(): array|string|int|float|bool|\ArrayObject|null;
}
5 changes: 4 additions & 1 deletion Tests/Fixtures/App/AppKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace Tests\Fixtures\App;

use Exception;
use Rollbar\Symfony\RollbarBundle\RollbarBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\MonologBundle\MonologBundle;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

Expand All @@ -14,6 +16,7 @@ public function registerBundles(): iterable
{
return [
new FrameworkBundle(),
new SecurityBundle(),
new MonologBundle(),
new RollbarBundle(),
];
Expand All @@ -25,7 +28,7 @@ public function getProjectDir(): string
}

/**
* @throws \Exception
* @throws Exception
*/
public function registerContainerConfiguration(LoaderInterface $loader): void
{
Expand Down
6 changes: 6 additions & 0 deletions Tests/Fixtures/App/config/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,9 @@ framework:
router:
resource: "%kernel.project_dir%/config/routing.yml"
strict_requirements: ~

security:
firewalls:
main:
pattern: ^/dashboard
security: false
103 changes: 103 additions & 0 deletions Tests/Service/PersonProviderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

namespace Rollbar\Symfony\RollbarBundle\Tests\Service;

use ArrayObject;
use Generator;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Rollbar\Symfony\RollbarBundle\Service\PersonProvider;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class PersonProviderTest extends TestCase
{
private MockObject|TokenStorageInterface $tokenStorage;
private MockObject|NormalizerInterface $normalizer;
private PersonProvider $personProvider;

public function setUp(): void
{
$this->tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)
->onlyMethods(['getToken', 'setToken'])
->getMock();

$this->normalizer = $this->getMockBuilder(NormalizerInterface::class)
->disableOriginalConstructor()
->onlyMethods(['normalize', 'supportsNormalization'])
->getMock();

$this->personProvider = new PersonProvider($this->tokenStorage, $this->normalizer);
}

public function testNullToken(): void
{
$this->tokenStorage->method('getToken')
->willReturn(null);

$info = $this->personProvider->getUserInfo();

$this->assertEquals(null, $info);
}

public function testNullUser(): void
{
$token = $this->getMockBuilder(UsernamePasswordToken::class)
->disableOriginalConstructor()
->onlyMethods(['getUser'])
->getMock();

$token->method('getUser')
->willReturn(null);

$this->tokenStorage->method('getToken')
->willReturn($token);

$info = $this->personProvider->getUserInfo();

$this->assertEquals(null, $info);
}

public static function normalizedUserData(): Generator
{
yield 'normalized data: null' => [null, null];
yield 'normalized data: int' => [12, 12];
yield 'normalized data: float' => [12.153, 12.153];
yield 'normalized data: string' => ['[email protected]', '[email protected]'];
yield 'normalized data: array' => [
['email' => '[email protected]', 'name' => 'John'],
['email' => '[email protected]', 'name' => 'John'],
];
yield 'normalized data: ArrayObject' => [
new ArrayObject(['email' => '[email protected]', 'name' => 'John']),
new ArrayObject(['email' => '[email protected]', 'name' => 'John']),
];
yield 'normalized data: bool' => [true, true];
}

/**
* @dataProvider normalizedUserData
*/
public function testUserInTokenStorage($normalizedData, $expected): void
{
$token = $this->getMockBuilder(UsernamePasswordToken::class)
->disableOriginalConstructor()
->onlyMethods(['getUser'])
->getMock();

$token->method('getUser')
->willReturn(new InMemoryUser('john-doe', 'pass'));

$this->tokenStorage->method('getToken')
->willReturn($token);

$this->normalizer->method('normalize')
->willReturn($normalizedData);

$info = $this->personProvider->getUserInfo();

$this->assertEquals($expected, $info);
}
}
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"symfony/http-kernel": "^5.4|^6.2|^7.0",
"symfony/monolog-bundle": "^3.8",
"symfony/serializer": "^5.4|^6.2|^7.0",
"symfony/security-bundle": "^5.4|^6.4",
"ext-json": "*"
},
"require-dev": {
Expand Down