8000 [2.2] [FrameworkBundle] [Serializer] Loads the Serializer component as a service in the Framework Bundle by loalf · Pull Request #5347 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[2.2] [FrameworkBundle] [Serializer] Loads the Serializer component as a service in the Framework Bundle #5347

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 26 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ca250b0
Adding the Serializer service to the Framework Bundle
humandb Aug 25, 2012
0b51471
Adding the Compiler Pass to add encoders and normalizers as tagged se…
humandb Aug 25, 2012
7b791fe
Fixing some issues with SerializerPass
humandb Aug 25, 2012
fb1685c
Now it sorts the encoders and normalizers depending on its priority
humandb Aug 25, 2012
881e9a6
Updated serializer.xml
humandb Aug 25, 2012
0278df8
Getting rid of the priorities
humandb Aug 26, 2012
e579aac
Added priority to the services according to the Symfony standards
humandb Sep 3, 2012
91812e2
Iterating through all the tags on the service
humandb Sep 3, 2012
4d6fdc0
Simplyfing the way to flatten the array acording to @stof comments
humandb Sep 3, 2012
5e24f74
Merge branch 'master' into serializer_in_dic
humandb Oct 14, 2012
d164806
Using camel case and typehinting the container
humandb Oct 18, 2012
b343488
Remove priority in encoders and normalizer as this is irrelevant
humandb Oct 18, 2012
4ef485a
Merge branch 'master' of git://github.com/symfony/symfony into serial…
humandb Oct 18, 2012
75d7ed9
Using canBeDisabled()
humandb Oct 18, 2012
8ccb530
Modifying CHANGELOG to reflect the new feature
humandb Oct 18, 2012
299c03e
Missing space after 'if'
humandb Oct 20, 2012
c6253ce
Adding the Serializer service to the Framework Bundle
humandb Aug 25, 2012
5fd4e90
Merge branch 'serializer_in_dic' of github.com:loalf/symfony into ser…
humandb Oct 29, 2012
1ddcba4
Merge branch 'serializer_in_dic' of github.com:loalf/symfony into ser…
humandb Oct 29, 2012
b46d4e9
Merge branch 'master' of git://github.com/symfony/symfony into serial…
humandb Nov 4, 2012
377aa31
Merge branch 'master' into serializer_in_dic
humandb Dec 16, 2012
731a05e
SerializerPass throws an exception if no encoders or normalizers are …
humandb Dec 16, 2012
627b69c
Adding functional testing for the SerializerPass class
humandb Dec 16, 2012
122ac5c
Merge branch 'serializer_in_dic' of github.com:loalf/symfony into ser…
humandb Dec 16, 2012
2fbd210
Merge branch 'master' into serializer_in_dic
humandb Jan 19, 2013
8cb0564
Fixed minor issues
humandb Jan 19, 2013
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ CHANGELOG
* replaced Symfony\Bundle\FrameworkBundle\Controller\TraceableControllerResolver by Symfony\Component\HttpKernel\Controller\TraceableControllerResolver
* replaced Symfony\Component\HttpKernel\Debug\ContainerAwareTraceableEventDispatcher by Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher
* added Client::enableProfiler()
* added posibility to load the serializer component in the service container
* A new parameter has been added to the DIC: `router.request_context.base_url`
You can customize it for your functional tests or for generating urls with
the right base url when your are in the cli context.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?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\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;

/**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

empty line is needed here

* Adds all services with the tags "serializer.encoder" and "serializer.normalizer" as
* encoders and normalizers to the Serializer service.
*
* @author Javier Lopez <f12loalf@gmail.com>
*/
class SerializerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('serializer')) {
return;
}

// Looks for all the services tagged "serializer.normalizer" and adds them to the Serializer service
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you execute the whole same code twice maybe factorize it inside a loop or a method ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I´ve reduced the length of this code so I think there is no need to refactor it anymore.

$normalizers = $this->findAndSortTaggedServices('serializer.normalizer', $container);
$container->getDefinition('serializer')->replaceArgument(0, $normalizers);

// Looks for all the services tagged "serializer.encoders" and adds them to the Serializer service
$encoders = $this->findAndSortTaggedServices('serializer.encoder', $container);
$container->getDefinition('serializer')->replaceArgument(1, $encoders);
}

private function findAndSortTaggedServices($tagName, ContainerBuilder $container)
{
$services = $container->findTaggedServiceIds($tagName);

if (empty($services)) {
throw new \RuntimeException(sprintf('You must tag at least one service as "%s" to use the Serializer service', $tagName));
}

$sortedServices = array();
foreach ($services as $serviceId => $tags) {
foreach ($tags as $tag) {
$priority = isset($tag['priority']) ? $tag['priority'] : 0;
$sortedServices[$priority][] = new Reference($serviceId);
}
}

krsort($sortedServices);

// Flatten the array
return call_user_func_array('array_merge', $sortedServices);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public function getConfigTreeBuilder()
$this->addTranslatorSection($rootNode);
$this->addValidationSection($rootNode);
$this->addAnnotationsSection($rootNode);
$this->addSerializerSection($rootNode);

return $treeBuilder;
}
Expand Down Expand Up @@ -393,4 +394,17 @@ private function addAnnotationsSection(ArrayNodeDefinition $rootNode)
->end()
;
}

private function addSerializerSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('serializer')
->info('serializer configuration')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Serialized with a capital letter.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

