Skip to content

Commit

Permalink
Add functional test and fix container usage (#472)
Browse files Browse the repository at this point in the history
* Add functional test

* Fix action service id

* Bump doctrine-bundle

* Deprecate instantiating TokenStorageUsernameCallable with Container
  • Loading branch information
franmomu authored Jan 25, 2022
1 parent 0d27594 commit 0175923
Show file tree
Hide file tree
Showing 16 changed files with 395 additions and 19 deletions.
4 changes: 0 additions & 4 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,6 @@ jobs:
dependencies: lowest
allowed-to-fail: false
variant: normal
- php-version: '8.1'
dependencies: highest
allowed-to-fail: false
variant: symfony/framework-bundle:"4.4.*"
- php-version: '8.1'
dependencies: highest
allowed-to-fail: false
Expand Down
9 changes: 7 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"twig/twig": "^2.6 || ^3.0"
},
"require-dev": {
"doctrine/doctrine-bundle": "^1.4 || ^2.2",
"doctrine/doctrine-bundle": "^1.12.8 || ^2.3.2",
"doctrine/doctrine-fixtures-bundle": "^3.4",
"gedmo/doctrine-extensions": "^3.0",
"matthiasnoback/symfony-dependency-injection-test": "^4.2.1",
"phpstan/extension-installer": "^1.1",
Expand All @@ -34,15 +35,19 @@
"phpunit/phpunit": "^9.5",
"psalm/plugin-phpunit": "^0.16.1",
"psalm/plugin-symfony": "^3.0",
"symfony/browser-kit": "^4.4 || ^5.3 || ^6.0",
"symfony/cache": "^4.4 || ^5.3 || ^6.0",
"symfony/framework-bundle": "^4.4 || ^5.3 || ^6.0",
"symfony/http-foundation": "^4.4 || ^5.3 || ^6.0",
"symfony/phpunit-bridge": "^6.0",
"symfony/security-bundle": "^4.4 || ^5.3 || ^6.0",
"symfony/twig-bundle": "^4.4 || ^5.3 || ^6.0",
"symfony/var-dumper": "^4.4 || ^5.3 || ^6.0",
"vimeo/psalm": "^4.8",
"weirdan/doctrine-psalm-plugin": "^2.0"
},
"conflict": {
"doctrine/doctrine-bundle": "<1.4",
"doctrine/doctrine-bundle": "<1.12.8",
"gedmo/doctrine-extensions": "<3.0",
"symfony/framework-bundle": "<4.4"
},
Expand Down
2 changes: 1 addition & 1 deletion src/Resources/config/actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
new ReferenceConfigurator('simplethings_entityaudit.reader'),
])

