Skip to content

[Marshaller] Introduce component #4

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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"symfony/ldap": "self.version",
"symfony/lock": "self.version",
"symfony/mailer": "self.version",
"symfony/marshaller": "self.version",
"symfony/messenger": "self.version",
"symfony/mime": "self.version",
"symfony/monolog-bridge": "self.version",
Expand Down Expand Up @@ -180,7 +181,8 @@
"Symfony\\Component\\": "src/Symfony/Component/"
},
"files": [
"src/Symfony/Component/String/Resources/functions.php"
"src/Symfony/Component/String/Resources/functions.php",
"src/Symfony/Component/Marshaller/Resources/functions.php"
],
"classmap": [
"src/Symfony/Component/Cache/Traits/ValueWrapper.php"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

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

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Marshaller\Attribute\Marshallable;
use Symfony\Component\Marshaller\Context\ContextBuilderInterface;
use Symfony\Component\Marshaller\Exception\ExceptionInterface;
use Symfony\Component\Marshaller\MarshallableResolverInterface;
use Symfony\Component\VarExporter\ProxyHelper;

use function Symfony\Component\Marshaller\marshal_generate;

/**
* @author Mathias Arlaud <[email protected]>
*/
final class MarshallerCacheWarmer implements CacheWarmerInterface
{
/**
* @param iterable<ContextBuilderInterface> $contextBuilders
* @param list<string> $formats
*/
public function __construct(
private readonly MarshallableResolverInterface $marshallableResolver,
private readonly iterable $contextBuilders,
private readonly string $templateCacheDir,
private readonly string $lazyObjectCacheDir,
private readonly array $formats,
private readonly bool $nullableData,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}

public function warmUp(string $cacheDir): array
{
if (!file_exists($this->templateCacheDir)) {
mkdir($this->templateCacheDir, recursive: true);
}

if (!file_exists($this->lazyObjectCacheDir)) {
mkdir($this->lazyObjectCacheDir, recursive: true);
}

foreach ($this->marshallableResolver->resolve() as $class => $attribute) {
foreach ($this->formats as $format) {
$this->warmClassTemplate($class, $attribute, $format);
}

$this->warmClassLazyObject($class);
}

return [];
}

public function isOptional(): bool
{
return true;
}

/**
* @param class-string $class
*/
private function warmClassTemplate(string $class, Marshallable $attribute, string $format): void
{
if ($attribute->nullable ?? $this->nullableData) {
$class = '?'.$class;
}

if (file_exists($path = sprintf('%s%s%s.%s.php', $this->templateCacheDir, \DIRECTORY_SEPARATOR, md5($class), $format))) {
return;
}

try {
$context = ['cache_dir' => $this->templateCacheDir];

foreach ($this->contextBuilders as $contextBuilder) {
$context = $contextBuilder->buildMarshalContext($context, true);
}

file_put_contents($path, marshal_generate($class, $format, $context));
} catch (ExceptionInterface $e) {
$this->logger->debug('Cannot generate template for "{class}": {exception}', ['class' => $class, 'exception' => $e]);
}
}

/**
* @param class-string $class
*/
private function warmClassLazyObject(string $class): void
{
if (file_exists($path = sprintf('%s%s%s.php', $this->lazyObjectCacheDir, \DIRECTORY_SEPARATOR, md5($class)))) {
return;
}

file_put_contents($path, sprintf(
'class %s%s',
sprintf('%sGhost', preg_replace('/\\\\/', '', $class)),
ProxyHelper::generateLazyGhost(new \ReflectionClass($class)),
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ class UnusedTagsPass implements CompilerPassInterface
'kernel.reset',
'ldap',
'mailer.transport_factory',
'marshaller.context_builder',
'marshaller.hook.marshal',
'marshaller.hook.unmarshal',
'messenger.bus',
'messenger.message_handler',
'messenger.receiver',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use Symfony\Component\Lock\Lock;
use Symfony\Component\Lock\Store\SemaphoreStore;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Marshaller\Marshaller;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Notifier\Notifier;
use Symfony\Component\PropertyAccess\PropertyAccessor;
Expand Down Expand Up @@ -185,6 +186,7 @@ public function getConfigTreeBuilder(): TreeBuilder
$this->addHtmlSanitizerSection($rootNode, $enableIfStandalone);
$this->addWebhookSection($rootNode, $enableIfStandalone);
$this->addRemoteEventSection($rootNode, $enableIfStandalone);
$this->addMarshallerSection($rootNode, $enableIfStandalone);

return $treeBuilder;
}
Expand Down Expand Up @@ -2388,4 +2390,39 @@ private function addHtmlSanitizerSection(ArrayNodeDefinition $rootNode, callable
->end()
;
}

private function addMarshallerSection(ArrayNodeDefinition $rootNode, callable $enableIfStandalone): void
{
$rootNode
->children()
->arrayNode('marshaller')
->info('Marshaller configuration')
->{$enableIfStandalone('symfony/marshaller', Marshaller::class)}()
->fixXmlConfig('marshallable_path')
->children()
->arrayNode('marshallable_paths')
->info('Defines where the marshaller should look to find marshallable classes.')
->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end()
->prototype('scalar')->end()
->end()
->arrayNode('template_warm_up')
->addDefaultsIfNotSet()
->fixXmlConfig('format')
->children()
->arrayNode('formats')
->info('Defines the formats that will be handled.')
->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end()
->prototype('scalar')->end()
->end()
->booleanNode('nullable_data')
->info('Defines if nullable data should be handled by default.')
->defaultFalse()
->end()
->end()
->end()
->end()
->end()
->end()
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Doctrine\Common\Annotations\Reader;
use Http\Client\HttpAsyncClient;
use Http\Client\HttpClient;
use Symfony\Component\Marshaller\Context\ContextBuilderInterface;
use Symfony\Component\Marshaller\MarshallerInterface;
use phpDocumentor\Reflection\DocBlockFactoryInterface;
use phpDocumentor\Reflection\Types\ContextFactory;
use PhpParser\Parser;
Expand All @@ -37,8 +39,8 @@
use Symfony\Component\Cache\Adapter\ChainAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Symfony\Component\Cache\DependencyInjection\CachePoolPass;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller as CacheDefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface as CacheMarshallerInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Config\Definition\ConfigurationInterface;
Expand Down Expand Up @@ -597,6 +599,10 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerHtmlSanitizerConfiguration($config['html_sanitizer'], $container, $loader);
}

if ($this->readConfigEnabled('marshaller', $container, $config['marshaller'])) {
$this->registerMarshallerConfiguration($config['marshaller'], $container, $loader);
}

$this->addAnnotatedClassesToCompile([
'**\\Controller\\',
'**\\Entity\\',
Expand Down Expand Up @@ -652,7 +658,7 @@ public function load(array $configs, ContainerBuilder $container)
$container->registerForAutoconfiguration(ResetInterface::class)
->addTag('kernel.reset', ['method' => 'reset']);

if (!interface_exists(MarshallerInterface::class)) {
if (!interface_exists(CacheMarshallerInterface::class)) {
$container->registerForAutoconfiguration(ResettableInterface::class)
->addTag('kernel.reset', ['method' => 'reset']);
}
Expand Down Expand Up @@ -689,6 +695,8 @@ public function load(array $configs, ContainerBuilder $container)
->addTag('mime.mime_type_guesser');
$container->registerForAutoconfiguration(LoggerAwareInterface::class)
->addMethodCall('setLogger', [new Reference('logger')]);
$container->registerForAutoconfiguration(ContextBuilderInterface::class)
->addTag('marshaller.context_builder');

$container->registerAttributeForAutoconfiguration(AsEventListener::class, static function (ChildDefinition $definition, AsEventListener $attribute, \ReflectionClass|\ReflectionMethod $reflector) {
$tagAttributes = get_object_vars($attribute);
Expand Down Expand Up @@ -2265,7 +2273,7 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder

private function registerCacheConfiguration(array $config, ContainerBuilder $container): void
{
if (!class_exists(DefaultMarshaller::class)) {
if (!class_exists(CacheDefaultMarshaller::class)) {
$container->removeDefinition('cache.default_marshaller');
}

Expand Down Expand Up @@ -2992,6 +3000,19 @@ private function registerHtmlSanitizerConfiguration(array $config, ContainerBuil
}
}

private function registerMarshallerConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader): void
{
if (!interface_exists(MarshallerInterface::class)) {
throw new LogicException('Marshaller support cannot be enabled as the Marshaller component is not installed. Try running "composer require symfony/marshaller');
}

$container->setParameter('marshaller.marshallable_paths', $config['marshallable_paths']);
$container->setParameter('marshaller.template_warm_up.formats', $config['template_warm_up']['formats']);
$container->setParameter('marshaller.template_warm_up.nullable_data', $config['template_warm_up']['nullable_data']);

$loader->load('marshaller.php');
}

private function resolveTrustedHeaders(array $headers): int
{
$trustedHeaders = 0;
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
use Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass;
use Symfony\Component\HttpKernel\DependencyInjection\ResettableServicePass;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Marshaller\DependencyInjection\MarshallerPass;
use Symfony\Component\Messenger\DependencyInjection\MessengerPass;
use Symfony\Component\Mime\DependencyInjection\AddMimeTypeGuesserPass;
use Symfony\Component\PropertyInfo\DependencyInjection\PropertyInfoPass;
Expand Down Expand Up @@ -173,6 +174,7 @@ public function build(ContainerBuilder $container)
$container->addCompilerPass(new RegisterReverseContainerPass(true));
$container->addCompilerPass(new RegisterReverseContainerPass(false), PassConfig::TYPE_AFTER_REMOVING);
$container->addCompilerPass(new RemoveUnusedSessionMarshallingHandlerPass());
$this->addCompilerPassIfExists($container, MarshallerPass::class);

if ($container->getParameter('kernel.debug')) {
$container->addCompilerPass(new EnableLoggerDebugModePass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -33);
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@
->private()
->tag('cache.pool')

->set('cache.marshaller')
->parent('cache.system')
->private()
->tag('cache.pool')

->set('cache.adapter.system', AdapterInterface::class)
->abstract()
->factory([AbstractAdapter::class, 'createSystemCache'])
Expand Down
Loading
Loading