Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[CallableWrapper] Add CallableWrapper component and framework integration #58076

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

Closed
wants to merge 1 commit into from
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
Add CallableWrapper component and framework integration
  • Loading branch information
yceruto committed Dec 13, 2024
commit bcedbc64ba5e561babbe648b9cf38a24b26e4b17
1 change: 1 addition & 0 deletions 1 composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"symfony/config": "self.version",
"symfony/console": "self.version",
"symfony/css-selector": "self.version",
"symfony/callable-wrapper": "self.version",
"symfony/dependency-injection": "self.version",
"symfony/debug-bundle": "self.version",
"symfony/doctrine-bridge": "self.version",
Expand Down
1 change: 1 addition & 0 deletions 1 src/Symfony/Bridge/Doctrine/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Accept `ReadableCollection` in `CollectionToArrayTransformer`
* Add `Transactional` attribute and `TransactionalCallableWrapper`

7.1
---
Expand Down
31 changes: 31 additions & 0 deletions 31 src/Symfony/Bridge/Doctrine/CallableWrapper/Transactional.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\CallableWrapper;

use Symfony\Component\CallableWrapper\Attribute\CallableWrapperAttribute;

/**
* Wraps persistence method operations within a single Doctrine transaction.
*
* @author Yonel Ceruto <open@yceruto.dev>
*/
#[\Attribute(\Attribute::TARGET_METHOD)]
class Transactional extends CallableWrapperAttribute
{
/**
* @param string|null $name The entity manager name (null for the default one)
*/
public function __construct(
public ?string $name = null,
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\CallableWrapper;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\CallableWrapper\CallableWrapperInterface;

/**
* @author Yonel Ceruto <open@yceruto.dev>
*/
class TransactionalCallableWrapper implements CallableWrapperInterface
{
public function __construct(
private readonly ManagerRegistry $managerRegistry,
) {
}

public function wrap(\Closure $func, Transactional $transactional = new Transactional()): \Closure
{
$entityManager = $this->managerRegistry->getManager($transactional->name);

if (!$entityManager instanceof EntityManagerInterface) {
throw new \RuntimeException(\sprintf('The manager "%s" is not an entity manager.', $transactional->name));
}

return static function (mixed ...$args) use ($func, $entityManager) {
$entityManager->getConnection()->beginTransaction();

try {
$return = $func(...$args);

$entityManager->flush();
$entityManager->getConnection()->commit();

return $return;
} catch (\Throwable $e) {
$entityManager->close();
$entityManager->getConnection()->rollBack();

throw $e;
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\Tests\CallableWrapper;

use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\CallableWrapper\Transactional;
use Symfony\Bridge\Doctrine\CallableWrapper\TransactionalCallableWrapper;
use Symfony\Component\CallableWrapper\CallableWrapper;
use Symfony\Component\CallableWrapper\Resolver\CallableWrapperResolver;

class TransactionalCallableWrapperTest extends TestCase
{
private ManagerRegistry $managerRegistry;
private Connection $connection;
private EntityManagerInterface $entityManager;
private CallableWrapper $wrapper;

protected function setUp(): void
{
$this->connection = $this->createMock(Connection::class);

$this->entityManager = $this->createMock(EntityManagerInterface::class);
$this->entityManager->method('getConnection')->willReturn($this->connection);

$this->managerRegistry = $this->createMock(ManagerRegistry::class);
$this->managerRegistry->method('getManager')->willReturn($this->entityManager);

$this->wrapper = new CallableWrapper(new CallableWrapperResolver([
TransactionalCallableWrapper::class => fn () => new TransactionalCallableWrapper($this->managerRegistry),
]));
}

public function testWrapInTransactionAndFlushes()
{
$handler = new TestHandler();

$this->connection->expects($this->once())->method('beginTransaction');
$this->connection->expects($this->once())->method('commit');
$this->entityManager->expects($this->once())->method('flush');

$result = $this->wrapper->call($handler->handle(...));
$this->assertSame('success', $result);
}

public function testTransactionIsRolledBackOnException()
{
$this->connection->expects($this->once())->method('beginTransaction');
$this->connection->expects($this->once())->method('rollBack');

$handler = new TestHandler();

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('A runtime error.');

$this->wrapper->call($handler->handleWithError(...));
}

public function testInvalidEntityManagerThrowsException()
{
$this->managerRegistry
->method('getManager')
->with('unknown_manager')
->willThrowException(new \InvalidArgumentException());

$handler = new TestHandler();

$this->expectException(\InvalidArgumentException::class);

$this->wrapper->call($handler->handleWithUnknownManager(...));
}
}

class TestHandler
{
#[Transactional]
public function handle(): string
{
return 'success';
}

#[Transactional]
public function handleWithError(): void
{
throw new \RuntimeException('A runtime error.');
}

#[Transactional('unknown_manager')]
public function handleWithUnknownManager(): void
{
}
}
1 change: 1 addition & 0 deletions 1 src/Symfony/Bridge/Doctrine/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"require-dev": {
"symfony/cache": "^6.4|^7.0",
"symfony/config": "^6.4|^7.0",
"symfony/callable-wrapper": "^7.3",
"symfony/dependency-injection": "^6.4|^7.0",
"symfony/doctrine-messenger": "^6.4|^7.0",
"symfony/expression-language": "^6.4|^7.0",
Expand Down
1 change: 1 addition & 0 deletions 1 src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* Add support for assets pre-compression
* Rename `TranslationUpdateCommand` to `TranslationExtractCommand`
* Add JsonEncoder services and configuration
* Add CallableWrapper services and support

7.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use Symfony\Component\Cache\DependencyInjection\CachePoolPass;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\CallableWrapper\CallableWrapperInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\FileLocator;
Expand Down Expand Up @@ -235,6 +236,10 @@ public function load(array $configs, ContainerBuilder $container): void
$loader->load('fragment_renderer.php');
$loader->load('error_renderer.php');

if (ContainerBuilder::willBeAvailable('symfony/callable-wrapper', CallableWrapperInterface::class, ['symfony/framework-bundle'])) {
$loader->load('callable_wrapper.php');
}

if (!ContainerBuilder::willBeAvailable('symfony/clock', ClockInterface::class, ['symfony/framework-bundle'])) {
$container->removeDefinition('clock');
$container->removeAlias(ClockInterface::class);
Expand Down Expand Up @@ -683,6 +688,8 @@ public function load(array $configs, ContainerBuilder $container): void
->addTag('mime.mime_type_guesser');
$container->registerForAutoconfiguration(LoggerAwareInterface::class)
->addMethodCall('setLogger', [new Reference('logger')]);
$container->registerForAutoconfiguration(CallableWrapperInterface::class)
->addTag('callable_wrapper');

$container->registerAttributeForAutoconfiguration(AsEventListener::class, static function (ChildDefinition $definition, AsEventListener $attribute, \ReflectionClass|\ReflectionMethod $reflector) {
$tagAttributes = get_object_vars($attribute);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\EventListener;

use Symfony\Component\CallableWrapper\CallableWrapperInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
* @author Yonel Ceruto <open@yceruto.dev>
*/
class WrapControllerListener implements EventSubscriberInterface
{
public function __construct(
private readonly CallableWrapperInterface $wrapper,
) {
}

public function decorate(ControllerArgumentsEvent $event): void
{
$event->setController($this->wrapper->wrap($event->getController()(...)));
}

public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER_ARGUMENTS => ['decorate', -1024],
];
}
}
2 changes: 2 additions & 0 deletions 2 src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use Symfony\Component\Cache\DependencyInjection\CachePoolClearerPass;
use Symfony\Component\Cache\DependencyInjection\CachePoolPass;
use Symfony\Component\Cache\DependencyInjection\CachePoolPrunerPass;
use Symfony\Component\CallableWrapper\DependencyInjection\CallableWrappersPass;
use Symfony\Component\Config\Resource\ClassExistenceResource;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\DependencyInjection\AddConsoleCommandPass;
Expand Down Expand Up @@ -181,6 +182,7 @@ public function build(ContainerBuilder $container): void
// must be registered after MonologBundle's LoggerChannelPass
$container->addCompilerPass(new ErrorLoggerCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -32);
$container->addCompilerPass(new VirtualRequestStackPass());
$this->addCompilerPassIfExists($container, CallableWrappersPass::class);

if ($container->getParameter('kernel.debug')) {
$container->addCompilerPass(new AddDebugLogProcessorPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 2);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bundle\FrameworkBundle\EventListener\WrapControllerListener;
use Symfony\Component\CallableWrapper\CallableWrapper;
use Symfony\Component\CallableWrapper\CallableWrapperInterface;
use Symfony\Component\CallableWrapper\Resolver\CallableWrapperResolverInterface;

return static function (ContainerConfigurator $container) {
$container->services()
->set('callable_wrapper', CallableWrapper::class)
->args([
service(CallableWrapperResolverInterface::class),
])

->alias(CallableWrapperInterface::class, 'callable_wrapper')

->set('callable_wrapper.wrap_controller.listener', WrapControllerListener::class)
->args([
service('callable_wrapper'),
])
->tag('kernel.event_subscriber')
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@
->abstract()
->args([
abstract_arg('bus handler resolver'),
false,
service('callable_wrapper')->ignoreOnInvalid(),
])
->tag('monolog.logger', ['channel' => 'messenger'])
->call('setLogger', [service('logger')->ignoreOnInvalid()])
Expand Down
1 change: 1 addition & 0 deletions 1 src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"symfony/console": "^6.4|^7.0",
"symfony/clock": "^6.4|^7.0",
"symfony/css-selector": "^6.4|^7.0",
"symfony/callable-wrapper": "^7.3",
"symfony/dom-crawler": "^6.4|^7.0",
"symfony/dotenv": "^6.4|^7.0",
"symfony/polyfill-intl-icu": "~1.0",
Expand Down
3 changes: 3 additions & 0 deletions 3 src/Symfony/Component/CallableWrapper/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore
3 changes: 3 additions & 0 deletions 3 src/Symfony/Component/CallableWrapper/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.