->set(ViewDetailAction::class, ViewEntityAction::class)
->set(ViewEntityAction::class, ViewEntityAction::class)
->public()
->args([
new ReferenceConfigurator('twig'),
Expand Down
2 changes: 1 addition & 1 deletion src/Resources/config/auditable.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
->args([new ReferenceConfigurator('simplethings_entityaudit.manager')])

->set('simplethings_entityaudit.username_callable.token_storage', TokenStorageUsernameCallable::class)
->args([new ReferenceConfigurator('service_container')])
->args([new ReferenceConfigurator('security.token_storage')])

->set('simplethings_entityaudit.config', AuditConfiguration::class)
->public()
Expand Down
45 changes: 35 additions & 10 deletions src/User/TokenStorageUsernameCallable.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,45 @@
namespace SimpleThings\EntityAudit\User;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class TokenStorageUsernameCallable
{
/**
* NEXT_MAJOR: Inject the required services instead of using the container.
*
* @var Container
* @var TokenStorageInterface
*/
private $container;
private $tokenStorage;

public function __construct(Container $container)
/**
* NEXT_MAJOR: remove Container type.
*
* @param Container|TokenStorageInterface $tokenStorageOrContainer
*/
public function __construct(object $tokenStorageOrContainer)
{
$this->container = $container;
if ($tokenStorageOrContainer instanceof TokenStorageInterface) {
$this->tokenStorage = $tokenStorageOrContainer;
} elseif ($tokenStorageOrContainer instanceof Container) {
@trigger_error(sprintf(
'Passing as argument 1 an instance of "%s" to "%s" is deprecated since'
.' sonata-project/entity-audit-bundle 1.x and will throw an "%s" in version 2.0.'
.' You must pass an instance of "%s" instead.',
Container::class,
__METHOD__,
\TypeError::class,
TokenStorageInterface::class
), \E_USER_DEPRECATED);

$this->tokenStorage = $tokenStorageOrContainer->get('security.token_storage');
} else {
throw new \TypeError(sprintf(
'Argument 1 passed to "%s()" must be an instance of "%s" or %s, instance of "%s" given.',
__METHOD__,
TokenStorageInterface::class,
Container::class,
\get_class($tokenStorageOrContainer)
));
}
}

/**
Expand All @@ -37,10 +62,10 @@ public function __construct(Container $container)
*/
public function __invoke()
{
/** @var TokenInterface $token */
$token = $this->container->get('security.token_storage')->getToken();
$token = $this->tokenStorage->getToken();

if (null !== $token && null !== $token->getUser()) {
// @phpstan-ignore-next-line
// @phpstan-ignore-next-line Use only "getUserIdentifier" when dropping support of Symfony < 5.3
return method_exists($token, 'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername();
}

Expand Down
92 changes: 92 additions & 0 deletions tests/App/AppKernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SimpleThings\EntityAudit\Tests\App;

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle;
use SimpleThings\EntityAudit\SimpleThingsEntityAuditBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

final class AppKernel extends Kernel
{
use MicroKernelTrait;

public function __construct()
{
parent::__construct('test', false);
}

public function registerBundles(): iterable
{
return [
new FrameworkBundle(),
new TwigBundle(),
new DoctrineBundle(),
new SecurityBundle(),
new DoctrineFixturesBundle(),
new SimpleThingsEntityAuditBundle(),
];
}

public function getCacheDir(): string
{
return sprintf('%scache', $this->getBaseDir());
}

public function getLogDir(): string
{
return sprintf('%slog', $this->getBaseDir());
}

public function getProjectDir(): string
{
return __DIR__;
}

/**
* TODO: add typehint when support for Symfony < 5.1 is dropped.
*
* @param RoutingConfigurator $routes
*/
protected function configureRoutes($routes): void
{
$routes->import(sprintf('%s/config/routes.yml', $this->getProjectDir()));
}

protected function configureContainer(ContainerBuilder $containerBuilder, LoaderInterface $loader): void
{
$loader->load(__DIR__.'/config/config.yml');

if (class_exists(InputBag::class)) {
$loader->load(__DIR__.'/config/config_symfony_v5.yml');
} else {
$loader->load(__DIR__.'/config/config_symfony_v4.yml');
}

$loader->load(__DIR__.'/config/services.php');
}

private function getBaseDir(): string
{
return sprintf('%s/entity-audit-bundle/var/', sys_get_temp_dir());
}
}
33 changes: 33 additions & 0 deletions tests/App/DataFixtures/UserFixture.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SimpleThings\EntityAudit\Tests\App\DataFixtures;

use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use SimpleThings\EntityAudit\Tests\App\Entity\User;

final class UserFixture extends Fixture
{
public function load(ObjectManager $manager): void
{
$user = new User('bob');

$manager->persist($user);
$manager->flush();

$user->setName('alice');

$manager->flush();
}
}
59 changes: 59 additions & 0 deletions tests/App/Entity/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SimpleThings\EntityAudit\Tests\App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="bundle_user")
*/
class User
{
/**
* @var int|null
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;

/**
* @var string
*
* @ORM\Column(type="string")
*/
private $name;

public function __construct(string $name)
{
$this->name = $name;
}

public function setName(string $name): void
{
$this->name = $name;
}

public function getId(): ?int
{
return $this->id;
}

public function getName(): string
{
return $this->name;
}
}
28 changes: 28 additions & 0 deletions tests/App/config/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
framework:
secret: '%env(APP_SECRET)%'
test: true

twig:
exception_controller: null
strict_variables: false

parameters:
env(DATABASE_URL): 'sqlite:////%kernel.cache_dir%/test_database.db'

doctrine:
dbal:
url: "%env(resolve:DATABASE_URL)%"
orm:
auto_generate_proxy_classes: true
auto_mapping: true
mappings:
AuditEntityTest:
type: annotation
dir: "%kernel.project_dir%/Entity"
is_bundle: false
prefix: SimpleThings\EntityAudit\Tests\App\Entity

simple_things_entity_audit:
revision_table_name: bundle_revisions
audited_entities:
- SimpleThings\EntityAudit\Tests\App\Entity\User
8 changes: 8 additions & 0 deletions tests/App/config/config_symfony_v4.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
framework:
session:
storage_id: session.storage.mock_file

security:
firewalls:
main:
anonymous: true
11 changes: 11 additions & 0 deletions tests/App/config/config_symfony_v5.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
framework:
session:
storage_factory_id: session.storage.factory.mock_file
router:
utf8: true

security:
enable_authenticator_manager: true
firewalls:
main:
lazy: true
3 changes: 3 additions & 0 deletions tests/App/config/routes.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
simple_things_entity_audit:
resource: "@SimpleThingsEntityAuditBundle/Resources/config/routing/audit.xml"
prefix: /audit
22 changes: 22 additions & 0 deletions tests/App/config/services.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
$containerConfigurator->services()
->defaults()
->autowire()
->autoconfigure()
->load('SimpleThings\\EntityAudit\\Tests\\App\\DataFixtures\\', dirname(__DIR__).'/DataFixtures');
};
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function testItRegistersDefaultServices(): void
$this->assertContainerBuilderHasServiceDefinitionWithTag('simplethings_entityaudit.create_schema_listener', 'doctrine.event_subscriber', ['connection' => 'default']);

$this->assertContainerBuilderHasService('simplethings_entityaudit.username_callable.token_storage', 'SimpleThings\EntityAudit\User\TokenStorageUsernameCallable');
$this->assertContainerBuilderHasServiceDefinitionWithArgument('simplethings_entityaudit.username_callable.token_storage', 0, 'service_container');
$this->assertContainerBuilderHasServiceDefinitionWithArgument('simplethings_entityaudit.username_callable.token_storage', 0, 'security.token_storage');

$this->assertContainerBuilderHasService('simplethings_entityaudit.config', 'SimpleThings\EntityAudit\AuditConfiguration');
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setAuditedEntityClasses', ['%simplethings.entityaudit.audited_entities%']);
Expand Down
Loading

0 comments on commit 0175923

Please sign in to comment.