->canBeDisabled()
->end()
->end()
;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This blank line should be removed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't see a duplicate blank line cause there should be one blank line between "{" and "private ... ", shouldn't it?

}
< 9E88 button type="button" class="btn-link color-fg-muted no-underline js-expand-full directional-expander tooltipped tooltipped-se" aria-label="Expand all" data-url="/symfony/symfony/blob_expand/040cd6719e9db654a229931a412707643ba1ec48?anchor=diff-e4f52d5033296421d02e360c8355aa1931bdfb0c12579f4815ea02b724322c0c&context=pull_request&diff=unified&direction=full&mode=100644&path=src%2FSymfony%2FBundle%2FFrameworkBundle%2FDependencyInjection%2FFrameworkExtension.php&pull_request_id=2162181" >
17 changes: 17 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerTranslatorConfiguration($config['translator'], $container);
}

if (isset($config['serializer'])) {
$this->registerSerializerConfiguration($config['serializer'], $loader);
}

$this->registerAnnotationsConfiguration($config['annotations'], $container, $loader);

$this->addClassesToCompile(array(
Expand Down Expand Up @@ -661,6 +665,19 @@ private function registerAnnotationsConfiguration(array $config, ContainerBuilde
}
}

/**
* Loads the Serializer configuration.
*
* @param array $config A Serializer configuration array
* @param XmlFileLoader $loader An XmlFileLoader instance
*/
private function registerSerializerConfiguration(array $config, XmlFileLoader $loader)
{
if ($config['enabled']) {
$loader->load('serializer.xml');
}
}

/**
* Returns the base path for the XSD files.
*
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 @@ -25,6 +25,7 @@
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CompilerDebugDumpPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslationExtractorPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslationDumperPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\HttpRenderingStrategyPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
Expand Down Expand Up @@ -66,6 +67,7 @@ public function build(ContainerBuilder $container)
$container->addCompilerPass(new AddCacheClearerPass());
$container->addCompilerPass(new TranslationExtractorPass());
$container->addCompilerPass(new TranslationDumperPass());
$container->addCompilerPass(new SerializerPass());
$container->addCompilerPass(new HttpRenderingStrategyPass(), PassConfig::TYPE_AFTER_REMOVING);

if ($container->getParameter('kernel.debug')) {
Expand Down
25 changes: 25 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/serializer.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
<parameter key="serializer.class">Symfony\Component\Serializer\Serializer</parameter>
<parameter key="serializer.encoder.xml.class">Symfony\Component\Serializer\Encoder\XmlEncoder</parameter>
<parameter key="serializer.encoder.json.class">Symfony\Component\Serializer\Encoder\JsonEncoder</parameter>

<services>
<service id="serializer" class="%serializer.class%" >
<argument type="collection" />
<argument type="collection" />
</service>
<!-- Encoders -->
<service id="serializer.encoder.xml" class="%serializer.encoder.xml.class%" public="false" >
<tag name="serializer.encoder" />
</service>
<service id="serializer.encoder.json" class="%serializer.encoder.json.class%" public="false" >
<tag name="serializer.encoder" />
</service>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registering this one should be optional. The GetSetMethodNormalizer is broken (by design) as soon as you have a cyclic object graph (you have an infinite loop when calling getters), so forcing to register it is a bad idea (expecially as many people tend to use bidirectional relations in their entities apparently)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for this service, you should add the tag conditionally in the DI extension according to a configuration, to allow disabling it.

and it should have a negative priority rather that a high priority IMO, so that custom normalizers registered with the default priority can be checked first (the GetSetNormalizer will accept any input)

</services>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?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\Tests\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass;

/**
* Tests for the SerializerPass class
*
* @author Javier Lopez <f12loalf@gmail.com>
*/
class SerializerPassTest extends \PHPUnit_Framework_TestCase
{

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those blank lines should be removed

public function testThrowExceptionWhenNoNormalizers()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');

$container->expects($this->once())
->method('hasDefinition')
->with('serializer')
->will($this->returnValue(true));

$container->expects($this->once())
->method('findTaggedServiceIds')
->with('serializer.normalizer')
->will($this->returnValue(array()));

$this->setExpectedException('RuntimeException');

$serializerPass = new SerializerPass();
$serializerPass->process($container);
}

public function testThrowExceptionWhenNoEncoders()
{
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');

$container->expects($this->once())
->method('hasDefinition')
->with('serializer')
->will($this->returnValue(true));

$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(
array('n' => array('serializer.normalizer')),
array()
));

$container->expects($this->once())
->method('getDefinition')
->will($this->returnValue($definition));

$this->setExpectedException('RuntimeException');

$serializerPass = new SerializerPass();
$serializerPass->process($container);
}

public function testServicesAreOrderedAccordingToPriority()
{
$services = array(
'n3' => array('tag' => array()),
'n1' => array('tag' => array('priority' => 200)),
'n2' => array('tag' => array('priority' => 100))
);

$expected = array(
new Reference('n1'),
new Reference('n2'),
new Reference('n3')
);

$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');

$container->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));

$serializerPass = new SerializerPass();

$method = new \ReflectionMethod(
'Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\SerializerPass',
'findAndSortTaggedServices'
);
$method->setAccessible(TRUE);

$actual = $method->invoke($serializerPass, 'tag', $container);

$this->assertEquals($expected, $actual);
}
}
0