diff --git a/UPDATE.ja.md b/UPDATE.ja.md
index fa54373f85..3c4adc6f22 100644
--- a/UPDATE.ja.md
+++ b/UPDATE.ja.md
@@ -5,11 +5,34 @@
このドキュメントでは、フレームワークの "パブリックな" APIを使っている場合に必要な変更点についてのみ説明しています。
フレームワークのコアコードを "ハック" している場合は、変更履歴を注意深く追跡する必要があるでしょう。
+PR11 to PR12
+------------
+
+* HttpFoundation\Cookie::getExpire() は getExpiresTime() に名前が変更されました。
+
+* XMLのコンフィギュレーションの記述方法が変更されました。属性が1つしかないタグは、すべてタグのコンテンツとして記述するように変更されました。
+
+ 変更前:
+
+
+
+
+
+ 変更後:
+
+ MyBundle
+ twig
+ twig.extension.debug
+
+* SwitchUserListenerが有効な場合に、すべてのユーザーが任意のアカウントになりすませる致命的な脆弱性を修正しました。SwitchUserListenerを利用しない設定にしている場合は影響はありません。
+
PR10 から PR11
--------------
* エクステンションのコンフィギュレーションクラスには、\ `Symfony\Component\Config\Definition\ConfigurationInterface`\ インターフェイスを実装する必要があります。この部分の後方互換性は維持されていますが、今後の開発のために、エクステンションにこのインターフェイスを実装しておいてください。
+* Monologのオプション "fingerscrossed" は "fingers_crossed" に名前が変更されました。
+
PR9 から PR10
-------------
diff --git a/UPDATE.md b/UPDATE.md
index a4c65143aa..916c669dfd 100644
--- a/UPDATE.md
+++ b/UPDATE.md
@@ -6,19 +6,67 @@ one. It only discusses changes that need to be done when using the "public"
API of the framework. If you "hack" the core, you should probably follow the
timeline closely anyway.
+PR12 to beta1
+-------------
+
+* The `trans` tag does not accept a message as an argument anymore:
+
+ {% trans "foo" %}
+ {% trans foo %}
+
+ Use the long version the tags or the filter instead:
+
+ {% trans %}foo{% endtrans %}
+ {{ foo|trans }}
+
+ This has been done to clarify the usage of the tag and filter and also to
+ make it clearer when the automatic output escaping rules are applied (see
+ the doc for more information).
+
+* Some methods in the DependencyInjection component's ContainerBuilder and
+ Definition classes have been renamed to be more specific and consistent:
+
+ Before:
+
+ $container->remove('my_definition');
+ $definition->setArgument(0, 'foo');
+
+ After:
+
+ $container->removeDefinition('my_definition');
+ $definition->replaceArgument(0, 'foo');
+
+* In the rememberme configuration, the token_provider key now expects a real
+ service id instead of only a suffix.
+
PR11 to PR12
------------
-* AsseticBundle's XML `bundle` node has been normalized to match other similar
- nodes
+* HttpFoundation\Cookie::getExpire() was renamed to getExpiresTime()
+
+* XML configurations have been normalized. All tags with only one attribute
+ have been converted to tag content:
Before:
+
+
After:
MyBundle
+ twig
+ twig.extension.debug
+
+* Fixes a critical security issue which allowed all users to switch to
+ arbitrary accounts when the SwitchUserListener was activated. Configurations
+ which do not use the SwitchUserListener are not affected.
+
+* The Dependency Injection Container now strongly validates the references of
+ all your services at the end of its compilation process. If you have invalid
+ references this will result in a compile-time exception instead of a run-time
+ exception (the previous behavior).
PR10 to PR11
------------
diff --git a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php
index 8b6dfa9e60..7cc5cc6b78 100644
--- a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php
+++ b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php
@@ -53,7 +53,7 @@ class TranslationExtension extends \Twig_Extension
public function getTokenParsers()
{
return array(
- // {% trans "Symfony is great!" %}
+ // {% trans %}Symfony is great!{% endtrans %}
new TransTokenParser(),
// {% transchoice count %}
@@ -70,7 +70,7 @@ class TranslationExtension extends \Twig_Extension
public function transchoice($message, $count, array $arguments = array(), $domain = "messages")
{
- return $this->translator->transChoice($message, $count, $arguments, $domain);
+ return $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain);
}
/**
diff --git a/src/Symfony/Bridge/Twig/Node/FormThemeNode.php b/src/Symfony/Bridge/Twig/Node/FormThemeNode.php
index 337114ea59..c4ad0205c0 100644
--- a/src/Symfony/Bridge/Twig/Node/FormThemeNode.php
+++ b/src/Symfony/Bridge/Twig/Node/FormThemeNode.php
@@ -12,7 +12,7 @@
namespace Symfony\Bridge\Twig\Node;
/**
- *
+ *
*
* @author Fabien Potencier
*/
diff --git a/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php
index 51e516a2b4..83da6e37b1 100644
--- a/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php
+++ b/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php
@@ -14,7 +14,7 @@ namespace Symfony\Bridge\Twig\TokenParser;
use Symfony\Bridge\Twig\Node\FormThemeNode;
/**
- *
+ *
*
* @author Fabien Potencier
*/
diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php
index 2e14c98399..351e660ccd 100644
--- a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php
+++ b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php
@@ -64,7 +64,7 @@ class TransChoiceTokenParser extends TransTokenParser
}
if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) {
- throw new \Twig_Error_Syntax(sprintf('A message must be a simple text (line %s)', $lineno), -1);
+ throw new \Twig_Error_Syntax('A message must be a simple text.');
}
$stream->expect(\Twig_Token::BLOCK_END_TYPE);
diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php
index 85a74845bc..c3450f67ab 100644
--- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php
+++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php
@@ -14,7 +14,7 @@ namespace Symfony\Bridge\Twig\TokenParser;
use Symfony\Bridge\Twig\Node\TransNode;
/**
- *
+ *
*
* @author Fabien Potencier
*/
@@ -36,35 +36,27 @@ class TransTokenParser extends \Twig_TokenParser
$vars = new \Twig_Node_Expression_Array(array(), $lineno);
$domain = new \Twig_Node_Expression_Constant('messages', $lineno);
if (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
- if (!$stream->test('from') && !$stream->test('with')) {
- // {% trans "message" %}
- // {% trans message %}
- $body = $this->parser->getExpressionParser()->parseExpression();
- }
-
if ($stream->test('with')) {
- // {% trans "message" with vars %}
+ // {% trans with vars %}
$stream->next();
$vars = $this->parser->getExpressionParser()->parseExpression();
}
if ($stream->test('from')) {
- // {% trans "message" from "messages" %}
+ // {% trans from "messages" %}
$stream->next();
$domain = $this->parser->getExpressionParser()->parseExpression();
} elseif (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
- throw new \Twig_Error_Syntax(sprintf('Unexpected token. Twig was looking for the "from" keyword line %s)', $lineno), -1);
+ throw new \Twig_Error_Syntax('Unexpected token. Twig was looking for the "with" or "from" keyword.');
}
}
- if (null === $body) {
- // {% trans %}message{% endtrans %}
- $stream->expect(\Twig_Token::BLOCK_END_TYPE);
- $body = $this->parser->subparse(array($this, 'decideTransFork'), true);
- }
+ // {% trans %}message{% endtrans %}
+ $stream->expect(\Twig_Token::BLOCK_END_TYPE);
+ $body = $this->parser->subparse(array($this, 'decideTransFork'), true);
if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) {
- throw new \Twig_Error_Syntax('A message must be a simple text', -1);
+ throw new \Twig_Error_Syntax('A message must be a simple text');
}
$stream->expect(\Twig_Token::BLOCK_END_TYPE);
diff --git a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php
index 6adf66f2a2..35e7e8dc67 100644
--- a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php
+++ b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetManagerCacheWarmer.php
@@ -11,21 +11,22 @@
namespace Symfony\Bundle\AsseticBundle\CacheWarmer;
-use Assetic\Factory\LazyAssetManager;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class AssetManagerCacheWarmer extends CacheWarmer
{
- protected $am;
+ private $container;
- public function __construct(LazyAssetManager $am)
+ public function __construct(ContainerInterface $container)
{
- $this->am = $am;
+ $this->container = $container;
}
public function warmUp($cacheDir)
{
- $this->am->load();
+ $am = $this->container->get('assetic.asset_manager');
+ $am->load();
}
public function isOptional()
diff --git a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php
index 034a45a6e0..298ffd235d 100644
--- a/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php
+++ b/src/Symfony/Bundle/AsseticBundle/CacheWarmer/AssetWriterCacheWarmer.php
@@ -11,24 +11,25 @@
namespace Symfony\Bundle\AsseticBundle\CacheWarmer;
-use Assetic\AssetManager;
use Assetic\AssetWriter;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class AssetWriterCacheWarmer extends CacheWarmer
{
- protected $am;
- protected $writer;
+ private $container;
+ private $writer;
- public function __construct(AssetManager $am, AssetWriter $writer)
+ public function __construct(ContainerInterface $container, AssetWriter $writer)
{
- $this->am = $am;
+ $this->container = $container;
$this->writer = $writer;
}
public function warmUp($cacheDir)
{
- $this->writer->writeManagerAssets($this->am);
+ $am = $this->container->get('assetic.asset_manager');
+ $this->writer->writeManagerAssets($am);
}
public function isOptional()
diff --git a/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php b/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php
index b34a845241..6ffd6fb95e 100644
--- a/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php
+++ b/src/Symfony/Bundle/AsseticBundle/Controller/AsseticController.php
@@ -12,6 +12,7 @@
namespace Symfony\Bundle\AsseticBundle\Controller;
use Assetic\Asset\AssetCache;
+use Assetic\Asset\AssetInterface;
use Assetic\Factory\LazyAssetManager;
use Assetic\Cache\CacheInterface;
use Symfony\Component\HttpFoundation\Request;
@@ -36,13 +37,17 @@ class AsseticController
$this->cache = $cache;
}
- public function render($name)
+ public function render($name, $pos = null)
{
if (!$this->am->has($name)) {
- throw new NotFoundHttpException('Asset Not Found');
+ throw new NotFoundHttpException(sprintf('The "%s" asset could not be found.', $name));
+ }
+
+ $asset = $this->am->get($name);
+ if (null !== $pos && !$asset = $this->findAssetLeaf($asset, $pos)) {
+ throw new NotFoundHttpException(sprintf('The "%s" asset does not include a leaf at position %d.', $name, $pos));
}
- $asset = $this->getAsset($name);
$response = $this->createResponse();
// last-modified
@@ -63,7 +68,7 @@ class AsseticController
return $response;
}
- $response->setContent($asset->dump());
+ $response->setContent($this->cachifyAsset($asset)->dump());
return $response;
}
@@ -73,8 +78,17 @@ class AsseticController
return new Response();
}
- protected function getAsset($name)
+ protected function cachifyAsset(AssetInterface $asset)
{
- return new AssetCache($this->am->get($name), $this->cache);
+ return new AssetCache($asset, $this->cache);
+ }
+
+ private function findAssetLeaf(AssetInterface $asset, $pos)
+ {
+ $leaves = array_values(iterator_to_array($asset));
+
+ if (isset($leaves[$pos])) {
+ return $leaves[$pos];
+ }
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php
index 0b4e5faac1..1284628dde 100644
--- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php
+++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/AsseticExtension.php
@@ -74,14 +74,12 @@ class AsseticExtension extends Extension
// choose dynamic or static
if ($parameterBag->resolveValue($parameterBag->get('assetic.use_controller'))) {
$loader->load('controller.xml');
- $container->setParameter('assetic.twig_extension.class', '%assetic.twig_extension.dynamic.class%');
$container->getDefinition('assetic.helper.dynamic')->addTag('templating.helper', array('alias' => 'assetic'));
- $container->remove('assetic.helper.static');
+ $container->removeDefinition('assetic.helper.static');
} else {
$loader->load('asset_writer.xml');
- $container->setParameter('assetic.twig_extension.class', '%assetic.twig_extension.static.class%');
$container->getDefinition('assetic.helper.static')->addTag('templating.helper', array('alias' => 'assetic'));
- $container->remove('assetic.helper.dynamic');
+ $container->removeDefinition('assetic.helper.dynamic');
}
// register config resources
diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php
index 22454b83af..154f2ce553 100644
--- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php
+++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/AssetManagerPass.php
@@ -48,7 +48,7 @@ class AssetManagerPass implements CompilerPassInterface
}
}
}
- $am->setArgument(1, $loaders);
+ $am->replaceArgument(1, $loaders);
// add resources
foreach ($container->findTaggedServiceIds('assetic.formula_resource') as $id => $attributes) {
diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php
index fd14b0b400..251fb758f8 100644
--- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php
+++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/CheckClosureFilterPass.php
@@ -25,9 +25,9 @@ class CheckClosureFilterPass implements CompilerPassInterface
{
if ($container->hasDefinition('assetic.filter.closure.jar') &&
$container->getParameterBag()->resolveValue($container->getParameter('assetic.filter.closure.jar'))) {
- $container->remove('assetic.filter.closure.api');
+ $container->removeDefinition('assetic.filter.closure.api');
} elseif ($container->hasDefinition('assetic.filter.closure.api')) {
- $container->remove('assetic.filter.closure.jar');
+ $container->removeDefinition('assetic.filter.closure.jar');
}
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php
index b9c258774b..af04a6e214 100644
--- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php
+++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/FilterManagerPass.php
@@ -39,6 +39,6 @@ class FilterManagerPass implements CompilerPassInterface
$container
->getDefinition('assetic.filter_manager')
- ->setArgument(1, $mapping);
+ ->replaceArgument(1, $mapping);
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php
index 852b488551..b0281261a7 100644
--- a/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php
+++ b/src/Symfony/Bundle/AsseticBundle/DependencyInjection/Compiler/TemplatingPass.php
@@ -31,13 +31,13 @@ class TemplatingPass implements CompilerPassInterface
if (!in_array('twig', $engines)) {
foreach ($container->findTaggedServiceIds('assetic.templating.twig') as $id => $attr) {
- $container->remove($id);
+ $container->removeDefinition($id);
}
}
if (!in_array('php', $engines)) {
foreach ($container->findTaggedServiceIds('assetic.templating.php') as $id => $attr) {
- $container->remove($id);
+ $container->removeDefinition($id);
}
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/Factory/Worker/UseControllerWorker.php b/src/Symfony/Bundle/AsseticBundle/Factory/Worker/UseControllerWorker.php
new file mode 100644
index 0000000000..527c81d706
--- /dev/null
+++ b/src/Symfony/Bundle/AsseticBundle/Factory/Worker/UseControllerWorker.php
@@ -0,0 +1,33 @@
+
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\AsseticBundle\Factory\Worker;
+
+use Assetic\Asset\AssetInterface;
+use Assetic\Factory\Worker\WorkerInterface;
+
+/**
+ * Prepends a fake front controller so the asset knows where it is-ish.
+ *
+ * @author Kris Wallsmith
+ */
+class UseControllerWorker implements WorkerInterface
+{
+ public function process(AssetInterface $asset)
+ {
+ $targetUrl = $asset->getTargetUrl();
+ if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, '_controller/')) {
+ $asset->setTargetUrl('_controller/'.$targetUrl);
+ }
+
+ return $asset;
+ }
+}
diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml
index 855caa06ec..c4a9515396 100644
--- a/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml
+++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/asset_writer.xml
@@ -12,7 +12,7 @@
-
+
diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml
index 2ef38f2616..23d67202d6 100644
--- a/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml
+++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/assetic.xml
@@ -42,7 +42,7 @@
-
+
diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml
index 65a65732c2..1da0a603e5 100644
--- a/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml
+++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/controller.xml
@@ -8,6 +8,7 @@
Symfony\Bundle\AsseticBundle\Controller\AsseticController
Symfony\Bundle\AsseticBundle\Routing\AsseticLoader
Assetic\Cache\FilesystemCache
+ Symfony\Bundle\AsseticBundle\Factory\Worker\UseControllerWorker
@@ -23,5 +24,8 @@
%assetic.cache_dir%/assets
+
+
+
diff --git a/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml b/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml
index 5e3d070eb4..a2340dc316 100644
--- a/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml
+++ b/src/Symfony/Bundle/AsseticBundle/Resources/config/templating_twig.xml
@@ -5,8 +5,7 @@
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
- Symfony\Bundle\AsseticBundle\Twig\DynamicExtension
- Symfony\Bundle\AsseticBundle\Twig\StaticExtension
+ Symfony\Bundle\AsseticBundle\Twig\AsseticExtension
Assetic\Extension\Twig\TwigFormulaLoader
@@ -16,6 +15,7 @@
%assetic.debug%
+ %assetic.use_controller%
diff --git a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php
index 763ef31be4..9525fc8ff2 100644
--- a/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php
+++ b/src/Symfony/Bundle/AsseticBundle/Routing/AsseticLoader.php
@@ -11,6 +11,7 @@
namespace Symfony\Bundle\AsseticBundle\Routing;
+use Assetic\Asset\AssetInterface;
use Assetic\Factory\LazyAssetManager;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Config\Resource\FileResource;
@@ -62,22 +63,56 @@ class AsseticLoader extends Loader
// routes
foreach ($this->am->getNames() as $name) {
$asset = $this->am->get($name);
+ $formula = $this->am->getFormula($name);
- $defaults = array(
- '_controller' => 'assetic.controller:render',
- 'name' => $name,
- );
+ $this->loadRouteForAsset($routes, $asset, $name);
- if ($extension = pathinfo($asset->getTargetUrl(), PATHINFO_EXTENSION)) {
- $defaults['_format'] = $extension;
+ // add a route for each "leaf" in debug mode
+ if (isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug()) {
+ $i = 0;
+ foreach ($asset as $leaf) {
+ $this->loadRouteForAsset($routes, $leaf, $name, $i++);
+ }
}
-
- $routes->add('assetic_'.$name, new Route($asset->getTargetUrl(), $defaults));
}
return $routes;
}
+ /**
+ * Loads a route to serve an supplied asset.
+ *
+ * The fake front controller that {@link UseControllerWorker} adds to the
+ * target URL will be removed before set as a route pattern.
+ *
+ * @param RouteCollection $routes The route collection
+ * @param AssetInterface $asset The asset
+ * @param string $name The name to use
+ * @param integer $pos The leaf index
+ */
+ private function loadRouteForAsset(RouteCollection $routes, AssetInterface $asset, $name, $pos = null)
+ {
+ $defaults = array(
+ '_controller' => 'assetic.controller:render',
+ 'name' => $name,
+ 'pos' => $pos,
+ );
+
+ // remove the fake front controller
+ $pattern = str_replace('_controller/', '', $asset->getTargetUrl());
+
+ if ($format = pathinfo($pattern, PATHINFO_EXTENSION)) {
+ $defaults['_format'] = $format;
+ }
+
+ $route = '_assetic_'.$name;
+ if (null !== $pos) {
+ $route .= '_'.$pos;
+ }
+
+ $routes->add($route, new Route($pattern, $defaults));
+ }
+
public function supports($resource, $type = null)
{
return 'assetic' == $type;
diff --git a/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php b/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php
index e1ad188abe..a3dad04501 100644
--- a/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php
+++ b/src/Symfony/Bundle/AsseticBundle/Templating/DynamicAsseticHelper.php
@@ -40,6 +40,6 @@ class DynamicAsseticHelper extends AsseticHelper
protected function getAssetUrl(AssetInterface $asset, $options = array())
{
- return $this->routerHelper->generate('assetic_'.$options['name']);
+ return $this->routerHelper->generate('_assetic_'.$options['name']);
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php
index 65b14bff26..02b959890c 100644
--- a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php
+++ b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetManagerCacheWarmerTest.php
@@ -24,13 +24,28 @@ class AssetManagerCacheWarmerTest extends \PHPUnit_Framework_TestCase
public function testWarmUp()
{
- $am = $this->getMockBuilder('Assetic\\Factory\\LazyAssetManager')
+ $am = $this
+ ->getMockBuilder('Assetic\\Factory\\LazyAssetManager')
->disableOriginalConstructor()
- ->getMock();
+ ->getMock()
+ ;
$am->expects($this->once())->method('load');
+
+ $container = $this
+ ->getMockBuilder('Symfony\\Component\\DependencyInjection\\Container')
+ ->setConstructorArgs(array())
+ ->getMock()
+ ;
+
+ $container
+ ->expects($this->once())
+ ->method('get')
+ ->with('assetic.asset_manager')
+ ->will($this->returnValue($am))
+ ;
- $warmer = new AssetManagerCacheWarmer($am);
+ $warmer = new AssetManagerCacheWarmer($container);
$warmer->warmUp('/path/to/cache');
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php
index 35e67cd129..d8b78c0e6f 100644
--- a/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php
+++ b/src/Symfony/Bundle/AsseticBundle/Tests/CacheWarmer/AssetWriterCacheWarmerTest.php
@@ -25,15 +25,33 @@ class AssetWriterCacheWarmerTest extends \PHPUnit_Framework_TestCase
public function testWarmUp()
{
$am = $this->getMock('Assetic\\AssetManager');
- $writer = $this->getMockBuilder('Assetic\\AssetWriter')
+
+ $writer = $this
+ ->getMockBuilder('Assetic\\AssetWriter')
->disableOriginalConstructor()
- ->getMock();
+ ->getMock()
+ ;
- $writer->expects($this->once())
+ $writer
+ ->expects($this->once())
->method('writeManagerAssets')
- ->with($am);
+ ->with($am)
+ ;
+
+ $container = $this
+ ->getMockBuilder('Symfony\\Component\\DependencyInjection\\Container')
+ ->setConstructorArgs(array())
+ ->getMock()
+ ;
+
+ $container
+ ->expects($this->once())
+ ->method('get')
+ ->with('assetic.asset_manager')
+ ->will($this->returnValue($am))
+ ;
- $warmer = new AssetWriterCacheWarmer($am, $writer);
+ $warmer = new AssetWriterCacheWarmer($container, $writer);
$warmer->warmUp('/path/to/cache');
}
}
diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php
index 05f1b0ef29..e73793b863 100644
--- a/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php
+++ b/src/Symfony/Bundle/AsseticBundle/Tests/DependencyInjection/AsseticExtensionTest.php
@@ -46,9 +46,7 @@ class AsseticExtensionTest extends \PHPUnit_Framework_TestCase
$this->markTestSkipped('Assetic is not available.');
}
- $this->kernel = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Kernel')
- ->disableOriginalConstructor()
- ->getMock();
+ $this->kernel = $this->getMock('Symfony\\Component\\HttpKernel\\KernelInterface');
$this->container = new ContainerBuilder();
$this->container->addScope(new Scope('request'));
@@ -61,6 +59,7 @@ class AsseticExtensionTest extends \PHPUnit_Framework_TestCase
$this->container->setParameter('kernel.cache_dir', __DIR__);
$this->container->setParameter('kernel.debug', false);
$this->container->setParameter('kernel.root_dir', __DIR__);
+ $this->container->set('kernel', $this->kernel);
}
/**
diff --git a/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php b/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php
index 76a6c600a0..3c9ba424ff 100644
--- a/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php
+++ b/src/Symfony/Bundle/AsseticBundle/Tests/FunctionalTest.php
@@ -44,7 +44,7 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase
}
/**
- * @dataProvider provideDebugAndAssetCount
+ * @dataProvider provideAmDebugAndAssetCount
*/
public function testKernel($debug, $count)
{
@@ -55,7 +55,7 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase
}
/**
- * @dataProvider provideDebugAndAssetCount
+ * @dataProvider provideRouterDebugAndAssetCount
*/
public function testRoutes($debug, $count)
{
@@ -64,7 +64,7 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase
$matches = 0;
foreach (array_keys($kernel->getContainer()->get('router')->getRouteCollection()->all()) as $name) {
- if (0 === strpos($name, 'assetic_')) {
+ if (0 === strpos($name, '_assetic_')) {
++$matches;
}
}
@@ -102,11 +102,18 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(2, count($crawler->filter('script[src$=".js"]')));
}
- public function provideDebugAndAssetCount()
+ public function provideAmDebugAndAssetCount()
{
- // totals include assets defined in both php and twig templates
return array(
- array(true, 6),
+ array(true, 3),
+ array(false, 3),
+ );
+ }
+
+ public function provideRouterDebugAndAssetCount()
+ {
+ return array(
+ array(true, 9),
array(false, 3),
);
}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php
new file mode 100644
index 0000000000..e5302ed71c
--- /dev/null
+++ b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticExtension.php
@@ -0,0 +1,49 @@
+
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\AsseticBundle\Twig;
+
+use Assetic\Extension\Twig\AsseticExtension as BaseAsseticExtension;
+use Assetic\Factory\AssetFactory;
+
+/**
+ * Assetic extension.
+ *
+ * @author Kris Wallsmith
+ */
+class AsseticExtension extends BaseAsseticExtension
+{
+ private $useController;
+
+ public function __construct(AssetFactory $factory, $debug = false, $useController = false)
+ {
+ parent::__construct($factory, $debug);
+
+ $this->useController = $useController;
+ }
+
+ public function getTokenParsers()
+ {
+ return array(
+ new AsseticTokenParser($this->factory, 'javascripts', 'js/*.js', false, array('package')),
+ new AsseticTokenParser($this->factory, 'stylesheets', 'css/*.css', false, array('package')),
+ new AsseticTokenParser($this->factory, 'image', 'images/*', true, array('package')),
+ );
+ }
+
+ public function getGlobals()
+ {
+ $globals = parent::getGlobals();
+ $globals['assetic']['use_controller'] = $this->useController;
+
+ return $globals;
+ }
+}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php
new file mode 100644
index 0000000000..1202b4abe0
--- /dev/null
+++ b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticNode.php
@@ -0,0 +1,57 @@
+
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\AsseticBundle\Twig;
+
+use Assetic\Asset\AssetInterface;
+use Assetic\Extension\Twig\AsseticNode as BaseAsseticNode;
+
+/**
+ * Assetic node.
+ *
+ * @author Kris Wallsmith
+ */
+class AsseticNode extends BaseAsseticNode
+{
+ protected function compileAssetUrl(\Twig_Compiler $compiler, AssetInterface $asset, $name)
+ {
+ $compiler
+ ->raw('isset($context[\'assetic\'][\'use_controller\']) && $context[\'assetic\'][\'use_controller\'] ? ')
+ ->subcompile($this->getPathFunction($name))
+ ->raw(' : ')
+ ->subcompile($this->getAssetFunction($asset->getTargetUrl()))
+ ;
+ }
+
+ private function getPathFunction($name)
+ {
+ return new \Twig_Node_Expression_Function(
+ new \Twig_Node_Expression_Name('path', $this->getLine()),
+ new \Twig_Node(array(new \Twig_Node_Expression_Constant('_assetic_'.$name, $this->getLine()))),
+ $this->getLine()
+ );
+ }
+
+ private function getAssetFunction($path)
+ {
+ $arguments = array(new \Twig_Node_Expression_Constant($path, $this->getLine()));
+
+ if ($this->hasAttribute('package')) {
+ $arguments[] = new \Twig_Node_Expression_Constant($this->getAttribute('package'), $this->getLine());
+ }
+
+ return new \Twig_Node_Expression_Function(
+ new \Twig_Node_Expression_Name('asset', $this->getLine()),
+ new \Twig_Node($arguments),
+ $this->getLine()
+ );
+ }
+}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php
new file mode 100644
index 0000000000..fc0673ea24
--- /dev/null
+++ b/src/Symfony/Bundle/AsseticBundle/Twig/AsseticTokenParser.php
@@ -0,0 +1,28 @@
+
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Symfony\Bundle\AsseticBundle\Twig;
+
+use Assetic\Asset\AssetInterface;
+use Assetic\Extension\Twig\AsseticTokenParser as BaseAsseticTokenParser;
+
+/**
+ * Assetic token parser.
+ *
+ * @author Kris Wallsmith
+ */
+class AsseticTokenParser extends BaseAsseticTokenParser
+{
+ protected function createNode(AssetInterface $asset, \Twig_NodeInterface $body, array $inputs, array $filters, $name, array $attributes = array(), $lineno = 0, $tag = null)
+ {
+ return new AsseticNode($asset, $body, $inputs, $filters, $name, $attributes, $lineno, $tag);
+ }
+}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php b/src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php
deleted file mode 100644
index fc95aec740..0000000000
--- a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicExtension.php
+++ /dev/null
@@ -1,32 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Symfony\Bundle\AsseticBundle\Twig;
-
-use Assetic\Extension\Twig\AsseticExtension;
-use Assetic\Factory\AssetFactory;
-
-/**
- * The dynamic extension is used when use_controllers is enabled.
- *
- * @author Kris Wallsmith
- */
-class DynamicExtension extends AsseticExtension
-{
- public function getTokenParsers()
- {
- return array(
- new DynamicTokenParser($this->factory, 'javascripts', 'js/*.js', $this->debug, false, array('package')),
- new DynamicTokenParser($this->factory, 'stylesheets', 'css/*.css', $this->debug, false, array('package')),
- new DynamicTokenParser($this->factory, 'image', 'images/*', $this->debug, true, array('package')),
- );
- }
-}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php b/src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php
deleted file mode 100644
index b17c0d0541..0000000000
--- a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicNode.php
+++ /dev/null
@@ -1,36 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Symfony\Bundle\AsseticBundle\Twig;
-
-use Assetic\Extension\Twig\AsseticNode;
-
-/**
- * The "dynamic" node uses a controller to render assets.
- *
- * @author Kris Wallsmith
- */
-class DynamicNode extends AsseticNode
-{
- /**
- * Renders the asset URL using Symfony's path() function.
- */
- protected function getAssetUrlNode(\Twig_NodeInterface $body)
- {
- return new \Twig_Node_Expression_Function(
- new \Twig_Node_Expression_Name('path', $body->getLine()),
- new \Twig_Node(array(
- new \Twig_Node_Expression_Constant('assetic_'.$this->getAttribute('name'), $body->getLine()),
- )),
- $body->getLine()
- );
- }
-}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php b/src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php
deleted file mode 100644
index 418b48d50e..0000000000
--- a/src/Symfony/Bundle/AsseticBundle/Twig/DynamicTokenParser.php
+++ /dev/null
@@ -1,27 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Symfony\Bundle\AsseticBundle\Twig;
-
-use Assetic\Extension\Twig\AsseticTokenParser;
-
-/**
- * Parses an Assetic tag.
- *
- * @author Kris Wallsmith
- */
-class DynamicTokenParser extends AsseticTokenParser
-{
- static protected function createNode(\Twig_NodeInterface $body, array $inputs, array $filters, array $attributes, $lineno = 0, $tag = null)
- {
- return new DynamicNode($body, $inputs, $filters, $attributes, $lineno, $tag);
- }
-}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php b/src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php
deleted file mode 100644
index 884e6c7f24..0000000000
--- a/src/Symfony/Bundle/AsseticBundle/Twig/StaticExtension.php
+++ /dev/null
@@ -1,32 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Symfony\Bundle\AsseticBundle\Twig;
-
-use Assetic\Extension\Twig\AsseticExtension;
-use Assetic\Factory\AssetFactory;
-
-/**
- * The static extension is used when use_controllers is disabled.
- *
- * @author Kris Wallsmith
- */
-class StaticExtension extends AsseticExtension
-{
- public function getTokenParsers()
- {
- return array(
- new StaticTokenParser($this->factory, 'javascripts', 'js/*.js', $this->debug, false, array('package')),
- new StaticTokenParser($this->factory, 'stylesheets', 'css/*.css', $this->debug, false, array('package')),
- new StaticTokenParser($this->factory, 'image', 'images/*', $this->debug, true, array('package')),
- );
- }
-}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php b/src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php
deleted file mode 100644
index 73f0fe383f..0000000000
--- a/src/Symfony/Bundle/AsseticBundle/Twig/StaticNode.php
+++ /dev/null
@@ -1,37 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Symfony\Bundle\AsseticBundle\Twig;
-
-use Assetic\Extension\Twig\AsseticNode;
-
-/**
- * The "static" node references a file in the web directory.
- *
- * @author Kris Wallsmith
- */
-class StaticNode extends AsseticNode
-{
- /**
- * Renders the asset URL using Symfony's asset() function.
- */
- protected function getAssetUrlNode(\Twig_NodeInterface $body)
- {
- return new \Twig_Node_Expression_Function(
- new \Twig_Node_Expression_Name('asset', $body->getLine()),
- new \Twig_Node(array(
- new \Twig_Node_Expression_Constant($this->getAttribute('output'), $body->getLine()),
- new \Twig_Node_Expression_Constant($this->hasAttribute('package') ? $this->getAttribute('package') : null, $body->getLine()),
- )),
- $body->getLine()
- );
- }
-}
diff --git a/src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php b/src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php
deleted file mode 100644
index 5ee21b8ec7..0000000000
--- a/src/Symfony/Bundle/AsseticBundle/Twig/StaticTokenParser.php
+++ /dev/null
@@ -1,27 +0,0 @@
-
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Symfony\Bundle\AsseticBundle\Twig;
-
-use Assetic\Extension\Twig\AsseticTokenParser;
-
-/**
- * Parses an Assetic tag.
- *
- * @author Kris Wallsmith
- */
-class StaticTokenParser extends AsseticTokenParser
-{
- static protected function createNode(\Twig_NodeInterface $body, array $inputs, array $filters, array $attributes, $lineno = 0, $tag = null)
- {
- return new StaticNode($body, $inputs, $filters, $attributes, $lineno, $tag);
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php
index 7a67cdcd35..2be80fb775 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php
@@ -48,7 +48,7 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$connection = $this->getDoctrineConnection($input->getOption('connection'));
-
+
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path']:$params['dbname'];
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php
index f7b390cc60..041f7b472a 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php
@@ -39,7 +39,7 @@ abstract class DoctrineCommand extends Command
{
/**
* Convenience method to push the helper sets of a given entity manager into the application.
- *
+ *
* @param Application $application
* @param string $emName
*/
@@ -165,10 +165,11 @@ abstract class DoctrineCommand extends Command
protected function findBasePathForBundle($bundle)
{
$path = str_replace('\\', '/', $bundle->getNamespace());
- $destination = str_replace('/'.$path, "", $bundle->getPath(), $c);
+ $search = str_replace('\\', '/', $bundle->getPath());
+ $destination = str_replace('/'.$path, '', $search, $c);
if ($c != 1) {
- throw new \RuntimeException("Something went terribly wrong.");
+ throw new \RuntimeException(sprintf('Can\'t find base path for bundle (path: "%s", destination: "%s").', $path, $destination));
}
return $destination;
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php
index 572c1e829c..2f7579d2b5 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php
@@ -53,7 +53,7 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$connection = $this->getDoctrineConnection($input->getOption('connection'));
-
+
$params = $connection->getParams();
$name = isset($params['path'])?$params['path']:(isset($params['dbname'])?$params['dbname']:false);
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php
index 365f87ccd4..d2e4025cc1 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php
@@ -60,7 +60,7 @@ EOT
$entityGenerator = $this->getEntityGenerator();
foreach ($metadatas as $metadata) {
- if ($filterEntity && $metadata->reflClass->getShortName() !== $filterEntity) {
+ if ($filterEntity && $metadata->getReflClass()->getShortName() !== $filterEntity) {
continue;
}
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php
index 72d3ba2897..6c9e46930a 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php
@@ -51,7 +51,7 @@ EOT
if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
$output->writeln(sprintf('Generating entity repositories for "%s"', $foundBundle->getName()));
$generator = new EntityRepositoryGenerator();
-
+
foreach ($metadatas as $metadata) {
if ($filterEntity && $filterEntity !== $metadata->reflClass->getShortname()) {
continue;
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php
index 7e889bcb36..5a34a963d9 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/ImportMappingDoctrineCommand.php
@@ -77,7 +77,7 @@ EOT
$em = $this->getEntityManager($this->container, $input->getOption('em'));
$databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
$em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
-
+
$emName = $input->getOption('em');
$emName = $emName ? $emName : 'default';
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php
index 7399ac344e..fa357ad84a 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/InfoDoctrineCommand.php
@@ -69,7 +69,7 @@ EOT
$output->write(sprintf("Found %d entities mapped in entity manager %s:\n",
count($entityClassNames), $entityManagerName), true);
-
+
foreach ($entityClassNames as $entityClassName) {
try {
$cm = $entityManager->getClassMetadata($entityClassName);
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php
index 99b5af1893..5a21e5169c 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php
@@ -40,7 +40,7 @@ class LoadDataFixturesDoctrineCommand extends DoctrineCommand
->setName('doctrine:data:load')
->setDescription('Load data fixtures to your database.')
->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.')
- ->addOption('append', null, InputOption::VALUE_OPTIONAL, 'Whether or not to append the data fixtures.', false)
+ ->addOption('append', null, InputOption::VALUE_NONE, 'Append the data fixtures instead of flushing the database first.')
->addOption('em', null, InputOption::VALUE_REQUIRED, 'The entity manager to use for this command.')
->setHelp(<<doctrine:data:load command loads data fixtures from your bundles:
diff --git a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php
index 10a0324349..9ecd176db3 100644
--- a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/Configuration.php
@@ -36,7 +36,7 @@ class Configuration implements ConfigurationInterface
{
$this->debug = (Boolean) $debug;
}
-
+
/**
* Generates the configuration tree builder.
*
@@ -70,12 +70,7 @@ class Configuration implements ConfigurationInterface
->children()
->arrayNode('types')
->useAttributeAsKey('name')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['class']); })
- ->then(function($v) { return $v['class']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->end()
->fixXmlConfig('connection')
@@ -132,7 +127,7 @@ class Configuration implements ConfigurationInterface
{
$node
->children()
- ->arrayNode('orm')
+ ->arrayNode('orm')
->children()
->scalarNode('default_entity_manager')->end()
->booleanNode('auto_generate_proxy_classes')->defaultFalse()->end()
@@ -167,12 +162,7 @@ class Configuration implements ConfigurationInterface
->children()
->arrayNode('hydrators')
->useAttributeAsKey('name')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['class']); })
- ->then(function($v) { return $v['class']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->end()
->fixXmlConfig('mapping')
@@ -204,30 +194,15 @@ class Configuration implements ConfigurationInterface
->children()
->arrayNode('string_functions')
->useAttributeAsKey('name')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['class']); })
- ->then(function($v) { return $v['class']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->arrayNode('numeric_functions')
->useAttributeAsKey('name')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['class']); })
- ->then(function($v) { return $v['class']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->arrayNode('datetime_functions')
->useAttributeAsKey('name')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['class']); })
- ->then(function($v) { return $v['class']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->end()
->end()
diff --git a/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd b/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd
index e28636b6eb..99021559ee 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd
+++ b/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd
@@ -43,8 +43,11 @@
-
-
+
+
+
+
+
@@ -112,7 +115,10 @@
-
-
+
+
+
+
+
diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml
index 7bbad12c7f..368cc890e1 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml
+++ b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/dbal_types.xml
@@ -8,7 +8,7 @@
-
+ Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType
diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml
index b1fd7bd935..07814ab913 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml
+++ b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_functions.xml
@@ -12,9 +12,9 @@
-
-
-
+ Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction
+ Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction
+ Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction
diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml
index fc5f393c58..03e8a766de 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml
+++ b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/config/xml/orm_hydration_mode.xml
@@ -10,7 +10,7 @@
-
+ Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator
diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php b/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php
deleted file mode 100644
index 8867c30a71..0000000000
--- a/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/TestHydrator.php
+++ /dev/null
@@ -1,20 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection;
-
-class TestHydrator extends \Doctrine\ORM\Internal\Hydration\AbstractHydrator
-{
- protected function _hydrateAll();
- {
- return array();
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php
deleted file mode 100644
index ca875c01a0..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/HydratorCacheWarmer.php
+++ /dev/null
@@ -1,76 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer;
-
-use Symfony\Component\DependencyInjection\Container;
-use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
-
-/**
- * The hydrator generator cache warmer generates all document hydrators.
- *
- * In the process of generating hydrators the cache for all the metadata is primed also,
- * since this information is necessary to build the hydrators in the first place.
- *
- * @author Benjamin Eberlei
- * @author Jonathan H. Wage
- */
-class HydratorCacheWarmer implements CacheWarmerInterface
-{
- /**
- * @var Container
- */
- private $container;
-
- /**
- * @param Container $container
- */
- public function __construct(Container $container)
- {
- $this->container = $container;
- }
-
- /**
- * This cache warmer is not optional, without hydrators fatal error occurs!
- *
- * @return false
- */
- public function isOptional()
- {
- return false;
- }
-
- public function warmUp($cacheDir)
- {
- // we need the directory no matter the hydrator cache generation strategy.
- $hydratorCacheDir = $this->container->getParameter('doctrine.odm.mongodb.hydrator_dir');
- if (!file_exists($hydratorCacheDir)) {
- if (false === @mkdir($hydratorCacheDir, 0777, true)) {
- throw new \RuntimeException(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir)));
- }
- } else if (!is_writable($hydratorCacheDir)) {
- throw new \RuntimeException(sprintf('Doctrine Hydrator directory (%s) is not writeable for the current system user.', $hydratorCacheDir));
- }
-
- // if hydrators are autogenerated we don't need to generate them in the cache warmer.
- if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes') === true) {
- return;
- }
-
- $documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
- foreach ($documentManagers as $documentManagerName) {
- $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
- /* @var $dm Doctrine\ODM\MongoDB\DocumentManager */
- $classes = $dm->getMetadataFactory()->getAllMetadata();
- $dm->getHydratorFactory()->generateHydratorClasses($classes);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php
deleted file mode 100644
index 0fb7870521..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/CacheWarmer/ProxyCacheWarmer.php
+++ /dev/null
@@ -1,76 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer;
-
-use Symfony\Component\DependencyInjection\Container;
-use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
-
-/**
- * The proxy generator cache warmer generates all document proxies.
- *
- * In the process of generating proxies the cache for all the metadata is primed also,
- * since this information is necessary to build the proxies in the first place.
- *
- * @author Benjamin Eberlei
- * @author Jonathan H. Wage
- */
-class ProxyCacheWarmer implements CacheWarmerInterface
-{
- /**
- * @var Container
- */
- private $container;
-
- /**
- * @param Container $container
- */
- public function __construct(Container $container)
- {
- $this->container = $container;
- }
-
- /**
- * This cache warmer is not optional, without proxies fatal error occurs!
- *
- * @return false
- */
- public function isOptional()
- {
- return false;
- }
-
- public function warmUp($cacheDir)
- {
- // we need the directory no matter the proxy cache generation strategy.
- $proxyCacheDir = $this->container->getParameter('doctrine.odm.mongodb.proxy_dir');
- if (!file_exists($proxyCacheDir)) {
- if (false === @mkdir($proxyCacheDir, 0777, true)) {
- throw new \RuntimeException(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir)));
- }
- } else if (!is_writable($proxyCacheDir)) {
- throw new \RuntimeException(sprintf('Doctrine Proxy directory (%s) is not writeable for the current system user.', $proxyCacheDir));
- }
-
- // if proxies are autogenerated we don't need to generate them in the cache warmer.
- if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes') === true) {
- return;
- }
-
- $documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
- foreach ($documentManagers as $documentManagerName) {
- $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
- /* @var $dm Doctrine\ODM\MongoDB\DocumentManager */
- $classes = $dm->getMetadataFactory()->getAllMetadata();
- $dm->getProxyFactory()->generateProxyClasses($classes);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php
deleted file mode 100644
index be10a906d2..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/ClearMetadataCacheDoctrineODMCommand.php
+++ /dev/null
@@ -1,54 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand;
-
-/**
- * Command to clear the metadata cache of the various cache drivers.
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- * @author Henrik Westphal
- */
-class ClearMetadataCacheDoctrineODMCommand extends MetadataCommand
-{
- protected function configure()
- {
- parent::configure();
-
- $this
- ->setName('doctrine:mongodb:cache:clear-metadata')
- ->setDescription('Clear all metadata cache for a document manager.')
- ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
- ->setHelp(<<doctrine:mongodb:cache:clear-metadata command clears all metadata cache for the default document manager:
-
- ./app/console doctrine:mongodb:cache:clear-metadata
-
-You can also optionally specify the --dm option to specify which document manager to clear the cache for:
-
- ./app/console doctrine:mongodb:cache:clear-metadata --dm=default
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
-
- return parent::execute($input, $output);
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php
deleted file mode 100644
index 78cc32e702..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/CreateSchemaDoctrineODMCommand.php
+++ /dev/null
@@ -1,53 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand;
-
-/**
- * Command to create the database schema for a set of classes based on their mappings.
- *
- * @author Justin Hileman
- */
-class CreateSchemaDoctrineODMCommand extends CreateCommand
-{
- protected function configure()
- {
- parent::configure();
-
- $this
- ->setName('doctrine:mongodb:schema:create')
- ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
- ->setHelp(<<doctrine:mongodb:schema:create command creates the default document manager's schema:
-
- ./app/console doctrine:mongodb:schema:create
-
-You can also optionally specify the name of a document manager to create the schema for:
-
- ./app/console doctrine:mongodb:schema:create --dm=default
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
-
- parent::execute($input, $output);
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php
deleted file mode 100644
index 61f1c1f221..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DoctrineODMCommand.php
+++ /dev/null
@@ -1,120 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Bundle\FrameworkBundle\Command\Command;
-use Symfony\Bundle\FrameworkBundle\Console\Application;
-use Doctrine\ODM\MongoDB\Tools\Console\Helper\DocumentManagerHelper;
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-use Doctrine\ODM\MongoDB\Tools\DisconnectedClassMetadataFactory;
-use Doctrine\ODM\MongoDB\Tools\DocumentGenerator;
-
-/**
- * Base class for Doctrine ODM console commands to extend.
- *
- * @author Justin Hileman
- */
-abstract class DoctrineODMCommand extends Command
-{
- public static function setApplicationDocumentManager(Application $application, $dmName)
- {
- $container = $application->getKernel()->getContainer();
- $dmName = $dmName ? $dmName : 'default';
- $dmServiceName = sprintf('doctrine.odm.mongodb.%s_document_manager', $dmName);
- if (!$container->has($dmServiceName)) {
- throw new \InvalidArgumentException(sprintf('Could not find Doctrine ODM DocumentManager named "%s"', $dmName));
- }
-
- $dm = $container->get($dmServiceName);
- $helperSet = $application->getHelperSet();
- $helperSet->set(new DocumentManagerHelper($dm), 'dm');
- }
-
- protected function getDocumentGenerator()
- {
- $documentGenerator = new DocumentGenerator();
- $documentGenerator->setAnnotationPrefix('mongodb:');
- $documentGenerator->setGenerateAnnotations(false);
- $documentGenerator->setGenerateStubMethods(true);
- $documentGenerator->setRegenerateDocumentIfExists(false);
- $documentGenerator->setUpdateDocumentIfExists(true);
- $documentGenerator->setNumSpaces(4);
- return $documentGenerator;
- }
-
- protected function getDoctrineDocumentManagers()
- {
- $documentManagerNames = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
- $documentManagers = array();
- foreach ($documentManagerNames as $documentManagerName) {
- $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
- $documentManagers[] = $dm;
- }
- return $documentManagers;
- }
-
- protected function getBundleMetadatas(Bundle $bundle)
- {
- $namespace = $bundle->getNamespace();
- $bundleMetadatas = array();
- $documentManagers = $this->getDoctrineDocumentManagers();
- foreach ($documentManagers as $key => $dm) {
- $cmf = new DisconnectedClassMetadataFactory();
- $cmf->setDocumentManager($dm);
- $cmf->setConfiguration($dm->getConfiguration());
- $metadatas = $cmf->getAllMetadata();
- foreach ($metadatas as $metadata) {
- if (strpos($metadata->name, $namespace) === 0) {
- $bundleMetadatas[$metadata->name] = $metadata;
- }
- }
- }
-
- return $bundleMetadatas;
- }
-
- protected function findBundle($bundleName)
- {
- $foundBundle = false;
- foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) {
- /* @var $bundle Bundle */
- if (strtolower($bundleName) == strtolower($bundle->getName())) {
- $foundBundle = $bundle;
- break;
- }
- }
-
- if (!$foundBundle) {
- throw new \InvalidArgumentException("No bundle " . $bundleName . " was found.");
- }
-
- return $foundBundle;
- }
-
- /**
- * Transform classname to a path $foundBundle substract it to get the destination
- *
- * @param Bundle $bundle
- * @return string
- */
- protected function findBasePathForBundle($bundle)
- {
- $path = str_replace('\\', '/', $bundle->getNamespace());
- $destination = str_replace('/'.$path, "", $bundle->getPath(), $c);
-
- if ($c != 1) {
- throw new \RuntimeException("Something went terribly wrong.");
- }
-
- return $destination;
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php
deleted file mode 100644
index cb1ab9e888..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/DropSchemaDoctrineODMCommand.php
+++ /dev/null
@@ -1,53 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand;
-
-/**
- * Command to create the database schema for a set of classes based on their mappings.
- *
- * @author Justin Hileman
- */
-class DropSchemaDoctrineODMCommand extends DropCommand
-{
- protected function configure()
- {
- parent::configure();
-
- $this
- ->setName('doctrine:mongodb:schema:drop')
- ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
- ->setHelp(<<doctrine:mongodb:schema:drop command drops the default document manager's schema:
-
- ./app/console doctrine:mongodb:schema:drop
-
-You can also optionally specify the name of a document manager to drop the schema for:
-
- ./app/console doctrine:mongodb:schema:drop --dm=default
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
-
- parent::execute($input, $output);
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php
deleted file mode 100644
index fabb536b59..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateDocumentsDoctrineODMCommand.php
+++ /dev/null
@@ -1,80 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-
-/**
- * Generate document classes from mapping information
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- */
-class GenerateDocumentsDoctrineODMCommand extends DoctrineODMCommand
-{
- protected function configure()
- {
- $this
- ->setName('doctrine:mongodb:generate:documents')
- ->setDescription('Generate document classes and method stubs from your mapping information.')
- ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the document or documents in.')
- ->addOption('document', null, InputOption::VALUE_OPTIONAL, 'The document class to initialize (shortname without namespace).')
- ->setHelp(<<doctrine:mongodb:generate:documents command generates document classes and method stubs from your mapping information:
-
-You have to limit generation of documents to an individual bundle:
-
- ./app/console doctrine:mongodb:generate:documents MyCustomBundle
-
-Alternatively, you can limit generation to a single document within a bundle:
-
- ./app/console doctrine:mongodb:generate:documents "MyCustomBundle" --document="User"
-
-You have to specify the shortname (without namespace) of the document you want to filter for.
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- $bundleName = $input->getArgument('bundle');
- $filterDocument = $input->getOption('document');
-
- $foundBundle = $this->findBundle($bundleName);
-
- if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
- $output->writeln(sprintf('Generating documents for "%s"', $foundBundle->getName()));
- $documentGenerator = $this->getDocumentGenerator();
-
- foreach ($metadatas as $metadata) {
- if ($filterDocument && $metadata->reflClass->getShortName() == $filterDocument) {
- continue;
- }
-
- if (strpos($metadata->name, $foundBundle->getNamespace()) === false) {
- throw new \RuntimeException(
- "Document " . $metadata->name . " and bundle don't have a common namespace, ".
- "generation failed because the target directory cannot be detected.");
- }
-
- $output->writeln(sprintf(' > generating %s', $metadata->name));
- $documentGenerator->generate(array($metadata), $this->findBasePathForBundle($foundBundle));
- }
- } else {
- throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped documents.");
- }
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php
deleted file mode 100644
index c025fae963..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateHydratorsDoctrineODMCommand.php
+++ /dev/null
@@ -1,54 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand;
-
-/**
- * Generate the Doctrine ORM document hydrators to your cache directory.
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- */
-class GenerateHydratorsDoctrineODMCommand extends GenerateHydratorsCommand
-{
- protected function configure()
- {
- parent::configure();
-
- $this
- ->setName('doctrine:mongodb:generate:hydrators')
- ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
- ->setHelp(<<doctrine:mongodb:generate:hydrators command generates hydrator classes for your documents:
-
- ./app/console doctrine:mongodb:generate:hydrators
-
-You can specify the document manager you want to generate the hydrators for:
-
- ./app/console doctrine:mongodb:generate:hydrators --dm=name
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
-
- return parent::execute($input, $output);
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php
deleted file mode 100644
index ecf8b650b2..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateProxiesDoctrineODMCommand.php
+++ /dev/null
@@ -1,54 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand;
-
-/**
- * Generate the Doctrine ORM document proxies to your cache directory.
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- */
-class GenerateProxiesDoctrineODMCommand extends GenerateProxiesCommand
-{
- protected function configure()
- {
- parent::configure();
-
- $this
- ->setName('doctrine:mongodb:generate:proxies')
- ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
- ->setHelp(<<doctrine:mongodb:generate:proxies command generates proxy classes for your default document manager:
-
- ./app/console doctrine:mongodb:generate:proxies
-
-You can specify the document manager you want to generate the proxies for:
-
- ./app/console doctrine:mongodb:generate:proxies --dm=name
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
-
- return parent::execute($input, $output);
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php
deleted file mode 100644
index 3233cbab82..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/GenerateRepositoriesDoctrineODMCommand.php
+++ /dev/null
@@ -1,77 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Doctrine\ODM\MongoDB\Tools\DocumentRepositoryGenerator;
-
-/**
- * Command to generate repository classes for mapping information.
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- */
-class GenerateRepositoriesDoctrineODMCommand extends DoctrineODMCommand
-{
- protected function configure()
- {
- $this
- ->setName('doctrine:mongodb:generate:repositories')
- ->setDescription('Generate repository classes from your mapping information.')
- ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to initialize the repositories in.')
- ->addOption('document', null, InputOption::VALUE_OPTIONAL, 'The document class to generate the repository for (shortname without namespace).')
- ->setHelp(<<doctrine:mongodb:generate:repositories command generates the configured document repository classes from your mapping information:
-
- ./app/console doctrine:mongodb:generate:repositories
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- $bundleName = $input->getArgument('bundle');
- $filterDocument = $input->getOption('document');
-
- $foundBundle = $this->findBundle($bundleName);
-
- if ($metadatas = $this->getBundleMetadatas($foundBundle)) {
- $output->writeln(sprintf('Generating document repositories for "%s"', $foundBundle->getName()));
- $generator = new DocumentRepositoryGenerator();
-
- foreach ($metadatas as $metadata) {
- if ($filterDocument && $filterDocument !== $metadata->reflClass->getShortname()) {
- continue;
- }
-
- if ($metadata->customRepositoryClassName) {
- if (strpos($metadata->customRepositoryClassName, $foundBundle->getNamespace()) === false) {
- throw new \RuntimeException(
- "Repository " . $metadata->customRepositoryClassName . " and bundle don't have a common namespace, ".
- "generation failed because the target directory cannot be detected.");
- }
-
- $output->writeln(sprintf(' > OK generating %s', $metadata->customRepositoryClassName));
- $generator->writeDocumentRepositoryClass($metadata->customRepositoryClassName, $this->findBasePathForBundle($foundBundle));
- } else {
- $output->writeln(sprintf(' > SKIP no custom repository for %s', $metadata->name));
- }
- }
- } else {
- throw new \RuntimeException("Bundle " . $bundleName . " does not contain any mapped documents.");
- }
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php
deleted file mode 100644
index 51779b22d6..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php
+++ /dev/null
@@ -1,84 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-
-/**
- * Show information about mapped documents
- *
- * @author Benjamin Eberlei
- * @author Jonathan H. Wage
- */
-class InfoDoctrineODMCommand extends DoctrineODMCommand
-{
- protected function configure()
- {
- $this
- ->setName('doctrine:mongodb:mapping:info')
- ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.')
- ->setDescription('Show basic information about all mapped documents.')
- ->setHelp(<<doctrine:mongodb:mapping:info shows basic information about which
-documents exist and possibly if their mapping information contains errors or not.
-
- ./app/console doctrine:mongodb:mapping:info
-
-If you are using multiple document managers you can pick your choice with the --dm option:
-
- ./app/console doctrine:mongodb:mapping:info --dm=default
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- $documentManagerName = $input->getOption('dm') ?
- $input->getOption('dm') :
- $this->container->getParameter('doctrine.odm.mongodb.default_document_manager');
-
- $documentManagerService = sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName);
-
- /* @var $documentManager Doctrine\ODM\MongoDB\DocumentManager */
- $documentManager = $this->container->get($documentManagerService);
-
- $documentClassNames = $documentManager->getConfiguration()
- ->getMetadataDriverImpl()
- ->getAllClassNames();
-
- if (!$documentClassNames) {
- throw new \Exception(
- 'You do not have any mapped Doctrine MongoDB ODM documents for any of your bundles. '.
- 'Create a class inside the Document namespace of any of your bundles and provide '.
- 'mapping information for it with Annotations directly in the classes doc blocks '.
- 'or with XML/YAML in your bundles Resources/config/doctrine/metadata/mongodb directory.'
- );
- }
-
- $output->write(sprintf("Found %d documents mapped in document manager %s:\n",
- count($documentClassNames), $documentManagerName), true);
-
- foreach ($documentClassNames AS $documentClassName) {
- try {
- $cm = $documentManager->getClassMetadata($documentClassName);
- $output->write("[OK] " . $documentClassName, true);
- } catch(\Exception $e) {
- $output->write("[FAIL] " . $documentClassName, true);
- $output->write("" . $e->getMessage()."", true);
- $output->write("", true);
- }
- }
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php
deleted file mode 100644
index f7ec8481db..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/LoadDataFixturesDoctrineODMCommand.php
+++ /dev/null
@@ -1,108 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Symfony\Component\Finder\Finder;
-use Symfony\Component\HttpKernel\Util\Filesystem;
-use Symfony\Bundle\DoctrineAbstractBundle\Common\DataFixtures\Loader as DataFixturesLoader;
-use Doctrine\Common\DataFixtures\Executor\MongoDBExecutor;
-use Doctrine\Common\DataFixtures\Purger\MongoDBPurger;
-use Doctrine\ODM\MongoDB\DocumentManager;
-use Doctrine\ODM\MongoDB\Internal\CommitOrderCalculator;
-use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
-use InvalidArgumentException;
-
-/**
- * Load data fixtures from bundles.
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- */
-class LoadDataFixturesDoctrineODMCommand extends DoctrineODMCommand
-{
- protected function configure()
- {
- $this
- ->setName('doctrine:mongodb:data:load')
- ->setDescription('Load data fixtures to your database.')
- ->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.')
- ->addOption('append', null, InputOption::VALUE_OPTIONAL, 'Whether or not to append the data fixtures.', false)
- ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
- ->setHelp(<<doctrine:mongodb:data:load command loads data fixtures from your bundles:
-
- ./app/console doctrine:mongodb:data:load
-
-You can also optionally specify the path to fixtures with the --fixtures option:
-
- ./app/console doctrine:mongodb:data:load --fixtures=/path/to/fixtures1 --fixtures=/path/to/fixtures2
-
-If you want to append the fixtures instead of flushing the database first you can use the --append option:
-
- ./app/console doctrine:mongodb:data:load --append
-EOT
- );
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- $dmName = $input->getOption('dm');
- $dmName = $dmName ? $dmName : 'default';
- $dmServiceName = sprintf('doctrine.odm.mongodb.%s_document_manager', $dmName);
-
- if (!$this->container->has($dmServiceName)) {
- throw new InvalidArgumentException(
- sprintf(
- 'Could not find a document manager configured with the name "%s". Check your '.
- 'application configuration to configure your Doctrine document managers.', $dmName
- )
- );
- }
-
- $dm = $this->container->get($dmServiceName);
- $dirOrFile = $input->getOption('fixtures');
- if ($dirOrFile) {
- $paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile);
- } else {
- $paths = array();
- foreach ($this->container->get('kernel')->getBundles() as $bundle) {
- $paths[] = $bundle->getPath().'/DataFixtures/MongoDB';
- }
- }
-
- $loader = new DataFixturesLoader($this->container);
- foreach ($paths as $path) {
- if (is_dir($path)) {
- $loader->loadFromDirectory($path);
- }
- }
-
- $fixtures = $loader->getFixtures();
- if (!$fixtures) {
- throw new InvalidArgumentException(
- sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths))
- );
- }
-
- $purger = new MongoDBPurger($dm);
- $executor = new MongoDBExecutor($dm, $purger);
- $executor->setLogger(function($message) use ($output) {
- $output->writeln(sprintf(' > %s', $message));
- });
- $executor->execute($fixtures, $input->getOption('append'));
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php
deleted file mode 100644
index fdacd39768..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/QueryDoctrineODMCommand.php
+++ /dev/null
@@ -1,44 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Command;
-
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Output\Output;
-use Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand;
-
-/**
- * Execute a Doctrine MongoDB ODM query and output the results.
- *
- * @author Fabien Potencier
- * @author Jonathan H. Wage
- */
-class QueryDoctrineODMCommand extends QueryCommand
-{
- protected function configure()
- {
- parent::configure();
-
- $this
- ->setName('doctrine:mongodb:query')
- ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.');
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- DoctrineODMCommand::setApplicationDocumentManager($this->getApplication(), $input->getOption('dm'));
-
- return parent::execute($input, $output);
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php
deleted file mode 100644
index e6c14eca15..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DataCollector/DoctrineMongoDBDataCollector.php
+++ /dev/null
@@ -1,59 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\DataCollector;
-
-use Symfony\Component\HttpKernel\DataCollector\DataCollector;
-use Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\HttpFoundation\Response;
-
-/**
- * Data collector for the Doctrine MongoDB ODM.
- *
- * @author Kris Wallsmith
- */
-class DoctrineMongoDBDataCollector extends DataCollector
-{
- protected $logger;
-
- public function __construct(DoctrineMongoDBLogger $logger)
- {
- $this->logger = $logger;
- }
-
- /**
- * {@inheritdoc}
- */
- public function collect(Request $request, Response $response, \Exception $exception = null)
- {
- $this->data['nb_queries'] = $this->logger->getNbQueries();
- $this->data['queries'] = $this->logger->getQueries();
- }
-
- public function getQueryCount()
- {
- return $this->data['nb_queries'];
- }
-
- public function getQueries()
- {
- return $this->data['queries'];
- }
-
- /**
- * {@inheritdoc}
- */
- public function getName()
- {
- return 'mongodb';
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php
deleted file mode 100644
index 1855c4e827..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateHydratorDirectoryPass.php
+++ /dev/null
@@ -1,30 +0,0 @@
-hasParameter('doctrine.odm.mongodb.hydrator_dir')) {
- return;
- }
- // Don't do anything if auto_generate_hydrator_classes is false
- if (!$container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes')) {
- return;
- }
- // Create document proxy directory
- $hydratorCacheDir = $container->getParameter('doctrine.odm.mongodb.hydrator_dir');
- if (!is_dir($hydratorCacheDir)) {
- if (false === @mkdir($hydratorCacheDir, 0777, true)) {
- exit(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir)));
- }
- } elseif (!is_writable($hydratorCacheDir)) {
- exit(sprintf('Unable to write in the Doctrine Hydrator directory (%s)', $hydratorCacheDir));
- }
- }
-
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php
deleted file mode 100644
index e14cc9e503..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/CreateProxyDirectoryPass.php
+++ /dev/null
@@ -1,30 +0,0 @@
-hasParameter('doctrine.odm.mongodb.proxy_dir')) {
- return;
- }
- // Don't do anything if auto_generate_proxy_classes is false
- if (!$container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes')) {
- return;
- }
- // Create document proxy directory
- $proxyCacheDir = $container->getParameter('doctrine.odm.mongodb.proxy_dir');
- if (!is_dir($proxyCacheDir)) {
- if (false === @mkdir($proxyCacheDir, 0777, true)) {
- exit(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir)));
- }
- } elseif (!is_writable($proxyCacheDir)) {
- exit(sprintf('Unable to write in the Doctrine Proxy directory (%s)', $proxyCacheDir));
- }
- }
-
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php
deleted file mode 100644
index b104c57845..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Compiler/RegisterEventListenersAndSubscribersPass.php
+++ /dev/null
@@ -1,59 +0,0 @@
-container = $container;
- foreach ($container->findTaggedServiceIds('doctrine.odm.mongodb.event_manager') as $id => $tag) {
- $definition = $container->getDefinition($id);
- $prefix = substr($id, 0, -1 * strlen('_event_manager'));
- $this->registerListeners($prefix, $definition);
- $this->registerSubscribers($prefix, $definition);
- }
- }
-
- protected function registerSubscribers($prefix, $definition)
- {
- $subscribers = array_merge(
- $this->container->findTaggedServiceIds('doctrine.common.event_subscriber'),
- $this->container->findTaggedServiceIds($prefix.'_event_subscriber')
- );
-
- foreach ($subscribers as $id => $instances) {
- $definition->addMethodCall('addEventSubscriber', array(new Reference($id)));
- }
- }
-
- protected function registerListeners($prefix, $definition)
- {
- $listeners = array_merge(
- $this->container->findTaggedServiceIds('doctrine.common.event_listener'),
- $this->container->findTaggedServiceIds($prefix.'_event_listener')
- );
-
- foreach ($listeners as $listenerId => $instances) {
- $events = array();
- foreach ($instances as $attributes) {
- if (isset($attributes['event'])) {
- $events[] = $attributes['event'];
- }
- }
-
- if (0 < count($events)) {
- $definition->addMethodCall('addEventListener', array(
- $events,
- new Reference($listenerId),
- ));
- }
- }
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php
deleted file mode 100644
index 44bd4da798..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/Configuration.php
+++ /dev/null
@@ -1,193 +0,0 @@
-
- */
-class Configuration implements ConfigurationInterface
-{
- private $debug;
-
- /**
- * Constructor.
- *
- * @param Boolean $debug The kernel.debug value
- */
- public function __construct($debug)
- {
- $this->debug = (Boolean) $debug;
- }
-
- /**
- * Generates the configuration tree builder.
- *
- * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
- */
- public function getConfigTreeBuilder()
- {
- $treeBuilder = new TreeBuilder();
- $rootNode = $treeBuilder->root('doctrine_mongo_db');
-
- $this->addDocumentManagersSection($rootNode);
- $this->addConnectionsSection($rootNode);
-
- $rootNode
- ->children()
- ->scalarNode('proxy_namespace')->defaultValue('Proxies')->end()
- ->scalarNode('proxy_dir')->defaultValue('%kernel.cache_dir%/doctrine/odm/mongodb/Proxies')->end()
- ->scalarNode('auto_generate_proxy_classes')->defaultValue(false)->end()
- ->scalarNode('hydrator_namespace')->defaultValue('Hydrators')->end()
- ->scalarNode('hydrator_dir')->defaultValue('%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators')->end()
- ->scalarNode('auto_generate_hydrator_classes')->defaultValue(false)->end()
- ->scalarNode('default_document_manager')->end()
- ->scalarNode('default_connection')->end()
- ->scalarNode('default_database')->defaultValue('default')->end()
- ->end()
- ;
-
- return $treeBuilder;
- }
-
- /**
- * Configures the "document_managers" section
- */
- private function addDocumentManagersSection(ArrayNodeDefinition $rootNode)
- {
- $rootNode
- ->fixXmlConfig('document_manager')
- ->children()
- ->arrayNode('document_managers')
- ->useAttributeAsKey('id')
- ->prototype('array')
- //->performNoDeepMerging()
- ->treatNullLike(array())
- ->append($this->getMetadataCacheDriverNode())
- ->children()
- ->scalarNode('connection')->end()
- ->scalarNode('database')->end()
- ->booleanNode('logging')->defaultValue($this->debug)->end()
- ->end()
- ->fixXmlConfig('mapping')
- ->append($this->getMappingsNode())
- ->end()
- ->end()
- ->end()
- ;
- }
-
- /**
- * Adds the configuration for the "connections" key
- */
- private function addConnectionsSection(ArrayNodeDefinition $rootNode)
- {
- $rootNode
- ->fixXmlConfig('connection')
- ->children()
- ->arrayNode('connections')
- ->useAttributeAsKey('id')
- ->prototype('array')
- ->performNoDeepMerging()
- ->children()
- ->scalarNode('server')->defaultNull()->end()
- ->end()
- ->append($this->addConnectionOptionsNode())
- ->end()
- ->end()
- ->end()
- ;
- }
-
- /**
- * Returns the array node used for "mappings".
- *
- * This is used in two different parts of the tree.
- *
- * @param NodeBuilder $rootNode The parent node
- * @return NodeBuilder
- */
- protected function getMappingsNode()
- {
- $builder = new TreeBuilder();
- $node = $builder->root('mappings');
-
- $node
- ->useAttributeAsKey('name')
- ->prototype('array')
- ->beforeNormalization()
- // if it's not an array, then the scalar is the type key
- ->ifString()
- ->then(function($v) { return array ('type' => $v); })
- ->end()
- // I believe that "null" should *not* set the type
- // it's guessed in AbstractDoctrineExtension::detectMetadataDriver
- ->treatNullLike(array())
- ->children()
- ->scalarNode('type')->end()
- ->scalarNode('dir')->end()
- ->scalarNode('prefix')->end()
- ->scalarNode('alias')->end()
- ->booleanNode('is_bundle')->end()
- ->end()
- ->performNoDeepMerging()
- ->end()
- ;
-
- return $node;
- }
-
- /**
- * Adds the NodeBuilder for the "options" key of a connection.
- */
- private function addConnectionOptionsNode()
- {
- $builder = new TreeBuilder();
- $node = $builder->root('options');
-
- $node
- ->performNoDeepMerging()
- ->addDefaultsIfNotSet() // adds an empty array of omitted
- // options go into the Mongo constructor
- // http://www.php.net/manual/en/mongo.construct.php
- ->children()
- ->booleanNode('connect')->end()
- ->scalarNode('persist')->end()
- ->scalarNode('timeout')->end()
- ->booleanNode('replicaSet')->end()
- ->scalarNode('username')->end()
- ->scalarNode('password')->end()
- ->end()
- ->end();
-
- return $node;
- }
-
- private function getMetadataCacheDriverNode()
- {
- $builder = new TreeBuilder();
- $node = $builder->root('metadata_cache_driver');
-
- $node
- ->beforeNormalization()
- // if scalar
- ->ifTrue(function($v) { return !is_array($v); })
- ->then(function($v) { return array('type' => $v); })
- ->end()
- ->children()
- ->scalarNode('type')->end()
- ->scalarNode('class')->end()
- ->scalarNode('host')->end()
- ->scalarNode('port')->end()
- ->scalarNode('instance_class')->end()
- ->end()
- ->end();
-
- return $node;
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php
deleted file mode 100644
index aa61fddd22..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DependencyInjection/DoctrineMongoDBExtension.php
+++ /dev/null
@@ -1,359 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Alias;
-use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\DependencyInjection\Definition;
-use Symfony\Component\Config\FileLocator;
-use Symfony\Component\Config\Definition\Processor;
-use Symfony\Bundle\DoctrineAbstractBundle\DependencyInjection\AbstractDoctrineExtension;
-
-/**
- * Doctrine MongoDB ODM extension.
- *
- * @author Bulat Shakirzyanov
- * @author Kris Wallsmith
- * @author Jonathan H. Wage
- */
-class DoctrineMongoDBExtension extends AbstractDoctrineExtension
-{
- /**
- * Responds to the doctrine_mongo_db configuration parameter.
- */
- public function load(array $configs, ContainerBuilder $container)
- {
- // Load DoctrineMongoDBBundle/Resources/config/mongodb.xml
- $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
- $loader->load('mongodb.xml');
-
- $processor = new Processor();
- $configuration = new Configuration($container->getParameter('kernel.debug'));
- $config = $processor->processConfiguration($configuration, $configs);
-
- // can't currently default this correctly in Configuration
- if (!isset($config['metadata_cache_driver'])) {
- $config['metadata_cache_driver'] = array('type' => 'array');
- }
-
- if (empty ($config['default_connection'])) {
- $keys = array_keys($config['connections']);
- $config['default_connection'] = reset($keys);
- }
-
- if (empty ($config['default_document_manager'])) {
- $keys = array_keys($config['document_managers']);
- $config['default_document_manager'] = reset($keys);
- }
-
- // set some options as parameters and unset them
- $config = $this->overrideParameters($config, $container);
-
- // load the connections
- $this->loadConnections($config['connections'], $container);
-
- // load the document managers
- $this->loadDocumentManagers(
- $config['document_managers'],
- $config['default_document_manager'],
- $config['default_database'],
- $config['metadata_cache_driver'],
- $container
- );
-
- $this->loadConstraints($container);
- }
-
- /**
- * Uses some of the extension options to override DI extension parameters.
- *
- * @param array $options The available configuration options
- * @param ContainerBuilder $container A ContainerBuilder instance
- */
- protected function overrideParameters($options, ContainerBuilder $container)
- {
- $overrides = array(
- 'proxy_namespace',
- 'proxy_dir',
- 'auto_generate_proxy_classes',
- 'hydrator_namespace',
- 'hydrator_dir',
- 'auto_generate_hydrator_classes',
- );
-
- foreach ($overrides as $key) {
- if (isset($options[$key])) {
- $container->setParameter('doctrine.odm.mongodb.'.$key, $options[$key]);
-
- // the option should not be used, the parameter should be referenced
- unset($options[$key]);
- }
- }
-
- return $options;
- }
-
- /**
- * Loads the document managers configuration.
- *
- * @param array $dmConfigs An array of document manager configs
- * @param string $defaultDM The default document manager name
- * @param string $defaultDB The default db name
- * @param string $defaultMetadataCache The default metadata cache configuration
- * @param ContainerBuilder $container A ContainerBuilder instance
- */
- protected function loadDocumentManagers(array $dmConfigs, $defaultDM, $defaultDB, $defaultMetadataCache, ContainerBuilder $container)
- {
- foreach ($dmConfigs as $name => $documentManager) {
- $documentManager['name'] = $name;
- $this->loadDocumentManager(
- $documentManager,
- $defaultDM,
- $defaultDB,
- $defaultMetadataCache,
- $container
- );
- }
- $container->setParameter('doctrine.odm.mongodb.document_managers', array_keys($dmConfigs));
- }
-
- /**
- * Loads a document manager configuration.
- *
- * @param array $documentManager A document manager configuration array
- * @param string $defaultDM The default document manager name
- * @param string $defaultDB The default db name
- * @param string $defaultMetadataCache The default metadata cache configuration
- * @param ContainerBuilder $container A ContainerBuilder instance
- */
- protected function loadDocumentManager(array $documentManager, $defaultDM, $defaultDB, $defaultMetadataCache, ContainerBuilder $container)
- {
- $defaultDatabase = isset($documentManager['default_database']) ? $documentManager['default_database'] : $defaultDB;
- $configServiceName = sprintf('doctrine.odm.mongodb.%s_configuration', $documentManager['name']);
-
- if ($container->hasDefinition($configServiceName)) {
- $odmConfigDef = $container->getDefinition($configServiceName);
- } else {
- $odmConfigDef = new Definition('%doctrine.odm.mongodb.configuration_class%');
- $container->setDefinition($configServiceName, $odmConfigDef);
- }
-
- $this->loadDocumentManagerBundlesMappingInformation($documentManager, $odmConfigDef, $container);
- $this->loadDocumentManagerMetadataCacheDriver($documentManager, $container, $defaultMetadataCache);
-
- $methods = array(
- 'setMetadataCacheImpl' => new Reference(sprintf('doctrine.odm.mongodb.%s_metadata_cache', $documentManager['name'])),
- 'setMetadataDriverImpl' => new Reference(sprintf('doctrine.odm.mongodb.%s_metadata_driver', $documentManager['name'])),
- 'setProxyDir' => '%doctrine.odm.mongodb.proxy_dir%',
- 'setProxyNamespace' => '%doctrine.odm.mongodb.proxy_namespace%',
- 'setAutoGenerateProxyClasses' => '%doctrine.odm.mongodb.auto_generate_proxy_classes%',
- 'setHydratorDir' => '%doctrine.odm.mongodb.hydrator_dir%',
- 'setHydratorNamespace' => '%doctrine.odm.mongodb.hydrator_namespace%',
- 'setAutoGenerateHydratorClasses' => '%doctrine.odm.mongodb.auto_generate_hydrator_classes%',
- 'setDefaultDB' => $defaultDatabase,
- );
-
- if ($documentManager['logging']) {
- $methods['setLoggerCallable'] = array(new Reference('doctrine.odm.mongodb.logger'), 'logQuery');
- }
-
- foreach ($methods as $method => $arg) {
- if ($odmConfigDef->hasMethodCall($method)) {
- $odmConfigDef->removeMethodCall($method);
- }
- $odmConfigDef->addMethodCall($method, array($arg));
- }
-
- // event manager
- $eventManagerName = isset($documentManager['event_manager']) ? $documentManager['event_manager'] : $documentManager['name'];
- $eventManagerId = sprintf('doctrine.odm.mongodb.%s_event_manager', $eventManagerName);
- if (!$container->hasDefinition($eventManagerId)) {
- $eventManagerDef = new Definition('%doctrine.odm.mongodb.event_manager_class%');
- $eventManagerDef->addTag('doctrine.odm.mongodb.event_manager');
- $eventManagerDef->setPublic(false);
- $container->setDefinition($eventManagerId, $eventManagerDef);
- }
-
- $odmDmArgs = array(
- new Reference(sprintf('doctrine.odm.mongodb.%s_connection', isset($documentManager['connection']) ? $documentManager['connection'] : $documentManager['name'])),
- new Reference(sprintf('doctrine.odm.mongodb.%s_configuration', $documentManager['name'])),
- new Reference($eventManagerId),
- );
- $odmDmDef = new Definition('%doctrine.odm.mongodb.document_manager_class%', $odmDmArgs);
- $odmDmDef->setFactoryClass('%doctrine.odm.mongodb.document_manager_class%');
- $odmDmDef->setFactoryMethod('create');
- $odmDmDef->addTag('doctrine.odm.mongodb.document_manager');
- $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManager['name']), $odmDmDef);
-
- if ($documentManager['name'] == $defaultDM) {
- $container->setAlias(
- 'doctrine.odm.mongodb.document_manager',
- new Alias(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManager['name']))
- );
- $container->setAlias(
- 'doctrine.odm.mongodb.event_manager',
- new Alias(sprintf('doctrine.odm.mongodb.%s_event_manager', $documentManager['name']))
- );
- }
- }
-
- /**
- * Loads the configured document manager metadata cache driver.
- *
- * @param array $config A configured document manager array
- * @param ContainerBuilder $container A ContainerBuilder instance
- * @param array $defaultMetadataCache The default metadata cache configuration array
- */
- protected function loadDocumentManagerMetadataCacheDriver(array $documentManager, ContainerBuilder $container, $defaultMetadataCache)
- {
- $dmMetadataCacheDriver = isset($documentManager['metadata_cache_driver']) ? $documentManager['metadata_cache_driver'] : $defaultMetadataCache;
- $type = $dmMetadataCacheDriver['type'];
-
- if ('memcache' === $type) {
- $memcacheClass = isset($dmMetadataCacheDriver['class']) ? $dmMetadataCacheDriver['class'] : sprintf('%%doctrine.odm.mongodb.cache.%s_class%%', $type);
- $cacheDef = new Definition($memcacheClass);
- $memcacheHost = isset($dmMetadataCacheDriver['host']) ? $dmMetadataCacheDriver['host'] : '%doctrine.odm.mongodb.cache.memcache_host%';
- $memcachePort = isset($dmMetadataCacheDriver['port']) ? $dmMetadataCacheDriver['port'] : '%doctrine.odm.mongodb.cache.memcache_port%';
- $memcacheInstanceClass = isset($dmMetadataCacheDriver['instance-class']) ? $dmMetadataCacheDriver['instance-class'] : (isset($dmMetadataCacheDriver['instance_class']) ? $dmMetadataCacheDriver['instance_class'] : '%doctrine.odm.mongodb.cache.memcache_instance_class%');
- $memcacheInstance = new Definition($memcacheInstanceClass);
- $memcacheInstance->addMethodCall('connect', array($memcacheHost, $memcachePort));
- $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_memcache_instance', $documentManager['name']), $memcacheInstance);
- $cacheDef->addMethodCall('setMemcache', array(new Reference(sprintf('doctrine.odm.mongodb.%s_memcache_instance', $documentManager['name']))));
- } else {
- $cacheDef = new Definition(sprintf('%%doctrine.odm.mongodb.cache.%s_class%%', $type));
- }
-
- $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_metadata_cache', $documentManager['name']), $cacheDef);
- }
-
- /**
- * Loads the configured connections.
- *
- * @param array $config An array of connections configurations
- * @param ContainerBuilder $container A ContainerBuilder instance
- */
- protected function loadConnections(array $connections, ContainerBuilder $container)
- {
- foreach ($connections as $name => $connection) {
- $odmConnArgs = array(
- isset($connection['server']) ? $connection['server'] : null,
- isset($connection['options']) ? $connection['options'] : array(),
- new Reference(sprintf('doctrine.odm.mongodb.%s_configuration', $name))
- );
- $odmConnDef = new Definition('%doctrine.odm.mongodb.connection_class%', $odmConnArgs);
- $container->setDefinition(sprintf('doctrine.odm.mongodb.%s_connection', $name), $odmConnDef);
- }
- }
-
- /**
- * Loads an ODM document managers bundle mapping information.
- *
- * There are two distinct configuration possibilities for mapping information:
- *
- * 1. Specify a bundle and optionally details where the entity and mapping information reside.
- * 2. Specify an arbitrary mapping location.
- *
- * @example
- *
- * doctrine.orm:
- * mappings:
- * MyBundle1: ~
- * MyBundle2: yml
- * MyBundle3: { type: annotation, dir: Documents/ }
- * MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
- * MyBundle5:
- * type: yml
- * dir: [bundle-mappings1/, bundle-mappings2/]
- * alias: BundleAlias
- * arbitrary_key:
- * type: xml
- * dir: %kernel.dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Documents
- * prefix: DoctrineExtensions\Documents\
- * alias: DExt
- *
- * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
- * in the mappings key everything except alias is a required argument.
- *
- * @param array $documentManager A configured ODM entity manager.
- * @param Definition A Definition instance
- * @param ContainerBuilder $container A ContainerBuilder instance
- */
- protected function loadDocumentManagerBundlesMappingInformation(array $documentManager, Definition $odmConfigDef, ContainerBuilder $container)
- {
- // reset state of drivers and alias map. They are only used by this methods and children.
- $this->drivers = array();
- $this->aliasMap = array();
-
- $this->loadMappingInformation($documentManager, $container);
- $this->registerMappingDrivers($documentManager, $container);
-
- if ($odmConfigDef->hasMethodCall('setDocumentNamespaces')) {
- // TODO: Can we make a method out of it on Definition? replaceMethodArguments() or something.
- $calls = $odmConfigDef->getMethodCalls();
- foreach ($calls as $call) {
- if ($call[0] == 'setDocumentNamespaces') {
- $this->aliasMap = array_merge($call[1][0], $this->aliasMap);
- }
- }
- $method = $odmConfigDef->removeMethodCall('setDocumentNamespaces');
- }
- $odmConfigDef->addMethodCall('setDocumentNamespaces', array($this->aliasMap));
- }
-
- protected function loadConstraints(ContainerBuilder $container)
- {
- // FIXME: the validator.annotations.namespaces parameter does not exist anymore
- // and anyway, it was not available in the FrameworkExtension code
- // as each bundle is isolated from the others
- if ($container->hasParameter('validator.annotations.namespaces')) {
- $container->setParameter('validator.annotations.namespaces', array_merge(
- $container->getParameter('validator.annotations.namespaces'),
- array('mongodb' => 'Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\\')
- ));
- }
- }
-
- protected function getObjectManagerElementName($name)
- {
- return 'doctrine.odm.mongodb.' . $name;
- }
-
- protected function getMappingObjectDefaultName()
- {
- return 'Document';
- }
-
- protected function getMappingResourceConfigDirectory()
- {
- return 'Resources/config/doctrine/metadata/mongodb';
- }
-
- /**
- * Returns the namespace to be used for this extension (XML namespace).
- *
- * @return string The XML namespace
- */
- public function getNamespace()
- {
- return 'http://symfony.com/schema/dic/doctrine/odm/mongodb';
- }
-
- /**
- * @return string
- */
- public function getXsdValidationBasePath()
- {
- return __DIR__.'/../Resources/config/schema';
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php
deleted file mode 100755
index 105267515f..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/DoctrineMongoDBBundle.php
+++ /dev/null
@@ -1,38 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle;
-
-use Symfony\Component\DependencyInjection\Compiler\PassConfig;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\HttpKernel\Bundle\Bundle;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateHydratorDirectoryPass;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\CreateProxyDirectoryPass;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Compiler\RegisterEventListenersAndSubscribersPass;
-
-/**
- * Doctrine MongoDB ODM bundle.
- *
- * @author Bulat Shakirzyanov
- * @author Kris Wallsmith
- * @author Jonathan H. Wage
- */
-class DoctrineMongoDBBundle extends Bundle
-{
- public function build(ContainerBuilder $container)
- {
- parent::build($container);
-
- $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION);
- $container->addCompilerPass(new CreateProxyDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING);
- $container->addCompilerPass(new CreateHydratorDirectoryPass(), PassConfig::TYPE_BEFORE_REMOVING);
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php
deleted file mode 100644
index 8f0d84abf0..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Logger/DoctrineMongoDBLogger.php
+++ /dev/null
@@ -1,301 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Logger;
-
-use Doctrine\MongoDB\GridFSFile;
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-
-/**
- * Logger for the Doctrine MongoDB ODM.
- *
- * The {@link logQuery()} method is configured as the logger callable in the
- * service container.
- *
- * @author Kris Wallsmith
- */
-class DoctrineMongoDBLogger
-{
- protected $logger;
-
- protected $prefix;
- protected $queries;
-
- protected $processed;
- protected $formattedQueries;
- protected $nbRealQueries;
-
- /**
- * Constructor.
- *
- * @param LoggerInterface $logger The Symfony logger
- * @param string $prefix A prefix for messages sent to the Symfony logger
- */
- public function __construct(LoggerInterface $logger = null, $prefix = 'MongoDB query: ')
- {
- $this->logger = $logger;
- $this->prefix = $prefix;
- $this->queries = array();
- $this->processed = false;
- }
-
- /**
- * Logs a query.
- *
- * This method is configured as the logger callable in the service
- * container.
- *
- * @param array $query A query log array from Doctrine
- */
- public function logQuery(array $query)
- {
- $this->queries[] = $query;
- $this->processed = false;
-
- if (null !== $this->logger) {
- $this->logger->info($this->prefix.static::bsonEncode($query));
- }
- }
-
- /**
- * Returns the number of queries that have been logged.
- *
- * @return integer The number of queries logged
- */
- public function getNbQueries()
- {
- if (!$this->processed) {
- $this->processQueries();
- }
-
- return $this->nbRealQueries;
- }
-
- /**
- * Returns a human-readable array of queries logged.
- *
- * @return array An array of queries
- */
- public function getQueries()
- {
- if (!$this->processed) {
- $this->processQueries();
- }
-
- return $this->formattedQueries;
- }
-
- /**
- * Groups and formats query arrays.
- *
- * @param array $queries An array of query arrays
- *
- * @return array An array of human-readable queries
- */
- protected function processQueries()
- {
- $this->formattedQueries = array();
- $this->nbRealQueries = 0;
-
- $grouped = array();
- $ordered = array();
- foreach ($this->queries as $query) {
- if (!isset($query['query']) || !isset($query['fields'])) {
- // no grouping necessary
- $ordered[] = array($query);
- continue;
- }
-
- $cursor = serialize($query['query']).serialize($query['fields']);
-
- // append if issued from cursor (currently just "sort")
- if (isset($query['sort'])) {
- unset($query['query'], $query['fields']);
- $grouped[$cursor][count($grouped[$cursor]) - 1][] = $query;
- } else {
- $grouped[$cursor][] = array($query);
- $ordered[] =& $grouped[$cursor][count($grouped[$cursor]) - 1];
- }
- }
-
- $i = 0;
- $db = '';
- $query = '';
- foreach ($ordered as $logs) {
- foreach ($logs as $log) {
- if (isset($log['db']) && $db != $log['db']) {
- // for readability
- $this->formattedQueries[$i++] = 'use '.$log['db'].';';
- $db = $log['db'];
- }
-
- if (isset($log['collection'])) {
- // flush the previous and start a new query
- if (!empty($query)) {
- if ('.' == $query[0]) {
- $query = 'db'.$query;
- }
-
- $this->formattedQueries[$i++] = $query.';';
- ++$this->nbRealQueries;
- }
-
- $query = 'db.'.$log['collection'];
- }
-
- // format the method call
- if (isset($log['authenticate'])) {
- $query .= '.authenticate()';
- } elseif (isset($log['batchInsert'])) {
- $query .= '.batchInsert(**'.$log['num'].' item(s)**)';
- } elseif (isset($log['command'])) {
- $query .= '.command()';
- } elseif (isset($log['count'])) {
- $query .= '.count(';
- if ($log['query'] || $log['limit'] || $log['skip']) {
- $query .= static::bsonEncode($log['query']);
- if ($log['limit'] || $log['skip']) {
- $query .= ', '.static::bsonEncode($log['limit']);
- if ($log['skip']) {
- $query .= ', '.static::bsonEncode($log['skip']);
- }
- }
- }
- $query .= ')';
- } elseif (isset($log['createCollection'])) {
- $query .= '.createCollection()';
- } elseif (isset($log['createDBRef'])) {
- $query .= '.createDBRef()';
- } elseif (isset($log['deleteIndex'])) {
- $query .= '.dropIndex('.static::bsonEncode($log['keys']).')';
- } elseif (isset($log['deleteIndexes'])) {
- $query .= '.dropIndexes()';
- } elseif (isset($log['drop'])) {
- $query .= '.drop()';
- } elseif (isset($log['dropDatabase'])) {
- $query .= '.dropDatabase()';
- } elseif (isset($log['ensureIndex'])) {
- $query .= '.ensureIndex('.static::bsonEncode($log['keys']).', '.static::bsonEncode($log['options']).')';
- } elseif (isset($log['execute'])) {
- $query .= '.execute()';
- } elseif (isset($log['find'])) {
- $query .= '.find(';
- if ($log['query'] || $log['fields']) {
- $query .= static::bsonEncode($log['query']);
- if ($log['fields']) {
- $query .= ', '.static::bsonEncode($log['fields']);
- }
- }
- $query .= ')';
- } elseif (isset($log['findOne'])) {
- $query .= '.findOne(';
- if ($log['query'] || $log['fields']) {
- $query .= static::bsonEncode($log['query']);
- if ($log['fields']) {
- $query .= ', '.static::bsonEncode($log['fields']);
- }
- }
- $query .= ')';
- } elseif (isset($log['getDBRef'])) {
- $query .= '.getDBRef()';
- } elseif (isset($log['group'])) {
- $query .= '.group('.static::bsonEncode(array(
- 'keys' => $log['keys'],
- 'initial' => $log['initial'],
- 'reduce' => $log['reduce'],
- )).')';
- } elseif (isset($log['insert'])) {
- $query .= '.insert('.static::bsonEncode($log['document']).')';
- } elseif (isset($log['remove'])) {
- $query .= '.remove('.static::bsonEncode($log['query']).')';
- } elseif (isset($log['save'])) {
- $query .= '.save('.static::bsonEncode($log['document']).')';
- } elseif (isset($log['sort'])) {
- $query .= '.sort('.static::bsonEncode($log['sortFields']).')';
- } elseif (isset($log['update'])) {
- // todo: include $log['options']
- $query .= '.update('.static::bsonEncode($log['query']).', '.static::bsonEncode($log['newObj']).')';
- } elseif (isset($log['validate'])) {
- $query .= '.validate()';
- }
- }
- }
-
- if (!empty($query)) {
- if ('.' == $query[0]) {
- $query = 'db'.$query;
- }
-
- $this->formattedQueries[$i++] = $query.';';
- ++$this->nbRealQueries;
- }
- }
-
- static protected function bsonEncode($query, $array = true)
- {
- $parts = array();
-
- foreach ($query as $key => $value) {
- if (!is_numeric($key)) {
- $array = false;
- }
-
- if (null === $value) {
- $formatted = 'null';
- } elseif (is_bool($value)) {
- $formatted = $value ? 'true' : 'false';
- } elseif (is_numeric($value)) {
- $formatted = $value;
- } elseif (is_scalar($value)) {
- $formatted = '"'.$value.'"';
- } elseif (is_array($value)) {
- $formatted = static::bsonEncode($value);
- } elseif ($value instanceof \MongoId) {
- $formatted = 'ObjectId("'.$value.'")';
- } elseif ($value instanceof \MongoDate) {
- $formatted = 'new Date("'.date('r', $value->sec).'")';
- } elseif ($value instanceof \DateTime) {
- $formatted = 'new Date("'.date('r', $value->getTimestamp()).'")';
- } elseif ($value instanceof \MongoRegex) {
- $formatted = 'new RegExp("'.$value->regex.'", "'.$value->flags.'")';
- } elseif ($value instanceof \MongoMinKey) {
- $formatted = 'new MinKey()';
- } elseif ($value instanceof \MongoMaxKey) {
- $formatted = 'new MaxKey()';
- } elseif ($value instanceof \MongoBinData) {
- $formatted = 'new BinData("'.$value->bin.'", "'.$value->type.'")';
- } elseif ($value instanceof \MongoGridFSFile || $value instanceof GridFSFile) {
- $formatted = 'new MongoGridFSFile("'.$value->getFilename().'")';
- } elseif ($value instanceof \stdClass) {
- $formatted = static::bsonEncode((array) $value);
- } else {
- $formatted = (string) $value;
- }
-
- $parts['"'.$key.'"'] = $formatted;
- }
-
- if (0 == count($parts)) {
- return $array ? '[ ]' : '{ }';
- }
-
- if ($array) {
- return '[ '.implode(', ', $parts).' ]';
- } else {
- $mapper = function($key, $value)
- {
- return $key.': '.$value;
- };
-
- return '{ '.implode(', ', array_map($mapper, array_keys($parts), array_values($parts))).' }';
- }
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml
deleted file mode 100755
index 9d8d49e6dd..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/mongodb.xml
+++ /dev/null
@@ -1,119 +0,0 @@
-
-
-
-
-
- Doctrine\MongoDB\Connection
- Doctrine\ODM\MongoDB\Configuration
- Doctrine\ODM\MongoDB\DocumentManager
- Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger
- Symfony\Bundle\DoctrineMongoDBBundle\DataCollector\DoctrineMongoDBDataCollector
- Doctrine\Common\EventManager
-
-
- Proxies
- %kernel.cache_dir%/doctrine/odm/mongodb/Proxies
- false
-
-
- Hydrators
- %kernel.cache_dir%/doctrine/odm/mongodb/Hydrators
- false
-
-
- Doctrine\Common\Cache\ArrayCache
- Doctrine\Common\Cache\ApcCache
- Doctrine\Common\Cache\MemcacheCache
- localhost
- 11211
- Memcache
- Doctrine\Common\Cache\XcacheCache
-
-
- Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain
- Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver
- Doctrine\Common\Annotations\AnnotationReader
- Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver
- Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver
-
-
-
- %doctrine.odm.mongodb.mapping_dirs%
- %doctrine.odm.mongodb.mapping_dirs%
-
-
-
- Symfony\Bundle\DoctrineMongoDBBundle\Security\DocumentUserProvider
-
-
- Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\ProxyCacheWarmer
-
-
- Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\HydratorCacheWarmer
-
-
- Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator
-
-
-
-
-
-
-
-
-
-
- %doctrine.odm.mongodb.document_dirs%
-
-
-
-
- Doctrine\ODM\MongoDB\Mapping\
- mongodb
-
-
-
- %doctrine.odm.mongodb.xml_mapping_dirs%
-
-
- %doctrine.odm.mongodb.yml_mapping_dirs%
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd b/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd
deleted file mode 100644
index f214496b5b..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/config/schema/mongodb-1.0.xsd
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig b/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig
deleted file mode 100644
index 253d9d622e..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Resources/views/Collector/mongodb.html.twig
+++ /dev/null
@@ -1,45 +0,0 @@
-{% extends 'WebProfilerBundle:Profiler:layout.html.twig' %}
-
-{% block toolbar %}
- {% set icon %}
-
- {% endset %}
- {% set text %}
- {{ collector.querycount }}
- {% endset %}
- {% include 'WebProfilerBundle:Profiler:toolbar_item.html.twig' with { 'link': profiler_url } %}
-{% endblock %}
-
-{% block menu %}
-
-
- Doctrine MongoDB
-
- {{ collector.querycount }}
-
-
-{% endblock %}
-
-{% block panel %}
- Queries
-
- {% if not collector.queries %}
-
- Query logging is disabled.
-
- {% elseif not collector.querycount %}
-
- No queries.
-
- {% else %}
-
- {% for query in collector.queries %}
- -
-
- {{ query }}
-
-
- {% endfor %}
-
- {% endif %}
-{% endblock %}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php
deleted file mode 100644
index 651c21c554..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php
+++ /dev/null
@@ -1,78 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Security;
-
-use Symfony\Component\Security\Core\User\UserInterface;
-use Symfony\Component\Security\Core\User\UserProviderInterface;
-use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
-use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
-
-class DocumentUserProvider implements UserProviderInterface
-{
- protected $class;
- protected $repository;
- protected $property;
-
- public function __construct($em, $class, $property = null)
- {
- $this->class = $class;
-
- if (false !== strpos($this->class, ':')) {
- $this->class = $em->getClassMetadata($class)->getName();
- }
-
- $this->repository = $em->getRepository($class);
- $this->property = $property;
- }
-
- /**
- * {@inheritdoc}
- */
- public function loadUserByUsername($username)
- {
- if (null !== $this->property) {
- $user = $this->repository->findOneBy(array($this->property => $username));
- } else {
- if (!$this->repository instanceof UserProviderInterface) {
- throw new \InvalidArgumentException(sprintf('The Doctrine repository "%s" must implement UserProviderInterface.', get_class($this->repository)));
- }
-
- $user = $this->repository->loadUserByUsername($username);
- }
-
- if (null === $user) {
- throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
- }
-
- return $user;
- }
-
- /**
- * {@inheritDoc}
- */
- public function loadUser(UserInterface $user)
- {
- if (!$user instanceof $this->class) {
- throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
- }
-
- return $this->loadUserByUsername($user->getUsername());
- }
-
- /**
- * {@inheritDoc}
- */
- public function supportsClass($class)
- {
- return $class === $this->class;
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php
deleted file mode 100644
index 6444c6b7b9..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/HydratorCacheWarmerTest.php
+++ /dev/null
@@ -1,97 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\CacheWarmer;
-
-use Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\HydratorCacheWarmer;
-
-class HydratorCacheWarmerTest extends \Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase
-{
- /**
- * This is not necessarily a good test, it doesn't generate any hydrators
- * because there are none in the AnnotationsBundle. However that is
- * rather a task of doctrine to test. We touch the lines here and
- * verify that the container is called correctly for the relevant information.
- *
- * @group DoctrineODMMongoDBHydrator
- */
- public function testWarmCache()
- {
- $testManager = $this->createTestDocumentManager(array(
- __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
- );
-
- $container = $this->getMock('Symfony\Component\DependencyInjection\Container');
- $container->expects($this->at(0))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.hydrator_dir'))
- ->will($this->returnValue(sys_get_temp_dir()));
- $container->expects($this->at(1))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_hydrator_classes'))
- ->will($this->returnValue(false));
- $container->expects($this->at(2))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.document_managers'))
- ->will($this->returnValue(array('default', 'foo')));
- $container->expects($this->at(3))
- ->method('get')
- ->with($this->equalTo('doctrine.odm.mongodb.default_document_manager'))
- ->will($this->returnValue($testManager));
- $container->expects($this->at(4))
- ->method('get')
- ->with($this->equalTo('doctrine.odm.mongodb.foo_document_manager'))
- ->will($this->returnValue($testManager));
-
- $cacheWarmer = new HydratorCacheWarmer($container);
- $cacheWarmer->warmUp(sys_get_temp_dir());
- }
-
- /**
- * @group DoctrineODMMongoDBHydrator
- */
- public function testSkipWhenHydratorsAreAutoGenerated()
- {
- $testManager = $this->createTestDocumentManager(array(
- __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
- );
-
- $container = $this->getMock('Symfony\Component\DependencyInjection\Container');
- $container->expects($this->at(0))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.hydrator_dir'))
- ->will($this->returnValue(sys_get_temp_dir()));
- $container->expects($this->at(1))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_hydrator_classes'))
- ->will($this->returnValue(true));
- $container->expects($this->at(2))
- ->method('getParameter')
- ->with($this->equalTo('assertion'))
- ->will($this->returnValue(true));
-
- $cacheWarmer = new HydratorCacheWarmer($container);
- $cacheWarmer->warmUp(sys_get_temp_dir());
-
- $container->getParameter('assertion'); // check that the assertion is really the third call.
- }
-
- /**
- * @group DoctrineODMMongoDBHydrator
- */
- public function testHydratorCacheWarmingIsNotOptional()
- {
- $container = $this->getMock('Symfony\Component\DependencyInjection\Container');
- $cacheWarmer = new HydratorCacheWarmer($container);
-
- $this->assertFalse($cacheWarmer->isOptional());
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php
deleted file mode 100644
index 9184b2f35b..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/CacheWarmer/ProxyCacheWarmerTest.php
+++ /dev/null
@@ -1,97 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\CacheWarmer;
-
-use Symfony\Bundle\DoctrineMongoDBBundle\CacheWarmer\ProxyCacheWarmer;
-
-class ProxyCacheWarmerTest extends \Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase
-{
- /**
- * This is not necessarily a good test, it doesn't generate any proxies
- * because there are none in the AnnotationsBundle. However that is
- * rather a task of doctrine to test. We touch the lines here and
- * verify that the container is called correctly for the relevant information.
- *
- * @group DoctrineODMMongoDBProxy
- */
- public function testWarmCache()
- {
- $testManager = $this->createTestDocumentManager(array(
- __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
- );
-
- $container = $this->getMock('Symfony\Component\DependencyInjection\Container');
- $container->expects($this->at(0))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.proxy_dir'))
- ->will($this->returnValue(sys_get_temp_dir()));
- $container->expects($this->at(1))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_proxy_classes'))
- ->will($this->returnValue(false));
- $container->expects($this->at(2))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.document_managers'))
- ->will($this->returnValue(array('default', 'foo')));
- $container->expects($this->at(3))
- ->method('get')
- ->with($this->equalTo('doctrine.odm.mongodb.default_document_manager'))
- ->will($this->returnValue($testManager));
- $container->expects($this->at(4))
- ->method('get')
- ->with($this->equalTo('doctrine.odm.mongodb.foo_document_manager'))
- ->will($this->returnValue($testManager));
-
- $cacheWarmer = new ProxyCacheWarmer($container);
- $cacheWarmer->warmUp(sys_get_temp_dir());
- }
-
- /**
- * @group DoctrineODMMongoDBProxy
- */
- public function testSkipWhenProxiesAreAutoGenerated()
- {
- $testManager = $this->createTestDocumentManager(array(
- __DIR__ . "/../DependencyInjection/Fixtures/Bundles/AnnotationsBundle/Document")
- );
-
- $container = $this->getMock('Symfony\Component\DependencyInjection\Container');
- $container->expects($this->at(0))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.proxy_dir'))
- ->will($this->returnValue(sys_get_temp_dir()));
- $container->expects($this->at(1))
- ->method('getParameter')
- ->with($this->equalTo('doctrine.odm.mongodb.auto_generate_proxy_classes'))
- ->will($this->returnValue(true));
- $container->expects($this->at(2))
- ->method('getParameter')
- ->with($this->equalTo('assertion'))
- ->will($this->returnValue(true));
-
- $cacheWarmer = new ProxyCacheWarmer($container);
- $cacheWarmer->warmUp(sys_get_temp_dir());
-
- $container->getParameter('assertion'); // check that the assertion is really the third call.
- }
-
- /**
- * @group DoctrineODMMongoDBProxy
- */
- public function testProxyCacheWarmingIsNotOptional()
- {
- $container = $this->getMock('Symfony\Component\DependencyInjection\Container');
- $cacheWarmer = new ProxyCacheWarmer($container);
-
- $this->assertFalse($cacheWarmer->isOptional());
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php
deleted file mode 100644
index 8c79cae1fb..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/ContainerTest.php
+++ /dev/null
@@ -1,60 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension;
-use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
-
-class ContainerTest extends TestCase
-{
- public function getContainer()
- {
- require_once __DIR__.'/DependencyInjection/Fixtures/Bundles/YamlBundle/YamlBundle.php';
-
- $container = new ContainerBuilder(new ParameterBag(array(
- 'kernel.bundles' => array('YamlBundle' => 'DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\YamlBundle'),
- 'kernel.cache_dir' => sys_get_temp_dir(),
- 'kernel.debug' => false,
- )));
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $configs = array();
- $configs[] = array('connections' => array('default' => array()), 'document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))));
- $loader->load($configs, $container);
-
- return $container;
- }
-
- public function testContainer()
- {
- $container = $this->getContainer();
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->get('doctrine.odm.mongodb.metadata.chain'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', $container->get('doctrine.odm.mongodb.metadata.annotation'));
- $this->assertInstanceOf('Doctrine\Common\Annotations\AnnotationReader', $container->get('doctrine.odm.mongodb.metadata.annotation_reader'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver', $container->get('doctrine.odm.mongodb.metadata.xml'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver', $container->get('doctrine.odm.mongodb.metadata.yml'));
- $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.cache.array'));
- $this->assertInstanceOf('Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger', $container->get('doctrine.odm.mongodb.logger'));
- $this->assertInstanceOf('Symfony\Bundle\DoctrineMongoDBBundle\DataCollector\DoctrineMongoDBDataCollector', $container->get('doctrine.odm.mongodb.data_collector'));
- $this->assertInstanceOf('Doctrine\MongoDB\Connection', $container->get('doctrine.odm.mongodb.default_connection'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\Configuration', $container->get('doctrine.odm.mongodb.default_configuration'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->get('doctrine.odm.mongodb.default_metadata_driver'));
- $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.default_metadata_cache'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\DocumentManager', $container->get('doctrine.odm.mongodb.default_document_manager'));
- $this->assertInstanceOf('Doctrine\Common\Cache\ArrayCache', $container->get('doctrine.odm.mongodb.cache'));
- $this->assertInstanceOf('Doctrine\ODM\MongoDB\DocumentManager', $container->get('doctrine.odm.mongodb.document_manager'));
- $this->assertInstanceof('Doctrine\Common\EventManager', $container->get('doctrine.odm.mongodb.event_manager'));
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php
deleted file mode 100644
index 2e9febf99b..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/AbstractMongoDBExtensionTest.php
+++ /dev/null
@@ -1,362 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
-
-use Symfony\Bundle\DoctrineMongoDBBundle\Tests\TestCase;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
-use Symfony\Component\DependencyInjection\Reference;
-
-abstract class AbstractMongoDBExtensionTest extends TestCase
-{
- abstract protected function loadFromFile(ContainerBuilder $container, $file);
-
- public function testDependencyInjectionConfigurationDefaults()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
-
- $loader->load(array(array()), $container);
-
- $this->assertEquals('Doctrine\MongoDB\Connection', $container->getParameter('doctrine.odm.mongodb.connection_class'));
- $this->assertEquals('Doctrine\ODM\MongoDB\Configuration', $container->getParameter('doctrine.odm.mongodb.configuration_class'));
- $this->assertEquals('Doctrine\ODM\MongoDB\DocumentManager', $container->getParameter('doctrine.odm.mongodb.document_manager_class'));
- $this->assertEquals('Proxies', $container->getParameter('doctrine.odm.mongodb.proxy_namespace'));
- $this->assertEquals(false, $container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes'));
- $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.odm.mongodb.cache.array_class'));
- $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.odm.mongodb.cache.apc_class'));
- $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.odm.mongodb.cache.memcache_class'));
- $this->assertEquals('localhost', $container->getParameter('doctrine.odm.mongodb.cache.memcache_host'));
- $this->assertEquals('11211', $container->getParameter('doctrine.odm.mongodb.cache.memcache_port'));
- $this->assertEquals('Memcache', $container->getParameter('doctrine.odm.mongodb.cache.memcache_instance_class'));
- $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.odm.mongodb.cache.xcache_class'));
- $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain', $container->getParameter('doctrine.odm.mongodb.metadata.driver_chain_class'));
- $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.odm.mongodb.metadata.annotation_class'));
- $this->assertEquals('Doctrine\Common\Annotations\AnnotationReader', $container->getParameter('doctrine.odm.mongodb.metadata.annotation_reader_class'));
- $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver', $container->getParameter('doctrine.odm.mongodb.metadata.xml_class'));
- $this->assertEquals('Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver', $container->getParameter('doctrine.odm.mongodb.metadata.yml_class'));
-
- $this->assertEquals('Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\UniqueValidator', $container->getParameter('doctrine_odm.mongodb.validator.unique.class'));
-
- $config = array(
- 'proxy_namespace' => 'MyProxies',
- 'auto_generate_proxy_classes' => true,
- 'connections' => array('default' => array()),
- 'document_managers' => array('default' => array())
- );
- $loader->load(array($config), $container);
-
- $this->assertEquals('MyProxies', $container->getParameter('doctrine.odm.mongodb.proxy_namespace'));
- $this->assertEquals(true, $container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes'));
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
- $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
- $this->assertEquals(array(null, array(), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
- $this->assertEquals('create', $definition->getFactoryMethod());
- $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
-
- $arguments = $definition->getArguments();
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
- $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
- $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
- }
-
- public function testSingleDocumentManagerConfiguration()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
-
- $config = array(
- 'connections' => array(
- 'default' => array(
- 'server' => 'mongodb://localhost:27017',
- 'options' => array('connect' => true)
- )
- ),
- 'document_managers' => array('default' => array())
- );
- $loader->load(array($config), $container);
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
- $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
- $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
- $this->assertEquals('create', $definition->getFactoryMethod());
- $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
-
- $arguments = $definition->getArguments();
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
- $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
- $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
- }
-
- public function testLoadSimpleSingleConnection()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $this->loadFromFile($container, 'mongodb_service_simple_single_connection');
-
- $container->getCompilerPassConfig()->setOptimizationPasses(array());
- $container->getCompilerPassConfig()->setRemovingPasses(array());
- $container->compile();
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
- $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
- $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_configuration');
- $methodCalls = $definition->getMethodCalls();
- $methodNames = array_map(function($call) { return $call[0]; }, $methodCalls);
- $this->assertInternalType('integer', $pos = array_search('setDefaultDB', $methodNames));
- $this->assertEquals('mydb', $methodCalls[$pos][1][0]);
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
- $this->assertEquals('create', $definition->getFactoryMethod());
- $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
-
- $arguments = $definition->getArguments();
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
- $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
- $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
- }
-
- public function testLoadSingleConnection()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $this->loadFromFile($container, 'mongodb_service_single_connection');
-
- $container->getCompilerPassConfig()->setOptimizationPasses(array());
- $container->getCompilerPassConfig()->setRemovingPasses(array());
- $container->compile();
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_connection');
- $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
- $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.default_configuration')), $definition->getArguments());
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_document_manager');
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
- $this->assertEquals('create', $definition->getFactoryMethod());
- $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
-
- $arguments = $definition->getArguments();
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
- $this->assertEquals('doctrine.odm.mongodb.default_connection', (string) $arguments[0]);
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
- $this->assertEquals('doctrine.odm.mongodb.default_configuration', (string) $arguments[1]);
- }
-
- public function testLoadMultipleConnections()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $this->loadFromFile($container, 'mongodb_service_multiple_connections');
-
- $container->getCompilerPassConfig()->setOptimizationPasses(array());
- $container->getCompilerPassConfig()->setRemovingPasses(array());
- $container->compile();
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.conn1_connection');
- $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
- $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.conn1_configuration')), $definition->getArguments());
-
- $this->assertEquals('doctrine.odm.mongodb.dm2_document_manager', (string) $container->getAlias('doctrine.odm.mongodb.document_manager'));
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.dm1_document_manager');
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
- $this->assertEquals('create', $definition->getFactoryMethod());
- $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
-
- $arguments = $definition->getArguments();
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
- $this->assertEquals('doctrine.odm.mongodb.conn1_connection', (string) $arguments[0]);
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
- $this->assertEquals('doctrine.odm.mongodb.dm1_configuration', (string) $arguments[1]);
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.conn2_connection');
- $this->assertEquals('%doctrine.odm.mongodb.connection_class%', $definition->getClass());
- $this->assertEquals(array('mongodb://localhost:27017', array('connect' => true), new Reference('doctrine.odm.mongodb.conn2_configuration')), $definition->getArguments());
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.dm2_document_manager');
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getClass());
- $this->assertEquals('%doctrine.odm.mongodb.document_manager_class%', $definition->getFactoryClass());
- $this->assertEquals('create', $definition->getFactoryMethod());
- $this->assertArrayHasKey('doctrine.odm.mongodb.document_manager', $definition->getTags());
-
- $arguments = $definition->getArguments();
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
- $this->assertEquals('doctrine.odm.mongodb.conn2_connection', (string) $arguments[0]);
- $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
- $this->assertEquals('doctrine.odm.mongodb.dm2_configuration', (string) $arguments[1]);
- }
-
- public function testBundleDocumentAliases()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
-
- $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))))), $container);
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_configuration');
- $calls = $definition->getMethodCalls();
- $this->assertTrue(isset($calls[0][1][0]['YamlBundle']));
- $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document', $calls[0][1][0]['YamlBundle']);
- }
-
- public function testYamlBundleMappingDetection()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension('YamlBundle');
-
- $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))))), $container);
-
- $calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls();
- $this->assertEquals('doctrine.odm.mongodb.default_yml_metadata_driver', (string) $calls[0][1][0]);
- $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\YamlBundle\Document', $calls[0][1][1]);
- }
-
- public function testXmlBundleMappingDetection()
- {
- $container = $this->getContainer('XmlBundle');
- $loader = new DoctrineMongoDBExtension();
-
- $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('XmlBundle' => array()))))), $container);
-
- $calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls();
- $this->assertEquals('doctrine.odm.mongodb.default_xml_metadata_driver', (string) $calls[0][1][0]);
- $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\XmlBundle\Document', $calls[0][1][1]);
- }
-
- public function testAnnotationsBundleMappingDetection()
- {
- $container = $this->getContainer('AnnotationsBundle');
- $loader = new DoctrineMongoDBExtension();
-
- $loader->load(array(array('document_managers' => array('default' => array('mappings' => array('AnnotationsBundle' => array()))))), $container);
-
- $calls = $container->getDefinition('doctrine.odm.mongodb.default_metadata_driver')->getMethodCalls();
- $this->assertEquals('doctrine.odm.mongodb.default_annotation_metadata_driver', (string) $calls[0][1][0]);
- $this->assertEquals('DoctrineMongoDBBundle\Tests\DependencyInjection\Fixtures\Bundles\AnnotationsBundle\Document', $calls[0][1][1]);
- }
-
- public function testDocumentManagerMetadataCacheDriverConfiguration()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $this->loadFromFile($container, 'mongodb_service_multiple_connections');
-
- $container->getCompilerPassConfig()->setOptimizationPasses(array());
- $container->getCompilerPassConfig()->setRemovingPasses(array());
- $container->compile();
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.dm1_metadata_cache');
- $this->assertEquals('%doctrine.odm.mongodb.cache.xcache_class%', $definition->getClass());
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.dm2_metadata_cache');
- $this->assertEquals('%doctrine.odm.mongodb.cache.apc_class%', $definition->getClass());
- }
-
- public function testDocumentManagerMemcacheMetadataCacheDriverConfiguration()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $this->loadFromFile($container, 'mongodb_service_simple_single_connection');
-
- $container->getCompilerPassConfig()->setOptimizationPasses(array());
- $container->getCompilerPassConfig()->setRemovingPasses(array());
- $container->compile();
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_metadata_cache');
- $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $definition->getClass());
-
- $calls = $definition->getMethodCalls();
- $this->assertEquals('setMemcache', $calls[0][0]);
- $this->assertEquals('doctrine.odm.mongodb.default_memcache_instance', (string) $calls[0][1][0]);
-
- $definition = $container->getDefinition('doctrine.odm.mongodb.default_memcache_instance');
- $this->assertEquals('Memcache', $definition->getClass());
-
- $calls = $definition->getMethodCalls();
- $this->assertEquals('connect', $calls[0][0]);
- $this->assertEquals('localhost', $calls[0][1][0]);
- $this->assertEquals(11211, $calls[0][1][1]);
- }
-
- public function testDependencyInjectionImportsOverrideDefaults()
- {
- $container = $this->getContainer();
- $loader = new DoctrineMongoDBExtension();
- $container->registerExtension($loader);
-
- $this->loadFromFile($container, 'odm_imports');
-
- $container->getCompilerPassConfig()->setOptimizationPasses(array());
- $container->getCompilerPassConfig()->setRemovingPasses(array());
- $container->compile();
-
- $this->assertTrue($container->getParameter('doctrine.odm.mongodb.auto_generate_proxy_classes'));
- }
-
- public function testRegistersValidatorNamespace()
- {
- $container = $this->getContainer();
-
- $container->setParameter('validator.annotations.namespaces', array('Namespace1\\', 'Namespace2\\'));
-
- $loader = new DoctrineMongoDBExtension();
-
- $loader->load(array(array()), $container);
-
- $this->assertEquals(array(
- 'Namespace1\\',
- 'Namespace2\\',
- 'mongodb' => 'Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints\\',
- ), $container->getParameter('validator.annotations.namespaces'));
- }
-
- protected function getContainer($bundle = 'YamlBundle')
- {
- require_once __DIR__.'/Fixtures/Bundles/'.$bundle.'/'.$bundle.'.php';
-
-
- return new ContainerBuilder(new ParameterBag(array(
- 'kernel.bundles' => array($bundle => 'DoctrineMongoDBBundle\\Tests\\DependencyInjection\\Fixtures\\Bundles\\'.$bundle.'\\'.$bundle),
- 'kernel.cache_dir' => sys_get_temp_dir(),
- 'kernel.debug' => false,
- )));
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php
deleted file mode 100644
index b566650464..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/ConfigurationTest.php
+++ /dev/null
@@ -1,283 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\Configuration;
-use Symfony\Component\Yaml\Yaml;
-use Symfony\Component\Config\Definition\Processor;
-
-class ConfigurationTest extends \PHPUnit_Framework_TestCase
-{
- public function testDefaults()
- {
- $processor = new Processor();
- $configuration = new Configuration(false);
- $options = $processor->processConfiguration($configuration, array());
-
- $defaults = array(
- 'auto_generate_hydrator_classes' => false,
- 'auto_generate_proxy_classes' => false,
- 'default_database' => 'default',
- 'document_managers' => array(),
- 'connections' => array(),
- 'proxy_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Proxies',
- 'proxy_namespace' => 'Proxies',
- 'hydrator_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators',
- 'hydrator_namespace' => 'Hydrators',
- );
-
- foreach ($defaults as $key => $default) {
- $this->assertTrue(array_key_exists($key, $options), sprintf('The default "%s" exists', $key));
- $this->assertEquals($default, $options[$key]);
-
- unset($options[$key]);
- }
-
- if (count($options)) {
- $this->fail('Extra defaults were returned: '. print_r($options, true));
- }
- }
-
- /**
- * Tests a full configuration.
- *
- * @dataProvider fullConfigurationProvider
- */
- public function testFullConfiguration($config)
- {
- $processor = new Processor();
- $configuration = new Configuration(false);
- $options = $processor->processConfiguration($configuration, array($config));
-
- $expected = array(
- 'proxy_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Proxies',
- 'proxy_namespace' => 'Test_Proxies',
- 'auto_generate_proxy_classes' => true,
- 'hydrator_dir' => '%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators',
- 'hydrator_namespace' => 'Test_Hydrators',
- 'auto_generate_hydrator_classes' => true,
- 'default_document_manager' => 'default_dm_name',
- 'default_database' => 'default_db_name',
- 'default_connection' => 'conn1',
- 'connections' => array(
- 'conn1' => array(
- 'server' => 'http://server',
- 'options' => array(
- 'connect' => true,
- 'persist' => 'persist_val',
- 'timeout' => 500,
- 'replicaSet' => true,
- 'username' => 'username_val',
- 'password' => 'password_val',
- ),
- ),
- 'conn2' => array(
- 'server' => 'http://server2',
- 'options' => array(),
- ),
- ),
- 'document_managers' => array(
- 'dm1' => array(
- 'mappings' => array(
- 'FooBundle' => array(
- 'type' => 'annotations',
- ),
- ),
- 'metadata_cache_driver' => array(
- 'type' => 'memcache',
- 'class' => 'fooClass',
- 'host' => 'host_val',
- 'port' => 1234,
- 'instance_class' => 'instance_val',
- ),
- 'logging' => false,
- ),
- 'dm2' => array(
- 'connection' => 'dm2_connection',
- 'database' => 'db1',
- 'mappings' => array(
- 'BarBundle' => array(
- 'type' => 'yml',
- 'dir' => '%kernel.cache_dir%',
- 'prefix' => 'prefix_val',
- 'alias' => 'alias_val',
- 'is_bundle' => false,
- )
- ),
- 'metadata_cache_driver' => array(
- 'type' => 'apc',
- ),
- 'logging' => true,
- )
- )
- );
-
- $this->assertEquals($expected, $options);
- }
-
- public function fullConfigurationProvider()
- {
- $yaml = Yaml::load(__DIR__.'/Fixtures/config/yml/full.yml');
- $yaml = $yaml['doctrine_mongo_db'];
-
- return array(
- array($yaml),
- );
- }
-
- /**
- * @dataProvider optionProvider
- * @param array $configs The source array of configuration arrays
- * @param array $correctValues A key-value pair of end values to check
- */
- public function testMergeOptions(array $configs, array $correctValues)
- {
- $processor = new Processor();
- $configuration = new Configuration(false);
- $options = $processor->processConfiguration($configuration, $configs);
-
- foreach ($correctValues as $key => $correctVal)
- {
- $this->assertEquals($correctVal, $options[$key]);
- }
- }
-
- public function optionProvider()
- {
- $cases = array();
-
- // single config, testing normal option setting
- $cases[] = array(
- array(
- array('default_document_manager' => 'foo'),
- ),
- array('default_document_manager' => 'foo')
- );
-
- // single config, testing normal option setting with dashes
- $cases[] = array(
- array(
- array('default-document-manager' => 'bar'),
- ),
- array('default_document_manager' => 'bar')
- );
-
- // testing the normal override merging - the later config array wins
- $cases[] = array(
- array(
- array('default_document_manager' => 'foo'),
- array('default_document_manager' => 'baz'),
- ),
- array('default_document_manager' => 'baz')
- );
-
- // the "options" array is totally replaced
- $cases[] = array(
- array(
- array('connections' => array('default' => array('options' => array('timeout' => 2000)))),
- array('connections' => array('default' => array('options' => array('username' => 'foo')))),
- ),
- array('connections' => array('default' => array('options' => array('username' => 'foo'), 'server' => null))),
- );
-
- // mappings are merged non-recursively.
- $cases[] = array(
- array(
- array('document_managers' => array('default' => array('mappings' => array('foomap' => array('type' => 'val1'), 'barmap' => array('dir' => 'val2'))))),
- array('document_managers' => array('default' => array('mappings' => array('barmap' => array('prefix' => 'val3'))))),
- ),
- array('document_managers' => array('default' => array('logging' => false, 'mappings' => array('foomap' => array('type' => 'val1'), 'barmap' => array('prefix' => 'val3'))))),
- );
-
- // connections are merged non-recursively.
- $cases[] = array(
- array(
- array('connections' => array('foocon' => array('server' => 'val1'), 'barcon' => array('options' => array('username' => 'val2')))),
- array('connections' => array('barcon' => array('server' => 'val3'))),
- ),
- array('connections' => array(
- 'foocon' => array('server' => 'val1', 'options' => array()),
- 'barcon' => array('server' => 'val3', 'options' => array())
- )),
- );
-
- // managers are merged non-recursively.
- $cases[] = array(
- array(
- array('document_managers' => array('foodm' => array('database' => 'val1'), 'bardm' => array('database' => 'val2'))),
- array('document_managers' => array('bardm' => array('database' => 'val3'))),
- ),
- array('document_managers' => array(
- 'foodm' => array('database' => 'val1', 'logging' => false, 'mappings' => array()),
- 'bardm' => array('database' => 'val3', 'logging' => false, 'mappings' => array()),
- )),
- );
-
- return $cases;
- }
-
- /**
- * @dataProvider getNormalizationTests
- */
- public function testNormalizeOptions(array $config, $targetKey, array $normalized)
- {
- $processor = new Processor();
- $configuration = new Configuration(false);
- $options = $processor->processConfiguration($configuration, array($config));
- $this->assertSame($normalized, $options[$targetKey]);
- }
-
- public function getNormalizationTests()
- {
- return array(
- // connection versus connections (id is the identifier)
- array(
- array('connection' => array(
- array('server' => 'mongodb://abc', 'id' => 'foo'),
- array('server' => 'mongodb://def', 'id' => 'bar'),
- )),
- 'connections',
- array(
- 'foo' => array('server' => 'mongodb://abc', 'options' => array()),
- 'bar' => array('server' => 'mongodb://def', 'options' => array()),
- ),
- ),
- // document_manager versus document_managers (id is the identifier)
- array(
- array('document_manager' => array(
- array('connection' => 'conn1', 'id' => 'foo'),
- array('connection' => 'conn2', 'id' => 'bar'),
- )),
- 'document_managers',
- array(
- 'foo' => array('connection' => 'conn1', 'logging' => false, 'mappings' => array()),
- 'bar' => array('connection' => 'conn2', 'logging' => false, 'mappings' => array()),
- ),
- ),
- // mapping configuration that's beneath a specific document manager
- array(
- array('document_manager' => array(
- array('id' => 'foo', 'connection' => 'conn1', 'mapping' => array(
- 'type' => 'xml', 'name' => 'foo-mapping'
- )),
- )),
- 'document_managers',
- array(
- 'foo' => array('connection' => 'conn1', 'mappings' => array(
- 'foo-mapping' => array('type' => 'xml'),
- ), 'logging' => false),
- ),
- ),
- );
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php
deleted file mode 100644
index 39e9f4f0a6..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/DoctrineMongoDBExtensionTest.php
+++ /dev/null
@@ -1,41 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Bundle\DoctrineMongoDBBundle\DependencyInjection\DoctrineMongoDBExtension;
-
-use Symfony\Component\Config\Definition\Processor;
-
-class DoctrineMongoDBExtensionTest extends \PHPUnit_Framework_TestCase
-{
- /**
- * @dataProvider parameterProvider
- */
- public function testParameterOverride($option, $parameter, $value)
- {
- $container = new ContainerBuilder();
- $container->setParameter('kernel.debug', false);
- $loader = new DoctrineMongoDBExtension();
- $loader->load(array(array($option => $value)), $container);
-
- $this->assertEquals($value, $container->getParameter('doctrine.odm.mongodb.'.$parameter));
- }
-
- public function parameterProvider()
- {
- return array(
- array('proxy_namespace', 'proxy_namespace', 'foo'),
- array('proxy-namespace', 'proxy_namespace', 'bar'),
- );
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php
deleted file mode 100644
index 23b96a825d..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/Bundles/AnnotationsBundle/AnnotationsBundle.php
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
- true
-
-
-
-
- true
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml
deleted file mode 100644
index 0663a9c314..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_simple_single_connection.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
-
-
- true
-
-
-
-
- Doctrine\Common\Cache\MemcacheCache
- localhost
- 11211
- Memcache
-
-
-
-
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml
deleted file mode 100644
index 0ee2ddb300..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/mongodb_service_single_connection.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
- true
-
-
-
-
-
- Doctrine\Common\Cache\MemcacheCache
- localhost
- 11211
- Memcache
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml
deleted file mode 100644
index 1e215a1635..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml
deleted file mode 100644
index b06efb4628..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/xml/odm_imports_import.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml
deleted file mode 100644
index 6ebed849a1..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/full.yml
+++ /dev/null
@@ -1,47 +0,0 @@
-doctrine_mongo_db:
- proxy_namespace: Test_Proxies
- auto_generate_proxy_classes: true
-
- hydrator_namespace: Test_Hydrators
- auto_generate_hydrator_classes: true
-
- default_document_manager: default_dm_name
- default_database: default_db_name
-
- default_connection: conn1
-
- connections:
- conn1:
- server: http://server
- options:
- connect: true
- persist: persist_val
- timeout: 500
- replicaSet: true
- username: username_val
- password: password_val
- conn2:
- server: http://server2
-
- document_managers:
- dm1:
- mappings:
- FooBundle: annotations
- metadata_cache_driver:
- type: memcache
- class: fooClass
- host: host_val
- port: 1234
- instance_class: instance_val
- dm2:
- connection: dm2_connection
- database: db1
- mappings:
- BarBundle:
- type: yml
- dir: %kernel.cache_dir%
- prefix: prefix_val
- alias: alias_val
- is_bundle: false
- metadata_cache_driver: apc
- logging: true
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml
deleted file mode 100644
index d56d9383ee..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_multiple_connections.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-doctrine_mongo_db:
- default_document_manager: dm2
- default_connection: conn2
- connections:
- conn1:
- server: mongodb://localhost:27017
- options:
- connect: true
- conn2:
- server: mongodb://localhost:27017
- options:
- connect: true
- document_managers:
- dm1:
- connection: conn1
- metadata_cache_driver: xcache
- dm2:
- connection: conn2
- metadata_cache_driver: apc
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml
deleted file mode 100644
index 4e55aa119e..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_simple_single_connection.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-doctrine_mongo_db:
- connections:
- default:
- server: mongodb://localhost:27017
- options: { connect: true }
- default_database: mydb
- document_managers:
- default:
- metadata_cache_driver:
- type: memcache
- class: Doctrine\Common\Cache\MemcacheCache
- host: localhost
- port: 11211
- instance_class: Memcache
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml
deleted file mode 100644
index 95466f9126..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/mongodb_service_single_connection.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-doctrine_mongo_db:
- connections:
- default:
- server: mongodb://localhost:27017
- options:
- connect: true
- document_managers:
- default:
- connection: default
- metadata_cache_driver:
- type: memcache
- class: Doctrine\Common\Cache\MemcacheCache
- host: localhost
- port: 11211
- instance_class: Memcache
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml
deleted file mode 100644
index e4292b8662..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-imports:
- - { resource: odm_imports_import.yml }
-
-doctrine_mongo_db:
- auto_generate_proxy_classes: true
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml
deleted file mode 100644
index 888177d921..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/Fixtures/config/yml/odm_imports_import.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-doctrine_mongo_db:
- auto_generate_proxy_classes: false
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php
deleted file mode 100644
index 00976d6bb9..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/XmlMongoDBExtensionTest.php
+++ /dev/null
@@ -1,25 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
-use Symfony\Component\Config\FileLocator;
-
-class XmlMongoDBExtensionTest extends AbstractMongoDBExtensionTest
-{
- protected function loadFromFile(ContainerBuilder $container, $file)
- {
- $loadXml = new XmlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/xml'));
- $loadXml->load($file.'.xml');
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php
deleted file mode 100644
index 2c56e63d6a..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/DependencyInjection/YamlMongoDBExtensionTest.php
+++ /dev/null
@@ -1,25 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\DependencyInjection;
-
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
-use Symfony\Component\Config\FileLocator;
-
-class YamlMongoDBExtensionTest extends AbstractMongoDBExtensionTest
-{
- protected function loadFromFile(ContainerBuilder $container, $file)
- {
- $loadYaml = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/yml'));
- $loadYaml->load($file.'.yml');
- }
-}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php
deleted file mode 100755
index 6c8b77d6ca..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Fixtures/Validator/Document.php
+++ /dev/null
@@ -1,9 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests\Logger;
-
-use Symfony\Bundle\DoctrineMongoDBBundle\Logger\DoctrineMongoDBLogger;
-
-class DoctrineMongoDBLoggerTest extends \PHPUnit_Framework_TestCase
-{
- protected $logger;
-
- protected function setUp()
- {
- $this->logger = new DoctrineMongoDBLogger();
- }
-
- /**
- * @dataProvider getQueries
- */
- public function testLogger($query, $formatted)
- {
- $this->logger->logQuery($query);
-
- $this->assertEquals($formatted, $this->logger->getQueries());
- }
-
- public function getQueries()
- {
- return array(
- // batchInsert
- array(
- array('db' => 'foo', 'collection' => 'bar', 'batchInsert' => true, 'num' => 1, 'data' => array('foo'), 'options' => array()),
- array('use foo;', 'db.bar.batchInsert(**1 item(s)**);'),
- ),
- // find
- array(
- array('db' => 'foo', 'collection' => 'bar', 'find' => true, 'query' => array('foo' => null), 'fields' => array()),
- array('use foo;', 'db.bar.find({ "foo": null });'),
- ),
- );
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php
deleted file mode 100644
index 3e14e1bb78..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/TestCase.php
+++ /dev/null
@@ -1,42 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Tests;
-
-use Doctrine\ODM\MongoDB\DocumentManager;
-use Doctrine\MongoDB\Connection;
-
-class TestCase extends \PHPUnit_Framework_TestCase
-{
- protected function setUp()
- {
- if (!class_exists('Doctrine\\ODM\\MongoDB\\Version')) {
- $this->markTestSkipped('Doctrine MongoDB ODM is not available.');
- }
- }
-
- /**
- * @return DocumentManager
- */
- protected function createTestDocumentManager($paths = array())
- {
- $config = new \Doctrine\ODM\MongoDB\Configuration();
- $config->setAutoGenerateProxyClasses(true);
- $config->setProxyDir(\sys_get_temp_dir());
- $config->setHydratorDir(\sys_get_temp_dir());
- $config->setProxyNamespace('SymfonyTests\Doctrine');
- $config->setHydratorNamespace('SymfonyTests\Doctrine');
- $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths));
- $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
-
- return DocumentManager::create(new Connection(), $config);
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php
deleted file mode 100755
index f3e0d6fae7..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Tests/Validator/Constraints/UniqueValidatorTest.php
+++ /dev/null
@@ -1,156 +0,0 @@
-classMetadata = $this->getClassMetadata();
- $this->repository = $this->getDocumentRepository();
- $this->dm = $this->getDocumentManager($this->classMetadata, $this->repository);
- $container = $this->getContainer();
- $this->validator = new UniqueValidator($container);
- }
-
- public function tearDown()
- {
- unset($this->validator, $this->dm, $this->repository, $this->classMetadata);
- }
-
- /**
- * @dataProvider getFieldsPathsValuesDocumentsAndReturns
- */
- public function testShouldValidateValidStringMappingValues($field, $path, $value, $document, $return)
- {
- $this->setFieldMapping($field, 'string');
-
- $this->repository->expects($this->once())
- ->method('findOneBy')
- ->with(array($path => $value))
- ->will($this->returnValue($return));
-
- $this->assertTrue($this->validator->isValid($document, new Unique($path)));
- }
-
- public function getFieldsPathsValuesDocumentsAndReturns()
- {
- $field = 'unique';
- $path = $field;
- $value = 'someUniqueValueToBeValidated';
- $document = $this->getFixtureDocument($field, $value);
-
- return array(
- array('unique', 'unique', 'someUniqueValueToBeValidated', $document, null),
- array('unique', 'unique', 'someUniqueValueToBeValidated', $document, $document),
- array('unique', 'unique', 'someUniqueValueToBeValidated', $document, $this->getFixtureDocument($field, $value)),
- );
- }
-
- /**
- * @dataProvider getFieldTypesFieldsPathsValuesAndQueries
- */
- public function testGetsCorrectQueryArrayForCollection($type, $field, $path, $value, $query)
- {
- $this->setFieldMapping($field, $type);
- $document = $this->getFixtureDocument($field, $value);
-
- $this->repository->expects($this->once())
- ->method('findOneBy')
- ->with($query);
-
- $this->validator->isValid($document, new Unique($path));
- }
-
- public function getFieldTypesFieldsPathsValuesAndQueries()
- {
- $field = 'unique';
- $key = 'uniqueValue';
- $path = $field.'.'.$key;
- $value = 'someUniqueValueToBeValidated';
-
- return array(
- array('collection', $field, $path, array($value), array($field => array('$in' => array($value)))),
- array('hash', $field, $path, array($key => $value), array($path => $value)),
- );
- }
-
- private function getContainer()
- {
- $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
-
- $container->expects($this->once())
- ->method('get')
- ->will($this->returnValue($this->dm));
-
- return $container;
- }
-
- private function getDocumentManager(ClassMetadata $classMetadata, DocumentRepository $repository)
- {
- $dm = $this->getMockBuilder('Doctrine\ODM\MongoDB\DocumentManager')
- ->disableOriginalConstructor()
- ->setMethods(array('getClassMetadata', 'getRepository'))
- ->getMock();
- $dm->expects($this->any())
- ->method('getClassMetadata')
- ->will($this->returnValue($classMetadata));
- $dm->expects($this->any())
- ->method('getRepository')
- ->will($this->returnValue($repository));
-
- return $dm;
- }
-
- protected function getDocumentRepository()
- {
- $dm = $this->getMock('Doctrine\ODM\MongoDB\DocumentRepository', array('findOneBy'), array(), '', false, false);
-
- return $dm;
- }
-
- protected function getClassMetadata()
- {
- $classMetadata = $this->getMock('Doctrine\ODM\MongoDB\Mapping\ClassMetadata', array(), array(), '', false, false);
- $classMetadata->expects($this->any())
- ->method('getFieldValue')
- ->will($this->returnCallback(function($document, $fieldName) {
- return $document->{$fieldName};
- }));
-
- $classMetadata->fieldmappings = array();
-
- return $classMetadata;
- }
-
- protected function setFieldMapping($fieldName, $type, array $attributes = array())
- {
- $this->classMetadata->fieldMappings[$fieldName] = array_merge(array(
- 'fieldName' => $fieldName,
- 'type' => $type,
- ), $attributes);
- }
-
- protected function getFixtureDocument($field, $value, $id = 1)
- {
- $document = new Document();
- $document->{$field} = $value;
- $document->id = 1;
-
- return $document;
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php
deleted file mode 100755
index 3a29894d0d..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/Unique.php
+++ /dev/null
@@ -1,56 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints;
-
-use Symfony\Component\Validator\Constraint;
-
-/**
- * Doctrine MongoDB ODM unique value constraint.
- *
- * @author Bulat Shakirzyanov
- */
-class Unique extends Constraint
-{
- public $message = 'The value for {{ property }} already exists.';
- public $path;
- public $documentManager;
-
- public function getDefaultOption()
- {
- return 'path';
- }
-
- public function getRequiredOptions()
- {
- return array('path');
- }
-
- public function validatedBy()
- {
- return 'doctrine_odm.mongodb.unique';
- }
-
- public function getTargets()
- {
- return Constraint::CLASS_CONSTRAINT;
- }
-
- public function getDocumentManagerId()
- {
- $id = 'doctrine.odm.mongodb.document_manager';
- if (null !== $this->documentManager) {
- $id = sprintf('doctrine.odm.mongodb.%s_document_manager', $this->documentManager);
- }
-
- return $id;
- }
-}
diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php
deleted file mode 100755
index 3708760971..0000000000
--- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/UniqueValidator.php
+++ /dev/null
@@ -1,138 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints;
-
-use Doctrine\ODM\MongoDB\DocumentManager;
-use Doctrine\ODM\MongoDB\Proxy\Proxy;
-use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use Symfony\Component\Validator\Constraint;
-use Symfony\Component\Validator\ConstraintValidator;
-
-/**
- * Doctrine MongoDB ODM unique value validator.
- *
- * @author Bulat Shakirzyanov
- */
-class UniqueValidator extends ConstraintValidator
-{
-
- private $container;
-
- public function __construct(ContainerInterface $container)
- {
- $this->container = $container;
- }
-
- /**
- * @param Doctrine\ODM\MongoDB\Document $value
- * @param Constraint $constraint
- * @return Boolean
- */
- public function isValid($document, Constraint $constraint)
- {
- $class = get_class($document);
- $dm = $this->getDocumentManager($constraint);
- $metadata = $dm->getClassMetadata($class);
-
- if ($metadata->isEmbeddedDocument) {
- throw new \InvalidArgumentException(sprintf("Document '%s' is an embedded document, and cannot be validated", $class));
- }
-
- $query = $this->getQueryArray($metadata, $document, $constraint->path);
-
- // check if document exists in mongodb
- if (null === ($doc = $dm->getRepository($class)->findOneBy($query))) {
- return true;
- }
-
- // check if document in mongodb is the same document as the checked one
- if ($doc === $document) {
- return true;
- }
-
- // check if returned document is proxy and initialize the minimum identifier if needed
- if ($doc instanceof Proxy) {
- $metadata->setIdentifierValue($doc, $doc->__identifier);
- }
-
- // check if document has the same identifier as the current one
- if ($metadata->getIdentifierValue($doc) === $metadata->getIdentifierValue($document)) {
- return true;
- }
-
- $this->context->setPropertyPath($this->context->getPropertyPath() . '.' . $constraint->path);
- $this->setMessage($constraint->message, array(
- '{{ property }}' => $constraint->path,
- ));
- return false;
- }
-
- protected function getQueryArray(ClassMetadata $metadata, $document, $path)
- {
- $class = $metadata->name;
- $field = $this->getFieldNameFromPropertyPath($path);
- if (!isset($metadata->fieldMappings[$field])) {
- throw new \LogicException('Mapping for \'' . $path . '\' doesn\'t exist for ' . $class);
- }
- $mapping = $metadata->fieldMappings[$field];
- if (isset($mapping['reference']) && $mapping['reference']) {
- throw new \LogicException('Cannot determine uniqueness of referenced document values');
- }
- switch ($mapping['type']) {
- case 'one':
- // TODO: implement support for embed one documents
- case 'many':
- // TODO: implement support for embed many documents
- throw new \RuntimeException('Not Implemented.');
- case 'hash':
- $value = $metadata->getFieldValue($document, $mapping['fieldName']);
- return array($path => $this->getFieldValueRecursively($path, $value));
- case 'collection':
- return array($mapping['fieldName'] => array('$in' => $metadata->getFieldValue($document, $mapping['fieldName'])));
- default:
- return array($mapping['fieldName'] => $metadata->getFieldValue($document, $mapping['fieldName']));
- }
- }
-
- /**
- * Returns the actual document field value
- *
- * E.g. document.someVal -> document
- * user.emails -> user
- * username -> username
- *
- * @param string $field
- * @return string
- */
- private function getFieldNameFromPropertyPath($field)
- {
- $pieces = explode('.', $field);
- return $pieces[0];
- }
-
- private function getFieldValueRecursively($fieldName, $value)
- {
- $pieces = explode('.', $fieldName);
- unset($pieces[0]);
- foreach ($pieces as $piece) {
- $value = $value[$piece];
- }
- return $value;
- }
-
- private function getDocumentManager(Unique $constraint)
- {
- return $this->container->get($constraint->getDocumentManagerId());
- }
-
-}
diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php
index 22263594b4..b8a142f03c 100644
--- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php
+++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php
@@ -91,8 +91,8 @@ class TemplatePathsCacheWarmer extends CacheWarmer
$template = $this->parser->parseFromFilename($file->getRelativePathname());
if (false !== $template) {
if (null !== $bundle) {
- $template->set('bundle', $bundle);
- }
+ $template->set('bundle', $bundle);
+ }
$templates[$template->getSignature()] = $this->locator->locate($template);
}
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Client.php b/src/Symfony/Bundle/FrameworkBundle/Client.php
index 91b4b63cf6..9329c21b63 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Client.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Client.php
@@ -14,8 +14,6 @@ namespace Symfony\Bundle\FrameworkBundle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Client as BaseClient;
-use Symfony\Component\BrowserKit\History;
-use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\HttpKernel\Profiler\Profiler as HttpProfiler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -27,23 +25,6 @@ use Symfony\Component\HttpFoundation\Response;
*/
class Client extends BaseClient
{
- protected $container;
-
- /**
- * Constructor.
- *
- * @param HttpKernelInterface $kernel An HttpKernelInterface instance
- * @param array $server The server parameters (equivalent of $_SERVER)
- * @param History $history A History instance to store the browser history
- * @param CookieJar $cookieJar A CookieJar instance to store the cookies
- */
- public function __construct(HttpKernelInterface $kernel, array $server = array(), History $history = null, CookieJar $cookieJar = null)
- {
- parent::__construct($kernel, $server, $history, $cookieJar);
-
- $this->container = $kernel->getContainer();
- }
-
/**
* Returns the container.
*
@@ -51,7 +32,7 @@ class Client extends BaseClient
*/
public function getContainer()
{
- return $this->container;
+ return $this->kernel->getContainer();
}
/**
@@ -71,11 +52,11 @@ class Client extends BaseClient
*/
public function getProfiler()
{
- if (!$this->container->has('profiler')) {
+ if (!$this->kernel->getContainer()->has('profiler')) {
return false;
}
- return $this->container->get('profiler')->loadFromResponse($this->response);
+ return $this->kernel->getContainer()->get('profiler')->loadFromResponse($this->response);
}
/**
@@ -87,10 +68,9 @@ class Client extends BaseClient
*/
protected function doRequest($request)
{
- $returnValue = $this->kernel->handle($request);
$this->kernel->shutdown();
- return $returnValue;
+ return $this->kernel->handle($request);
}
/**
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php
index bf1f323685..14ef5f12ca 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php
@@ -57,7 +57,7 @@ EOF
$oldCacheDir = $realCacheDir.'_old';
if (!is_writable($realCacheDir)) {
- throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $this->realCacheDir));
+ throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $realCacheDir));
}
if ($input->getOption('no-warmup')) {
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php
index 0195ff4648..8aeb8193ce 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php
@@ -49,13 +49,7 @@ The container:debug displays all configured publiccontainer:debug
-You can also search for specific services using wildcards (*):
-
- container:debug doctrine.*
-
- container:debug *event_manager
-
-To get specific information about a service, use specify its name exactly:
+To get specific information about a service, specify its name:
container:debug validator
@@ -73,20 +67,23 @@ EOF
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
- $filter = $input->getArgument('name');
+ $name = $input->getArgument('name');
$this->containerBuilder = $this->getContainerBuilder();
- $serviceIds = $this->filterServices($this->containerBuilder->getServiceIds(), $filter);
+ $serviceIds = $this->containerBuilder->getServiceIds();
- if (1 == count($serviceIds) && false === strpos($filter, '*')) {
- $this->outputService($output, $serviceIds[0]);
+ // sort so that it reads like an index of services
+ asort($serviceIds);
+
+ if ($name) {
+ $this->outputService($output, $name);
} else {
$showPrivate = $input->getOption('show-private');
- $this->outputServices($output, $serviceIds, $filter, $showPrivate);
+ $this->outputServices($output, $serviceIds, $showPrivate);
}
}
- protected function outputServices(OutputInterface $output, $serviceIds, $filter, $showPrivate = false)
+ protected function outputServices(OutputInterface $output, $serviceIds, $showPrivate = false)
{
// set the label to specify public or public+private
if ($showPrivate) {
@@ -95,9 +92,6 @@ EOF
$label = 'Public services';
}
- if ($filter) {
- $label .= sprintf(' matching %s', $filter);
- }
$output->writeln($this->getHelper('formatter')->formatSection('container', $label));
// loop through to find get space needed and filter private services
@@ -215,74 +209,4 @@ EOF
// the service has been injected in some special way, just return the service
return $this->containerBuilder->get($serviceId);
}
-
- /**
- * Filters the given array of service ids by the given string filter:
- *
- * * An exact filter, "foo", will return *only* the "foo" service
- * * A wildcard filter, "foo*", will return all services matching the wildcard
- *
- * @param array $serviceIds The array of service ids
- * @param string $filter The given filter. If ending in *, a wildcard
- * @return array
- */
- private function filterServices($serviceIds, $filter, $onlyPublic = true)
- {
- // alphabetical so that this reads like an index of services
- asort($serviceIds);
-
- if (!$filter) {
- return $serviceIds;
- }
-
- $regex = $this->buildFilterRegularExpression($filter);
- $filteredIds = array();
- foreach ($serviceIds as $serviceId) {
- if (preg_match($regex, $serviceId)) {
- $filteredIds[] = $serviceId;
- }
- }
-
- if (!$filteredIds) {
- // give a different message if the use was searching for an exact service
- if (false === strpos($filter, '*')) {
- $message = sprintf('The service "%s" does not exist.', $filter);
- } else {
- $message = sprintf('No services matched the pattern "%s"', $filter);
- }
-
- throw new \InvalidArgumentException($message);
- }
-
- return $filteredIds;
- }
-
- /**
- * Given a string with wildcards denoted as asterisks (*), this returns
- * the regular expression that can be used to match on the string.
- *
- * For example, *foo* would equate to:
- *
- * /^(.+?)*foo(.+?)*$/
- *
- * @param string $filter The raw filter
- * @return string The regular expression
- */
- private function buildFilterRegularExpression($filter)
- {
- $regex = preg_quote(str_replace('*', '', $filter));
-
- // process the "front" wildcard
- if ('*' === substr($filter, 0, 1)) {
- $regex = '(.+?)*'.$regex;
- }
-
- // process the "end" wildcard
- if ('*' === substr($filter, -1, 1)) {
- $regex .= '(.+?)*';
- }
- $regex = sprintf('/^%s$/', $regex);
-
- return $regex;
- }
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php
index b0cfe53a59..87479a0aa6 100644
--- a/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php
+++ b/src/Symfony/Bundle/FrameworkBundle/ContainerAwareEventDispatcher.php
@@ -34,7 +34,7 @@ class ContainerAwareEventDispatcher extends EventDispatcher
* The service IDs of the event listeners and subscribers
* @var array
*/
- private $listenerIds;
+ private $listenerIds = array();
/**
* Constructor.
@@ -61,9 +61,9 @@ class ContainerAwareEventDispatcher extends EventDispatcher
throw new \InvalidArgumentException('Expected a string argument');
}
- foreach ((array) $eventNames as $event) {
+ foreach ((array) $eventNames as $eventName) {
// Prevent duplicate entries
- $this->listenerIds[$event][$serviceId] = $priority;
+ $this->listenerIds[$eventName][$serviceId] = $priority;
}
}
@@ -72,6 +72,8 @@ class ContainerAwareEventDispatcher extends EventDispatcher
*
* Lazily loads listeners for this event from the dependency injection
* container.
+ *
+ * @throws \InvalidArgumentException if the service is not defined
*/
public function dispatch($eventName, Event $event = null)
{
diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php
index 81d40ce8da..40f9a729b2 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php
@@ -51,23 +51,43 @@ class RedirectController extends ContainerAware
/**
* Redirects to a URL.
*
- * It expects a url path parameter.
* By default, the response status code is 301.
*
- * If the url is empty, the status code will be 410.
- * If the permanent path parameter is set, the status code will be 302.
+ * If the path is empty, the status code will be 410.
+ * If the permanent flag is set, the status code will be 302.
*
- * @param string $url The url to redirect to
+ * @param string $path The path to redirect to
* @param Boolean $permanent Whether the redirect is permanent or not
+ * @param Boolean $scheme The URL scheme (null to keep the current one)
+ * @param integer $httpPort The HTTP port
+ * @param integer $httpsPort The HTTPS port
*
* @return Response A Response instance
*/
- public function urlRedirectAction($url, $permanent = false)
+ public function urlRedirectAction($path, $permanent = false, $scheme = null, $httpPort = 80, $httpsPort = 443)
{
- if (!$url) {
+ if (!$path) {
return new Response(null, 410);
}
+ $request = $this->container->get('request');
+ if (null === $scheme) {
+ $scheme = $request->getScheme();
+ }
+ $qs = $request->getQueryString();
+ if ($qs) {
+ $qs = '?'.$qs;
+ }
+
+ $port = '';
+ if ('http' === $scheme && 80 != $httpPort) {
+ $port = ':'.$httpPort;
+ } elseif ('https' === $scheme && 443 != $httpPort) {
+ $port = ':'.$httpsPort;
+ }
+
+ $url = $scheme.'://'.$request->getHttpHost().$port.$request->getBaseUrl().$path.$qs;
+
return new RedirectResponse($url, $permanent ? 301 : 302);
}
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php b/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php
index 9e4ab42ac2..9fa355055d 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Debug/TraceableEventDispatcher.php
@@ -124,10 +124,10 @@ class TraceableEventDispatcher extends ContainerAwareEventDispatcher implements
/**
* Returns information about the listener
- *
+ *
* @param object $listener The listener
* @param string $eventName The event name
- *
+ *
* @return array Informations about the listener
*/
private function getListenerInfo($listener, $eventName)
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php
index b69e79a159..170c33e360 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddCacheWarmerPass.php
@@ -41,7 +41,7 @@ class AddCacheWarmerPass implements CompilerPassInterface
krsort($warmers);
$warmers = call_user_func_array('array_merge', $warmers);
- $container->getDefinition('cache_warmer')->setArgument(0, $warmers);
+ $container->getDefinition('cache_warmer')->replaceArgument(0, $warmers);
if ('full' === $container->getParameter('kernel.cache_warmup')) {
$container->getDefinition('cache_warmer')->addMethodCall('enableOptionalWarmers', array());
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php
index 574282ea34..99ee9d6280 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php
@@ -29,6 +29,6 @@ class AddConstraintValidatorsPass implements CompilerPassInterface
}
}
- $container->getDefinition('validator.validator_factory')->setArgument(1, $validators);
+ $container->getDefinition('validator.validator_factory')->replaceArgument(1, $validators);
}
}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php
new file mode 100644
index 0000000000..9d5507082b
--- /dev/null
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CompilerDebugDumpPass.php
@@ -0,0 +1,24 @@
+getCompilerLogFilename($container), false);
+ $cache->write(implode("\n", $container->getCompiler()->getLog()));
+ }
+
+ public static function getCompilerLogFilename(ContainerInterface $container)
+ {
+ $class = $container->getParameter('kernel.container_class');
+
+ return $container->getParameter('kernel.cache_dir').'/'.$class.'Compiler.log';
+ }
+}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
index b6addf9a05..b45e2d4582 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
@@ -131,6 +131,8 @@ class Configuration implements ConfigurationInterface
->scalarNode('cache_warmer')->defaultFalse()->end()
->scalarNode('resource')->isRequired()->end()
->scalarNode('type')->end()
+ ->scalarNode('http_port')->defaultValue(80)->end()
+ ->scalarNode('https_port')->defaultValue(443)->end()
->end()
->end()
->end()
@@ -195,12 +197,7 @@ class Configuration implements ConfigurationInterface
->ifTrue(function($v){ return !is_array($v); })
->then(function($v){ return array($v); })
->end()
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['value']); })
- ->then(function($v){ return $v['value']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->scalarNode('cache')->end()
->scalarNode('cache_warmer')->defaultFalse()->end()
@@ -213,13 +210,8 @@ class Configuration implements ConfigurationInterface
->beforeNormalization()
->ifTrue(function($v){ return !is_array($v); })
->then(function($v){ return array($v); })
- ->end()
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['id']); })
- ->then(function($v){ return $v['id']; })
- ->end()
->end()
+ ->prototype('scalar')->end()
->end()
->end()
->fixXmlConfig('loader')
@@ -237,18 +229,11 @@ class Configuration implements ConfigurationInterface
->arrayNode('packages')
->useAttributeAsKey('name')
->prototype('array')
- ->children()
- ->scalarNode('version')->defaultNull()->end()
- ->end()
->fixXmlConfig('base_url')
->children()
+ ->scalarNode('version')->defaultNull()->end()
->arrayNode('base_urls')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['value']); })
- ->then(function($v){ return $v['value']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->end()
->end()
@@ -300,12 +285,7 @@ class Configuration implements ConfigurationInterface
->children()
->arrayNode('namespaces')
->useAttributeAsKey('prefix')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['namespace']); })
- ->then(function($v){ return $v['namespace']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->end()
->end()
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
index bb690d064e..f2297d3f4e 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
@@ -75,12 +75,12 @@ class FrameworkExtension extends Extension
} else {
$container
->getDefinition('error_handler')->addMethodCall('register', array())
- ->setArgument(0, $config['error_handler'])
+ ->replaceArgument(0, $config['error_handler'])
;
}
}
- $container->getDefinition('exception_listener')->setArgument(0, $config['exception_controller']);
+ $container->getDefinition('exception_listener')->replaceArgument(0, $config['exception_controller']);
if (!empty($config['test'])) {
$loader->load('test.xml');
@@ -194,8 +194,8 @@ class FrameworkExtension extends Extension
$loader->load('collectors.xml');
$container->getDefinition('profiler_listener')
- ->setArgument(2, $config['only_exceptions'])
- ->setArgument(3, $config['only_master_requests'])
+ ->replaceArgument(2, $config['only_exceptions'])
+ ->replaceArgument(3, $config['only_master_requests'])
;
// Choose storage class based on the DSN
@@ -209,10 +209,10 @@ class FrameworkExtension extends Extension
}
$container->getDefinition('profiler.storage')
- ->setArgument(0, $config['dsn'])
- ->setArgument(1, $config['username'])
- ->setArgument(2, $config['password'])
- ->setArgument(3, $config['lifetime'])
+ ->replaceArgument(0, $config['dsn'])
+ ->replaceArgument(1, $config['username'])
+ ->replaceArgument(2, $config['password'])
+ ->replaceArgument(3, $config['lifetime'])
->setClass($supported[$class])
;
@@ -256,6 +256,10 @@ class FrameworkExtension extends Extension
$container->setAlias('router', 'router.cached');
}
+ $def = $container->getDefinition('request_listener');
+ $def->replaceArgument(2, $config['http_port']);
+ $def->replaceArgument(3, $config['https_port']);
+
$this->addClassesToCompile(array(
'Symfony\\Component\\Routing\\RouterInterface',
'Symfony\\Component\\Routing\\Matcher\\UrlMatcherInterface',
@@ -285,7 +289,7 @@ class FrameworkExtension extends Extension
$container->setParameter('session.class', $config['class']);
}
- $container->getDefinition('session')->setArgument(1, $config['default_locale']);
+ $container->getDefinition('session')->replaceArgument(1, $config['default_locale']);
$container->setAlias('session.storage', 'session.storage.'.$config['storage_id']);
@@ -323,7 +327,7 @@ class FrameworkExtension extends Extension
$container
->getDefinition('templating.helper.code')
- ->setArgument(0, str_replace('%', '%%', isset($links[$ide]) ? $links[$ide] : $ide))
+ ->replaceArgument(0, str_replace('%', '%%', isset($links[$ide]) ? $links[$ide] : $ide))
;
if ($container->getParameter('kernel.debug')) {
@@ -339,9 +343,9 @@ class FrameworkExtension extends Extension
}
$container
->getDefinition('templating.helper.assets')
- ->setArgument(1, isset($config['assets_base_urls']) ? $config['assets_base_urls'] : array())
- ->setArgument(2, $config['assets_version'])
- ->setArgument(3, $packages)
+ ->replaceArgument(1, isset($config['assets_base_urls']) ? $config['assets_base_urls'] : array())
+ ->replaceArgument(2, $config['assets_version'])
+ ->replaceArgument(3, $packages)
;
if (!empty($config['loaders'])) {
@@ -360,13 +364,16 @@ class FrameworkExtension extends Extension
// Wrap the existing loader with cache (must happen after loaders are registered)
$container->setDefinition('templating.loader.wrapped', $container->findDefinition('templating.loader'));
$loaderCache = $container->getDefinition('templating.loader.cache');
- $loaderCache->setArgument(1, $config['cache']);
+ $loaderCache->replaceArgument(1, $config['cache']);
$container->setDefinition('templating.loader', $loaderCache);
}
if ($config['cache_warmer']) {
- $container->getDefinition('templating.cache_warmer.template_paths')->addTag('kernel.cache_warmer');
+ $container
+ ->getDefinition('templating.cache_warmer.template_paths')
+ ->addTag('kernel.cache_warmer', array('priority' => 20))
+ ;
$container->setAlias('templating.locator', 'templating.locator.cached');
} else {
$container->setAlias('templating.locator', 'templating.locator.uncached');
@@ -403,7 +410,7 @@ class FrameworkExtension extends Extension
if (1 === count($engines)) {
$container->setAlias('templating', (string) reset($engines));
} else {
- $container->getDefinition('templating.engine.delegating')->setArgument(1, $engines);
+ $container->getDefinition('templating.engine.delegating')->replaceArgument(1, $engines);
$container->setAlias('templating', 'templating.engine.delegating');
}
}
@@ -466,12 +473,12 @@ class FrameworkExtension extends Extension
$container
->getDefinition('validator.mapping.loader.xml_files_loader')
- ->setArgument(0, $this->getValidatorXmlMappingFiles($container))
+ ->replaceArgument(0, $this->getValidatorXmlMappingFiles($container))
;
$container
->getDefinition('validator.mapping.loader.yaml_files_loader')
- ->setArgument(0, $this->getValidatorYamlMappingFiles($container))
+ ->replaceArgument(0, $this->getValidatorYamlMappingFiles($container))
;
if (isset($config['annotations'])) {
@@ -484,7 +491,7 @@ class FrameworkExtension extends Extension
// Register annotation loader
$container
->getDefinition('validator.mapping.loader.annotation_loader')
- ->setArgument(0, $namespaces)
+ ->replaceArgument(0, $namespaces)
;
$loaderChain = $container->getDefinition('validator.mapping.loader.loader_chain');
@@ -495,7 +502,7 @@ class FrameworkExtension extends Extension
if (isset($config['cache'])) {
$container->getDefinition('validator.mapping.class_metadata_factory')
- ->setArgument(1, new Reference('validator.mapping.cache.'.$config['cache']));
+ ->replaceArgument(1, new Reference('validator.mapping.cache.'.$config['cache']));
$container->setParameter(
'validator.mapping.cache.prefix',
'validator_'.md5($container->getParameter('kernel.root_dir'))
diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
index 6d4ec3dc3e..593b74f8df 100644
--- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
+++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
@@ -23,6 +23,7 @@ use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddClassesToAuto
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TranslatorPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddCacheWarmerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ContainerBuilderDebugDumpPass;
+use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CompilerDebugDumpPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\Scope;
@@ -83,6 +84,10 @@ class FrameworkBundle extends Bundle
$container->addCompilerPass(new AddClassesToAutoloadMapPass());
$container->addCompilerPass(new TranslatorPass());
$container->addCompilerPass(new AddCacheWarmerPass());
- $container->addCompilerPass(new ContainerBuilderDebugDumpPass(), PassConfig::TYPE_BEFORE_REMOVING);
+
+ if ($container->getParameter('kernel.debug')) {
+ $container->addCompilerPass(new ContainerBuilderDebugDumpPass(), PassConfig::TYPE_BEFORE_REMOVING);
+ $container->addCompilerPass(new CompilerDebugDumpPass(), PassConfig::TYPE_AFTER_REMOVING);
+ }
}
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php b/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php
index c06fcd7ded..dcde0d34df 100644
--- a/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php
+++ b/src/Symfony/Bundle/FrameworkBundle/HttpKernel.php
@@ -169,7 +169,7 @@ class HttpKernel extends BaseHttpKernel
'controller' => $controller,
'path' => $attributes ? http_build_query($attributes) : 'none',
'_format' => $this->container->get('request')->getRequestFormat(),
- ), true);
+ ));
if ($query) {
$uri = $uri.'?'.http_build_query($query);
diff --git a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php
index 04fb40a424..ac68a2e57c 100644
--- a/src/Symfony/Bundle/FrameworkBundle/RequestListener.php
+++ b/src/Symfony/Bundle/FrameworkBundle/RequestListener.php
@@ -21,6 +21,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
use Symfony\Component\Routing\RouterInterface;
+use Symfony\Component\Routing\RequestContext;
/**
* RequestListener.
@@ -29,14 +30,18 @@ use Symfony\Component\Routing\RouterInterface;
*/
class RequestListener
{
- protected $router;
- protected $logger;
- protected $container;
+ private $router;
+ private $logger;
+ private $container;
+ private $httpPort;
+ private $httpsPort;
- public function __construct(ContainerInterface $container, RouterInterface $router, LoggerInterface $logger = null)
+ public function __construct(ContainerInterface $container, RouterInterface $router, $httpPort = 80, $httpsPort = 443, LoggerInterface $logger = null)
{
$this->container = $container;
$this->router = $router;
+ $this->httpPort = $httpPort;
+ $this->httpsPort = $httpsPort;
$this->logger = $logger;
}
@@ -72,13 +77,20 @@ class RequestListener
if ($master) {
// set the context even if the parsing does not need to be done
// to have correct link generation
- $this->router->setContext(array(
- 'base_url' => $request->getBaseUrl(),
- 'method' => $request->getMethod(),
- 'host' => $request->getHost(),
- 'port' => $request->getPort(),
- 'is_secure' => $request->isSecure(),
- ));
+ $context = new RequestContext(
+ $request->getBaseUrl(),
+ $request->getMethod(),
+ $request->getHost(),
+ $request->getScheme(),
+ $this->httpPort,
+ $this->httpsPort
+ );
+
+ if ($session = $request->getSession()) {
+ $context->setParameter('_locale', $session->getLocale());
+ }
+
+ $this->router->setContext($context);
}
if ($request->attributes->has('_controller')) {
@@ -95,10 +107,6 @@ class RequestListener
}
$request->attributes->add($parameters);
-
- if ($locale = $request->attributes->get('_locale')) {
- $request->getSession()->setLocale($locale);
- }
} catch (NotFoundException $e) {
$message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
if (null !== $this->logger) {
@@ -112,6 +120,11 @@ class RequestListener
}
throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
}
+
+ if ($master && $locale = $request->attributes->get('_locale')) {
+ $request->getSession()->setLocale($locale);
+ $context->setParameter('_locale', $locale);
+ }
}
private function parametersToString(array $parameters)
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd
index f146f0abb2..326a4f4a87 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd
+++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd
@@ -94,7 +94,7 @@
-
+
@@ -104,10 +104,6 @@
-
-
-
-
@@ -133,7 +129,10 @@
-
-
+
+
+
+
+
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml
index 217de8192c..9fae044bd5 100755
--- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml
+++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml
@@ -31,6 +31,8 @@
+
+
diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php
index 54b65ce1ce..c08badac42 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php
@@ -19,12 +19,24 @@ use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface;
*/
class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface
{
- public function redirect($pathinfo, $route)
+ /**
+ * Redirects the user to another URL.
+ *
+ * @param string $path The path info to redirect to.
+ * @param string $route The route that matched
+ * @param string $scheme The URL scheme (null to keep the current one)
+ *
+ * @return array An array of parameters
+ */
+ public function redirect($path, $route, $scheme = null)
{
return array(
'_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction',
- 'url' => $this->context['base_url'].$pathinfo,
+ 'path' => $path,
'permanent' => true,
+ 'scheme' => $scheme,
+ 'httpPort' => $this->context->getHttpPort(),
+ 'httpsPort' => $this->context->getHttpsPort(),
'_route' => $route,
);
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php
index 4e32326379..49d8f6f51b 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/CachedTemplateLocator.php
@@ -66,9 +66,9 @@ class CachedTemplateLocator extends TemplateLocator
/**
* Returns the template path from the cache
- *
+ *
* @param TemplateReferenceInterface $template The template
- *
+ *
* @return string|null The path when it is present in the cache, false otherwise
*/
protected function getCachedTemplatePath(TemplateReferenceInterface $template)
diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php
index f7a6466b3c..9c6f48db24 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php
@@ -83,7 +83,7 @@ class TemplateNameParser extends BaseTemplateNameParser
* Convert a filename to a template.
*
* @param string $file The filename
- *
+ *
* @return TemplateReferenceInterface A template
*/
public function parseFromFilename($file)
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php
new file mode 100644
index 0000000000..ea06810311
--- /dev/null
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/ContainerAwareEventDispatcherTest.php
@@ -0,0 +1,82 @@
+getMock('Symfony\Bundle\FrameworkBundle\Tests\Service');
+
+ $service
+ ->expects($this->once())
+ ->method('onEvent')
+ ->with($event)
+ ;
+
+ $container = new Container();
+ $container->set('service.listener', $service);
+
+ $dispatcher = new ContainerAwareEventDispatcher($container);
+ $dispatcher->addListenerService('onEvent', 'service.listener');
+
+ $dispatcher->dispatch('onEvent', $event);
+ }
+
+ public function testPreventDuplicateListenerService()
+ {
+ $event = new Event();
+
+ $service = $this->getMock('Symfony\Bundle\FrameworkBundle\Tests\Service');
+
+ $service
+ ->expects($this->once())
+ ->method('onEvent')
+ ->with($event)
+ ;
+
+ $container = new Container();
+ $container->set('service.listener', $service);
+
+ $dispatcher = new ContainerAwareEventDispatcher($container);
+ $dispatcher->addListenerService('onEvent', 'service.listener', 5);
+ $dispatcher->addListenerService('onEvent', 'service.listener', 10);
+
+ $dispatcher->dispatch('onEvent', $event);
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ */
+ public function testTriggerAListenerServiceOutOfScope()
+ {
+ $service = $this->getMock('Symfony\Bundle\FrameworkBundle\Tests\Service');
+
+ $scope = new Scope('scope');
+
+ $container = new Container();
+ $container->addScope($scope);
+ $container->enterScope('scope');
+ $container->set('service.listener', $service, 'scope');
+
+ $dispatcher = new ContainerAwareEventDispatcher($container);
+ $dispatcher->addListenerService('onEvent', 'service.listener');
+
+ $container->leaveScope('scope');
+ $dispatcher->dispatch('onEvent');
+ }
+}
+
+class Service
+{
+ function onEvent(Event $e)
+ {
+ }
+}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php
index 159e999d3f..158848d2df 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php
@@ -13,14 +13,27 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
-use Symfony\Bundle\FrameworkBundle\Tests\Logger;
-use Symfony\Bundle\FrameworkBundle\Tests\Kernel;
-
-require_once __DIR__.'/../Kernel.php';
-require_once __DIR__.'/../Logger.php';
+use Symfony\Component\ClassLoader\UniversalClassLoader;
class ControllerNameParserTest extends TestCase
{
+ protected $loader;
+
+ public function setUp()
+ {
+ $this->loader = new UniversalClassLoader();
+ $this->loader->registerNamespaces(array(
+ 'TestBundle' => __DIR__.'/../Fixtures',
+ 'TestApplication' => __DIR__.'/../Fixtures',
+ ));
+ $this->loader->register();
+ }
+
+ public function tearDown()
+ {
+ spl_autoload_unregister(array($this->loader, 'loadClass'));
+ }
+
public function testParse()
{
$parser = $this->createParser();
@@ -63,10 +76,31 @@ class ControllerNameParserTest extends TestCase
private function createParser()
{
- $kernel = new Kernel();
- $kernel->boot();
- $logger = new Logger();
+ $bundles = array(
+ 'SensioFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
+ 'SensioCmsFooBundle' => array($this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle')),
+ 'FooBundle' => array($this->getBundle('TestBundle\FooBundle', 'FooBundle')),
+ 'FabpotFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
+ );
- return new ControllerNameParser($kernel, $logger);
+ $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
+ $kernel
+ ->expects($this->any())
+ ->method('getBundle')
+ ->will($this->returnCallback(function ($bundle) use ($bundles) {
+ return $bundles[$bundle];
+ }))
+ ;
+
+ return new ControllerNameParser($kernel);
+ }
+
+ private function getBundle($namespace, $name)
+ {
+ $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
+ $bundle->expects($this->any())->method('getName')->will($this->returnValue($name));
+ $bundle->expects($this->any())->method('getNamespace')->will($this->returnValue($namespace));
+
+ return $bundle;
}
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php
index 85e2c1ff37..04c39b0f62 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php
@@ -17,8 +17,6 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
-use Symfony\Bundle\FrameworkBundle\Tests\Logger;
-use Symfony\Bundle\FrameworkBundle\Tests\Kernel;
/**
* @author Marcin Sikon
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php
index e79da04999..ab6b62a8c1 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/TestBundle/TestBundle.php
@@ -4,5 +4,5 @@ namespace Symfony\Bundle\FrameworkBundle\Tests;
class TestBundle extends \Symfony\Component\HttpKernel\Bundle\Bundle
{
-
+
}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml
index 6bb8b66835..481dbfb58a 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml
@@ -2,33 +2,33 @@
-
-
-
-
-
-
-
- loader.foo
- loader.bar
-
-
- http://cdn.example.com
-
- http://images1.example.com
- http://images2.example.com
-
-
-
- http://bar1.example.com
- http://bar2.example.com
-
-
-
-
-
+
+
+
+
+
+
+
+ loader.foo
+ loader.bar
+ php
+ twig
+ http://cdn.example.com
+
+ http://images1.example.com
+ http://images2.example.com
+
+
+
+ http://bar1.example.com
+ http://bar2.example.com
+
+
+
+
+
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml
index f54fb261d3..cb088ee787 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/session_pdo.xml
@@ -2,11 +2,11 @@
-
-
-
+
+
+
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml
index 18e058aed6..8980e16a3b 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_annotations.xml
@@ -2,13 +2,13 @@
-
-
-
-
-
+
+
+ Application\Validator\Constraints\
+
+
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php
deleted file mode 100644
index cbbf78226d..0000000000
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel.php
+++ /dev/null
@@ -1,65 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\FrameworkBundle\Tests;
-
-use Symfony\Component\HttpKernel\Kernel as BaseKernel;
-use Symfony\Component\HttpKernel\Util\Filesystem;
-use Symfony\Component\ClassLoader\UniversalClassLoader;
-use Symfony\Component\Config\Loader\LoaderInterface;
-
-class Kernel extends BaseKernel
-{
- public function __construct()
- {
- $this->rootDir = sys_get_temp_dir().'/sf2_'.rand(1, 9999);
- if (!is_dir($this->rootDir)) {
- if (false === @mkdir($this->rootDir)) {
- exit(sprintf('Unable to create a temporary directory (%s)', $this->rootDir));
- }
- } elseif (!is_writable($this->rootDir)) {
- exit(sprintf('Unable to write in a temporary directory (%s)', $this->rootDir));
- }
-
- parent::__construct('env', true);
-
- $loader = new UniversalClassLoader();
- $loader->registerNamespaces(array(
- 'TestBundle' => __DIR__.'/Fixtures/',
- 'TestApplication' => __DIR__.'/Fixtures/',
- ));
- $loader->register();
- }
-
- public function __destruct()
- {
- $fs = new Filesystem();
- $fs->remove($this->rootDir);
- }
-
- public function registerBundles()
- {
- return array(
- new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
- new \TestBundle\Sensio\FooBundle\SensioFooBundle(),
- new \TestBundle\Sensio\Cms\FooBundle\SensioCmsFooBundle(),
- new \TestBundle\FooBundle\FooBundle(),
- new \TestBundle\Fabpot\FooBundle\FabpotFooBundle(),
- );
- }
-
- public function registerContainerConfiguration(LoaderInterface $loader)
- {
- $loader->load(function ($container) {
- $container->setParameter('kernel.compiled_classes', array());
- });
- }
-}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php
deleted file mode 100644
index e975d61978..0000000000
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Logger.php
+++ /dev/null
@@ -1,88 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Bundle\FrameworkBundle\Tests;
-
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
-
-class Logger implements LoggerInterface
-{
- protected $logs;
-
- public function __construct()
- {
- $this->clear();
- }
-
- public function getLogs($priority = false)
- {
- return false === $priority ? $this->logs : $this->logs[$priority];
- }
-
- public function clear()
- {
- $this->logs = array(
- 'emerg' => array(),
- 'alert' => array(),
- 'crit' => array(),
- 'err' => array(),
- 'warn' => array(),
- 'notice' => array(),
- 'info' => array(),
- 'debug' => array(),
- );
- }
-
- public function log($message, $priority)
- {
- $this->logs[$priority][] = $message;
- }
-
- public function emerg($message)
- {
- $this->log($message, 'emerg');
- }
-
- public function alert($message)
- {
- $this->log($message, 'alert');
- }
-
- public function crit($message)
- {
- $this->log($message, 'crit');
- }
-
- public function err($message)
- {
- $this->log($message, 'err');
- }
-
- public function warn($message)
- {
- $this->log($message, 'warn');
- }
-
- public function notice($message)
- {
- $this->log($message, 'notice');
- }
-
- public function info($message)
- {
- $this->log($message, 'info');
- }
-
- public function debug($message)
- {
- $this->log($message, 'debug');
- }
-}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php
index e43fc8194c..b5240021b5 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php
@@ -12,7 +12,6 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
-use Symfony\Bundle\FrameworkBundle\Tests\Kernel;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
@@ -22,9 +21,18 @@ class TemplateNameParserTest extends TestCase
protected function setUp()
{
- $kernel = new Kernel();
- $kernel->boot();
+ $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
+ $kernel
+ ->expects($this->any())
+ ->method('getBundle')
+ ->will($this->returnCallback(function ($bundle) {
+ if (in_array($bundle, array('SensioFooBundle', 'SensioCmsFooBundle', 'FooBundle'))) {
+ return true;
+ }
+ throw new \InvalidArgumentException();
+ }))
+ ;
$this->parser = new TemplateNameParser($kernel);
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php
index 32053262b2..c49010bfdc 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php
@@ -12,7 +12,6 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
-use Symfony\Bundle\FrameworkBundle\Tests\Kernel;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
class TemplateTest extends TestCase
@@ -34,7 +33,7 @@ class TemplateTest extends TestCase
{
if (!$template->get('bundle')) {
$this->assertEquals($template->getPath(), $path);
- }
+ }
}
public function getTemplateToPathProvider()
diff --git a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php
index 7df19c1b21..f957467966 100644
--- a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php
+++ b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Compiler/LoggerChannelPass.php
@@ -27,19 +27,19 @@ class LoggerChannelPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
- if (false === $container->hasDefinition('monolog.logger')) {
+ if (!$container->hasDefinition('monolog.logger')) {
return;
}
foreach ($container->findTaggedServiceIds('monolog.logger') as $id => $tags) {
foreach ($tags as $tag) {
- if (!empty ($tag['channel']) && 'app' !== $tag['channel']) {
+ if (!empty($tag['channel']) && 'app' !== $tag['channel']) {
$definition = $container->getDefinition($id);
$loggerId = sprintf('monolog.logger.%s', $tag['channel']);
$this->createLogger($tag['channel'], $loggerId, $container);
foreach ($definition->getArguments() as $index => $argument) {
if ($argument instanceof Reference && 'logger' === (string) $argument) {
- $definition->setArgument($index, new Reference($loggerId, $argument->getInvalidBehavior(), $argument->isStrict()));
+ $definition->replaceArgument($index, new Reference($loggerId, $argument->getInvalidBehavior(), $argument->isStrict()));
}
}
}
@@ -51,7 +51,7 @@ class LoggerChannelPass implements CompilerPassInterface
{
if (!in_array($channel, $this->channels)) {
$logger = new DefinitionDecorator('monolog.logger_prototype');
- $logger->setArgument(0, $channel);
+ $logger->replaceArgument(0, $channel);
$container->setDefinition($loggerId, $logger);
array_push($this->channels, $channel);
}
diff --git a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php
index 22269be9b1..a6c76a77a2 100644
--- a/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/MonologBundle/DependencyInjection/Configuration.php
@@ -96,12 +96,7 @@ class Configuration implements ConfigurationInterface
$node
->canBeUnset()
->performNoDeepMerging()
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['callback']); })
- ->then(function($v){ return $v['callback']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
;
return $node;
diff --git a/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml b/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml
index 0fb3396887..f9d84105a8 100644
--- a/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml
+++ b/src/Symfony/Bundle/MonologBundle/Resources/config/monolog.xml
@@ -17,9 +17,10 @@
-
+
app
+
diff --git a/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd b/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd
index ee58895137..8f61e3d39c 100644
--- a/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd
+++ b/src/Symfony/Bundle/MonologBundle/Resources/config/schema/monolog-1.0.xsd
@@ -10,13 +10,13 @@
-
+
-
+
@@ -34,10 +34,6 @@
-
-
-
-
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php
index 19d1319cec..a856584da4 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php
@@ -40,6 +40,6 @@ class AddSecurityVotersPass implements CompilerPassInterface
$voters = iterator_to_array($voters);
ksort($voters);
- $container->getDefinition('security.access.decision_manager')->setArgument(0, array_values($voters));
+ $container->getDefinition('security.access.decision_manager')->replaceArgument(0, array_values($voters));
}
}
\ No newline at end of file
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php
index 4cc90a3665..6884cfafff 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php
@@ -24,7 +24,7 @@ class MainConfiguration implements ConfigurationInterface
/**
* Constructor.
*
- * @param array $factories
+ * @param array $factories
*/
public function __construct(array $factories)
{
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php
index 4e91baff24..703821fdaf 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php
@@ -148,17 +148,17 @@ abstract class AbstractFactory implements SecurityFactoryInterface
{
$listenerId = $this->getListenerId();
$listener = new DefinitionDecorator($listenerId);
- $listener->setArgument(3, $id);
- $listener->setArgument(4, array_intersect_key($config, $this->options));
+ $listener->replaceArgument(3, $id);
+ $listener->replaceArgument(4, array_intersect_key($config, $this->options));
// success handler
if (isset($config['success_handler'])) {
- $listener->setArgument(5, new Reference($config['success_handler']));
+ $listener->replaceArgument(5, new Reference($config['success_handler']));
}
// failure handler
if (isset($config['failure_handler'])) {
- $listener->setArgument(6, new Reference($config['failure_handler']));
+ $listener->replaceArgument(6, new Reference($config['failure_handler']));
}
$listenerId .= '.'.$id;
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php
index 53296e5862..e23b4d52b9 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php
@@ -65,8 +65,8 @@ class FormLoginFactory extends AbstractFactory
$provider = 'security.authentication.provider.dao.'.$id;
$container
->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.dao'))
- ->setArgument(0, new Reference($userProviderId))
- ->setArgument(2, $id)
+ ->replaceArgument(0, new Reference($userProviderId))
+ ->replaceArgument(2, $id)
;
return $provider;
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php
index 8a5a17b0cf..c87f68c38f 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php
@@ -29,8 +29,8 @@ class HttpBasicFactory implements SecurityFactoryInterface
$provider = 'security.authentication.provider.dao.'.$id;
$container
->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.dao'))
- ->setArgument(0, new Reference($userProvider))
- ->setArgument(2, $id)
+ ->replaceArgument(0, new Reference($userProvider))
+ ->replaceArgument(2, $id)
;
// entry point
@@ -39,8 +39,8 @@ class HttpBasicFactory implements SecurityFactoryInterface
// listener
$listenerId = 'security.authentication.listener.basic.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.basic'));
- $listener->setArgument(2, $id);
- $listener->setArgument(3, new Reference($entryPointId));
+ $listener->replaceArgument(2, $id);
+ $listener->replaceArgument(3, new Reference($entryPointId));
return array($provider, $listenerId, $entryPointId);
}
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php
index cdeaeb43a4..2f09be07af 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpDigestFactory.php
@@ -29,8 +29,8 @@ class HttpDigestFactory implements SecurityFactoryInterface
$provider = 'security.authentication.provider.dao.'.$id;
$container
->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.dao'))
- ->setArgument(0, new Reference($userProvider))
- ->setArgument(2, $id)
+ ->replaceArgument(0, new Reference($userProvider))
+ ->replaceArgument(2, $id)
;
// entry point
@@ -39,9 +39,9 @@ class HttpDigestFactory implements SecurityFactoryInterface
// listener
$listenerId = 'security.authentication.listener.digest.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.digest'));
- $listener->setArgument(1, new Reference($userProvider));
- $listener->setArgument(2, $id);
- $listener->setArgument(3, new Reference($entryPointId));
+ $listener->replaceArgument(1, new Reference($userProvider));
+ $listener->replaceArgument(2, $id);
+ $listener->replaceArgument(3, new Reference($entryPointId));
return array($provider, $listenerId, $entryPointId);
}
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php
index 68c7c5227e..13cf66fa39 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php
@@ -35,9 +35,6 @@ class RememberMeFactory implements SecurityFactoryInterface
// remember me services
if (isset($config['token_provider'])) {
- $config['token-provider'] = $config['token_provider'];
- }
- if (isset($config['token-provider'])) {
$templateId = 'security.authentication.rememberme.services.persistent';
$rememberMeServicesId = $templateId.'.'.$id;
} else {
@@ -53,18 +50,17 @@ class RememberMeFactory implements SecurityFactoryInterface
}
$rememberMeServices = $container->setDefinition($rememberMeServicesId, new DefinitionDecorator($templateId));
- $rememberMeServices->setArgument(1, $config['key']);
- $rememberMeServices->setArgument(2, $id);
+ $rememberMeServices->replaceArgument(1, $config['key']);
+ $rememberMeServices->replaceArgument(2, $id);
- if (isset($config['token-provider'])) {
- // FIXME: make the naming assumption more flexible
+ if (isset($config['token_provider'])) {
$rememberMeServices->addMethodCall('setTokenProvider', array(
- new Reference('security.rememberme.token.provider.'.$config['token-provider'])
+ new Reference($config['token_provider'])
));
}
// remember-me options
- $rememberMeServices->setArgument(3, array_intersect_key($config, $this->options));
+ $rememberMeServices->replaceArgument(3, array_intersect_key($config, $this->options));
// attach to remember-me aware listeners
$userProviders = array();
@@ -88,12 +84,12 @@ class RememberMeFactory implements SecurityFactoryInterface
if (count($userProviders) === 0) {
throw new \RuntimeException('You must configure at least one remember-me aware listener (such as form-login) for each firewall that has remember-me enabled.');
}
- $rememberMeServices->setArgument(0, $userProviders);
+ $rememberMeServices->replaceArgument(0, $userProviders);
// remember-me listener
$listenerId = 'security.authentication.listener.rememberme.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.rememberme'));
- $listener->setArgument(1, new Reference($rememberMeServicesId));
+ $listener->replaceArgument(1, new Reference($rememberMeServicesId));
return array($authProviderId, $listenerId, $defaultEntryPoint);
}
@@ -111,7 +107,7 @@ class RememberMeFactory implements SecurityFactoryInterface
public function addConfiguration(NodeDefinition $node)
{
$builder = $node->children();
-
+
$builder
->scalarNode('key')->isRequired()->cannotBeEmpty()->end()
->scalarNode('token_provider')->end()
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php
index 87625cc2cd..d24942b672 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php
@@ -30,16 +30,16 @@ class X509Factory implements SecurityFactoryInterface
$provider = 'security.authentication.provider.pre_authenticated.'.$id;
$container
->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.pre_authenticated'))
- ->setArgument(0, new Reference($userProvider))
+ ->replaceArgument(0, new Reference($userProvider))
->addArgument($id)
;
// listener
$listenerId = 'security.authentication.listener.x509.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.x509'));
- $listener->setArgument(2, $id);
- $listener->setArgument(3, $config['user']);
- $listener->setArgument(4, $config['credentials']);
+ $listener->replaceArgument(2, $id);
+ $listener->replaceArgument(3, $config['user']);
+ $listener->replaceArgument(4, $config['credentials']);
return array($provider, $listenerId, $defaultEntryPoint);
}
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php
index 35c69b2cb1..689678cdaf 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php
@@ -62,7 +62,7 @@ class SecurityExtension extends Extension
// set some global scalars
$container->setParameter('security.access.denied_url', $config['access_denied_url']);
- $container->getDefinition('security.authentication.session_strategy')->setArgument(0, $config['session_fixation_strategy']);
+ $container->getDefinition('security.authentication.session_strategy')->replaceArgument(0, $config['session_fixation_strategy']);
$container
->getDefinition('security.access.decision_manager')
->addArgument($config['access_decision_manager']['strategy'])
@@ -138,13 +138,13 @@ class SecurityExtension extends Extension
private function createRoleHierarchy($config, ContainerBuilder $container)
{
if (!isset($config['role_hierarchy'])) {
- $container->remove('security.access.role_hierarchy_voter');
+ $container->removeDefinition('security.access.role_hierarchy_voter');
return;
}
$container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']);
- $container->remove('security.access.simple_role_voter');
+ $container->removeDefinition('security.access.simple_role_voter');
}
private function createAuthorization($config, ContainerBuilder $container)
@@ -202,12 +202,12 @@ class SecurityExtension extends Extension
$contextId = 'security.firewall.map.context.'.$name;
$context = $container->setDefinition($contextId, new DefinitionDecorator('security.firewall.context'));
$context
- ->setArgument(0, $listeners)
- ->setArgument(1, $exceptionListener)
+ ->replaceArgument(0, $listeners)
+ ->replaceArgument(1, $exceptionListener)
;
$map[$contextId] = $matcher;
}
- $mapDef->setArgument(1, $map);
+ $mapDef->replaceArgument(1, $map);
// add authentication providers to authentication manager
$authenticationProviders = array_map(function($id) {
@@ -215,7 +215,7 @@ class SecurityExtension extends Extension
}, array_values(array_unique($authenticationProviders)));
$container
->getDefinition('security.authentication.manager')
- ->setArgument(0, $authenticationProviders)
+ ->replaceArgument(0, $authenticationProviders)
;
}
@@ -263,13 +263,13 @@ class SecurityExtension extends Extension
if (isset($firewall['logout'])) {
$listenerId = 'security.logout_listener.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.logout_listener'));
- $listener->setArgument(1, $firewall['logout']['path']);
- $listener->setArgument(2, $firewall['logout']['target']);
+ $listener->replaceArgument(1, $firewall['logout']['path']);
+ $listener->replaceArgument(2, $firewall['logout']['target']);
$listeners[] = new Reference($listenerId);
// add logout success handler
if (isset($firewall['logout']['success_handler'])) {
- $listener->setArgument(3, new Reference($firewall['logout']['success_handler']));
+ $listener->replaceArgument(3, new Reference($firewall['logout']['success_handler']));
}
// add session logout handler
@@ -324,7 +324,7 @@ class SecurityExtension extends Extension
$listenerId = 'security.context_listener.'.count($this->contextListeners);
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.context_listener'));
- $listener->setArgument(2, $contextKey);
+ $listener->replaceArgument(2, $contextKey);
return $this->contextListeners[$contextKey] = $listenerId;
}
@@ -356,7 +356,7 @@ class SecurityExtension extends Extension
$listenerId = 'security.authentication.listener.anonymous.'.$id;
$container
->setDefinition($listenerId, new DefinitionDecorator('security.authentication.listener.anonymous'))
- ->setArgument(1, $firewall['anonymous']['key'])
+ ->replaceArgument(1, $firewall['anonymous']['key'])
;
$listeners[] = new Reference($listenerId);
@@ -364,7 +364,7 @@ class SecurityExtension extends Extension
$providerId = 'security.authentication.provider.anonymous.'.$id;
$container
->setDefinition($providerId, new DefinitionDecorator('security.authentication.provider.anonymous'))
- ->setArgument(0, $firewall['anonymous']['key'])
+ ->replaceArgument(0, $firewall['anonymous']['key'])
;
$authenticationProviders[] = $providerId;
@@ -496,13 +496,13 @@ class SecurityExtension extends Extension
{
$exceptionListenerId = 'security.exception_listener.'.$id;
$listener = $container->setDefinition($exceptionListenerId, new DefinitionDecorator('security.exception_listener'));
- $listener->setArgument(2, null === $defaultEntryPoint ? null : new Reference($defaultEntryPoint));
+ $listener->replaceArgument(2, null === $defaultEntryPoint ? null : new Reference($defaultEntryPoint));
// access denied handler setup
if (isset($config['access_denied_handler'])) {
- $listener->setArgument(4, new Reference($config['access_denied_handler']));
+ $listener->replaceArgument(4, new Reference($config['access_denied_handler']));
} else if (isset($config['access_denied_url'])) {
- $listener->setArgument(3, $config['access_denied_url']);
+ $listener->replaceArgument(3, $config['access_denied_url']);
}
return $exceptionListenerId;
@@ -514,10 +514,10 @@ class SecurityExtension extends Extension
$switchUserListenerId = 'security.authentication.switchuser_listener.'.$id;
$listener = $container->setDefinition($switchUserListenerId, new DefinitionDecorator('security.authentication.switchuser_listener'));
- $listener->setArgument(1, new Reference($userProvider));
- $listener->setArgument(3, $id);
- $listener->setArgument(6, $config['parameter']);
- $listener->setArgument(7, $config['role']);
+ $listener->replaceArgument(1, new Reference($userProvider));
+ $listener->replaceArgument(3, $id);
+ $listener->replaceArgument(6, $config['parameter']);
+ $listener->replaceArgument(7, $config['role']);
return $switchUserListenerId;
}
diff --git a/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php b/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php
index d038159e47..8f78d2498d 100644
--- a/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php
+++ b/src/Symfony/Bundle/SwiftmailerBundle/DataCollector/MessageDataCollector.php
@@ -25,7 +25,7 @@ class MessageDataCollector extends DataCollector
{
protected $logger;
protected $mailer;
-
+
public function __construct(\Swift_Events_SendListener $logger, \Swift_Mailer $mailer)
{
$this->logger = $logger;
@@ -51,7 +51,7 @@ class MessageDataCollector extends DataCollector
{
return $this->data['messages'];
}
-
+
public function isSpool()
{
return $this->data['isSpool'];
diff --git a/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php
index 8200c40897..ac2423ecb0 100644
--- a/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/SwiftmailerBundle/DependencyInjection/Configuration.php
@@ -36,7 +36,7 @@ class Configuration implements ConfigurationInterface
{
$this->debug = (Boolean) $debug;
}
-
+
/**
* Generates the configuration tree builder.
*
diff --git a/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php b/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php
index e5534dea31..62d72b862a 100644
--- a/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php
+++ b/src/Symfony/Bundle/SwiftmailerBundle/Logger/MessageLogger.php
@@ -53,7 +53,7 @@ class MessageLogger implements \Swift_Events_SendListener
/**
* Empty the message list
- *
+ *
*/
public function clear()
{
diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
index a4abc2c91d..643a1e9912 100644
--- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
@@ -43,12 +43,7 @@ class Configuration implements ConfigurationInterface
->fixXmlConfig('extension')
->children()
->arrayNode('extensions')
- ->prototype('scalar')
- ->beforeNormalization()
- ->ifTrue(function($v) { return is_array($v) && isset($v['id']); })
- ->then(function($v){ return $v['id']; })
- ->end()
- ->end()
+ ->prototype('scalar')->end()
->end()
->end()
;
diff --git a/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php b/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php
index 9a9709b6da..9df2baa668 100644
--- a/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php
+++ b/src/Symfony/Bundle/TwigBundle/Node/HelperNode.php
@@ -12,7 +12,7 @@
namespace Symfony\Bundle\TwigBundle\Node;
/**
- *
+ *
*
* @author Fabien Potencier
*/
diff --git a/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd b/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd
index d972068c7d..f6163abd33 100644
--- a/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd
+++ b/src/Symfony/Bundle/TwigBundle/Resources/config/schema/twig-1.0.xsd
@@ -11,7 +11,7 @@
-
+
@@ -36,10 +36,6 @@
-
-
-
-
diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml
index bd5d8bf8b3..f0355e9bb2 100644
--- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml
+++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Fixtures/xml/full.xml
@@ -12,7 +12,7 @@
3.14
-
-
+ twig.extension.debug
+ twig.extension.text
diff --git a/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php b/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php
index 42e1f81061..cb7db4fd52 100644
--- a/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php
+++ b/src/Symfony/Bundle/TwigBundle/TokenParser/IncludeTokenParser.php
@@ -14,7 +14,7 @@ namespace Symfony\Bundle\TwigBundle\TokenParser;
use Symfony\Bundle\TwigBundle\Node\IncludeNode;
/**
- *
+ *
*
* @author Fabien Potencier
*/
diff --git a/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php b/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php
index 3be5ef7e97..2217e72679 100644
--- a/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php
+++ b/src/Symfony/Bundle/WebProfilerBundle/DependencyInjection/WebProfilerExtension.php
@@ -48,8 +48,8 @@ class WebProfilerExtension extends Extension
$loader->load('toolbar.xml');
$container->getDefinition('web_profiler.debug.toolbar')
- ->setArgument(1, $config['intercept_redirects'])
- ->setArgument(2, $config['verbose'])
+ ->replaceArgument(1, $config['intercept_redirects'])
+ ->replaceArgument(2, $config['verbose'])
;
}
}
diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig
index 0df1a08c04..b3752b7729 100644
--- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig
+++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/request.html.twig
@@ -75,6 +75,18 @@
{% include 'WebProfilerBundle:Profiler:bag.html.twig' with { 'bag': collector.requestheaders } only %}
+ Request Content
+
+
+ {% if collector.content == false %}
+ Request content not available (it was retrieved as a resource).
+ {% elseif collector.content %}
+
{{ collector.content }}
+ {% else %}
+ No content
+ {% endif %}
+
+
Request Server Parameters
{% include 'WebProfilerBundle:Profiler:bag.html.twig' with { 'bag': collector.requestserver } only %}
diff --git a/src/Symfony/Component/BrowserKit/Client.php b/src/Symfony/Component/BrowserKit/Client.php
index 07b8f93690..bf8a14efd6 100644
--- a/src/Symfony/Component/BrowserKit/Client.php
+++ b/src/Symfony/Component/BrowserKit/Client.php
@@ -108,6 +108,29 @@ abstract class Client
), $server);
}
+ /**
+ * Sets single server parameter.
+ *
+ * @param string $key A key of the parameter
+ * @param string $value A value of the parameter
+ */
+ public function setServerParameter($key, $value)
+ {
+ $this->server[$key] = $value;
+ }
+
+ /**
+ * Gets single server parameter for specified key.
+ *
+ * @param string $key A key of the parameter to get
+ * @param string $default A default value when key is undefined
+ * @return string A value of the parameter
+ */
+ public function getServerParameter($key, $default = '')
+ {
+ return (isset($this->server[$key])) ? $this->server[$key] : $default;
+ }
+
/**
* Returns the History instance.
*
diff --git a/src/Symfony/Component/Config/Definition/BaseNode.php b/src/Symfony/Component/Config/Definition/BaseNode.php
index d8c51ac66c..4ba29a6aa3 100644
--- a/src/Symfony/Component/Config/Definition/BaseNode.php
+++ b/src/Symfony/Component/Config/Definition/BaseNode.php
@@ -56,8 +56,8 @@ abstract class BaseNode implements NodeInterface
/**
* Adds an equivalent value.
*
- * @param mixed $originalValue
- * @param mixed $equivalentValue
+ * @param mixed $originalValue
+ * @param mixed $equivalentValue
*/
public function addEquivalentValue($originalValue, $equivalentValue)
{
@@ -143,8 +143,8 @@ abstract class BaseNode implements NodeInterface
/**
* Merges two values together.
*
- * @param mixed $leftSide
- * @param mixed $rightSide
+ * @param mixed $leftSide
+ * @param mixed $rightSide
* @return mixed The merged value
* @throws ForbiddenOverwriteException
*/
@@ -196,7 +196,7 @@ abstract class BaseNode implements NodeInterface
/**
* Finalizes a value, applying all finalization closures.
*
- * @param mixed $value The value to finalize
+ * @param mixed $value The value to finalize
* @return mixed The finalized value
*/
public final function finalize($value)
@@ -231,7 +231,7 @@ abstract class BaseNode implements NodeInterface
* @throws InvalidTypeException when the value is invalid
*/
abstract protected function validateType($value);
-
+
/**
* Normalizes the value.
*
@@ -239,16 +239,16 @@ abstract class BaseNode implements NodeInterface
* @return mixed The normalized value
*/
abstract protected function normalizeValue($value);
-
+
/**
* Merges two values together
*
- * @param mixed $leftSide
- * @param mixed $rightSide
+ * @param mixed $leftSide
+ * @param mixed $rightSide
* @return mixed The merged value
*/
abstract protected function mergeValues($leftSide, $rightSide);
-
+
/**
* Finalizes a value
*
diff --git a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php
index ca1712f853..bede6e991b 100644
--- a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php
+++ b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php
@@ -97,7 +97,7 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
return $this;
}
-
+
/**
* Requires the node to have at least one element.
*
@@ -238,7 +238,7 @@ class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinition
/**
* Returns a node builder to be used to add children and protoype
- *
+ *
* @return NodeBuilder The node builder
*/
protected function getNodeBuilder()
diff --git a/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php b/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php
index c6eb376224..ca8d222ef2 100644
--- a/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php
+++ b/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php
@@ -96,7 +96,7 @@ class NodeBuilder implements NodeParentInterface
{
return $this->node($name, 'variable');
}
-
+
/**
* Returns the parent node.
*
@@ -154,9 +154,9 @@ class NodeBuilder implements NodeParentInterface
/**
* Returns the class name of the node definition
- *
+ *
* @param string $type The node type
- *
+ *
* @return string The node definition class name
*
* @throws \RuntimeException When the node type is not registered
diff --git a/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php b/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php
index ca2f5a8148..24f397193e 100644
--- a/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php
+++ b/src/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php
@@ -19,4 +19,3 @@ namespace Symfony\Component\Config\Definition\Builder;
interface NodeParentInterface
{
}
-
\ No newline at end of file
diff --git a/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php b/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php
index a67ed52701..2d95954239 100644
--- a/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php
+++ b/src/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php
@@ -24,4 +24,3 @@ interface ParentNodeDefinitionInterface
function setBuilder(NodeBuilder $builder);
}
-
\ No newline at end of file
diff --git a/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php b/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php
index 047235081c..3c1362a8d1 100644
--- a/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php
+++ b/src/Symfony/Component/Config/Definition/Builder/TreeBuilder.php
@@ -24,7 +24,7 @@ class TreeBuilder implements NodeParentInterface
/**
* Creates the root node.
- *
+ *
* @param string $name The name of the root node
* @param string $type The type of the root node
* @param NodeBuilder $builder A custom node builder instance
@@ -36,7 +36,7 @@ class TreeBuilder implements NodeParentInterface
public function root($name, $type = 'array', NodeBuilder $builder = null)
{
$builder = null === $builder ? new NodeBuilder() : $builder;
-
+
$this->root = $builder->node($name, $type);
$this->root->setParent($this);
@@ -56,7 +56,7 @@ class TreeBuilder implements NodeParentInterface
if (null !== $this->tree) {
return $this->tree;
}
-
+
return $this->tree = $this->root->getNode(true);
}
}
\ No newline at end of file
diff --git a/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php b/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php
index f9439fbdb2..f7da120661 100644
--- a/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php
+++ b/src/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php
@@ -37,7 +37,7 @@ class VariableNodeDefinition extends NodeDefinition
protected function createNode()
{
$node = $this->instantiateNode();
-
+
if (null !== $this->normalization) {
$node->setNormalizationClosures($this->normalization->before);
}
@@ -65,5 +65,5 @@ class VariableNodeDefinition extends NodeDefinition
return $node;
}
-
+
}
\ No newline at end of file
diff --git a/src/Symfony/Component/Config/Definition/NodeInterface.php b/src/Symfony/Component/Config/Definition/NodeInterface.php
index 33d53feb99..74f50aed58 100644
--- a/src/Symfony/Component/Config/Definition/NodeInterface.php
+++ b/src/Symfony/Component/Config/Definition/NodeInterface.php
@@ -34,21 +34,21 @@ interface NodeInterface
* @return string The node path
*/
function getPath();
-
+
/**
* Returns true when the node is required.
*
* @return Boolean If the node is required
*/
function isRequired();
-
+
/**
* Returns true when the node has a default value.
*
* @return Boolean If the node has a default value
*/
function hasDefaultValue();
-
+
/**
* Returns the default value of the node.
*
@@ -56,7 +56,7 @@ interface NodeInterface
* @throws \RuntimeException if the node has no default value
*/
function getDefaultValue();
-
+
/**
* Normalizes the supplied value.
*
@@ -64,16 +64,16 @@ interface NodeInterface
* @return mixed The normalized value
*/
function normalize($value);
-
+
/**
* Merges two values together.
*
- * @param mixed $leftSide
- * @param mixed $rightSide
+ * @param mixed $leftSide
+ * @param mixed $rightSide
* @return mixed The merged values
*/
function merge($leftSide, $rightSide);
-
+
/**
* Finalizes a value.
*
diff --git a/src/Symfony/Component/Config/Definition/Processor.php b/src/Symfony/Component/Config/Definition/Processor.php
index 3f7a7f1a43..42a184e61c 100644
--- a/src/Symfony/Component/Config/Definition/Processor.php
+++ b/src/Symfony/Component/Config/Definition/Processor.php
@@ -23,7 +23,7 @@ class Processor
*
* @param NodeInterface $configTree The node tree describing the configuration
* @param array $configs An array of configuration items to process
- *
+ *
* @return array The processed configuration
*/
public function process(NodeInterface $configTree, array $configs)
diff --git a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php
index 14d4ed9fce..64048c22ad 100644
--- a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php
+++ b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php
@@ -194,6 +194,11 @@ class PrototypedArrayNode extends ArrayNode
if ($this->removeKeyAttribute) {
unset($v[$this->keyAttribute]);
}
+
+ // if only "value" is left
+ if (1 == count($v) && isset($v['value'])) {
+ $v = $v['value'];
+ }
}
if (array_key_exists($k, $normalized)) {
diff --git a/src/Symfony/Component/Config/Loader/Loader.php b/src/Symfony/Component/Config/Loader/Loader.php
index 584b7b3734..f02110c28e 100644
--- a/src/Symfony/Component/Config/Loader/Loader.php
+++ b/src/Symfony/Component/Config/Loader/Loader.php
@@ -63,7 +63,7 @@ abstract class Loader implements LoaderInterface
*/
public function resolve($resource, $type = null)
{
-
+
if ($this->supports($resource, $type)) {
return $this;
}
@@ -76,5 +76,5 @@ abstract class Loader implements LoaderInterface
return $loader;
}
-
+
}
diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php
index 9e88575a54..1ad936321a 100644
--- a/src/Symfony/Component/Console/Application.php
+++ b/src/Symfony/Component/Console/Application.php
@@ -759,7 +759,7 @@ class Application
* Gets the name of the command based on input.
*
* @param InputInterface $input The input interface
- *
+ *
* @return string The command name
*/
protected function getCommandName(InputInterface $input)
diff --git a/src/Symfony/Component/CssSelector/Node/ClassNode.php b/src/Symfony/Component/CssSelector/Node/ClassNode.php
index 10950f90b7..b54d2f1539 100644
--- a/src/Symfony/Component/CssSelector/Node/ClassNode.php
+++ b/src/Symfony/Component/CssSelector/Node/ClassNode.php
@@ -39,7 +39,7 @@ class ClassNode implements NodeInterface
}
/**
- * {@inheritDoc}
+ * {@inheritDoc}
*/
public function __toString()
{
diff --git a/src/Symfony/Component/CssSelector/Node/ElementNode.php b/src/Symfony/Component/CssSelector/Node/ElementNode.php
index 97c96f7a9d..37e8ce0f61 100644
--- a/src/Symfony/Component/CssSelector/Node/ElementNode.php
+++ b/src/Symfony/Component/CssSelector/Node/ElementNode.php
@@ -31,7 +31,7 @@ class ElementNode implements NodeInterface
*
* @param string $namespace Namespace
* @param string $element Element
- */
+ */
public function __construct($namespace, $element)
{
$this->namespace = $namespace;
diff --git a/src/Symfony/Component/CssSelector/Node/FunctionNode.php b/src/Symfony/Component/CssSelector/Node/FunctionNode.php
index 6a1bdbcbc4..c8b0b76a59 100644
--- a/src/Symfony/Component/CssSelector/Node/FunctionNode.php
+++ b/src/Symfony/Component/CssSelector/Node/FunctionNode.php
@@ -37,7 +37,7 @@ class FunctionNode implements NodeInterface
* @param NodeInterface $selector The XPath expression
* @param string $type
* @param string $name
- * @param XPathExpr $expr
+ * @param XPathExpr $expr
*/
public function __construct($selector, $type, $name, $expr)
{
@@ -76,10 +76,10 @@ class FunctionNode implements NodeInterface
/**
* undocumented function
*
- * @param XPathExpr $xpath
- * @param mixed $expr
- * @param string $last
- * @param string $addNameTest
+ * @param XPathExpr $xpath
+ * @param mixed $expr
+ * @param string $last
+ * @param string $addNameTest
* @return XPathExpr
*/
protected function _xpath_nth_child($xpath, $expr, $last = false, $addNameTest = true)
@@ -148,8 +148,8 @@ class FunctionNode implements NodeInterface
/**
* undocumented function
*
- * @param XPathExpr $xpath
- * @param XPathExpr $expr
+ * @param XPathExpr $xpath
+ * @param XPathExpr $expr
* @return XPathExpr
*/
protected function _xpath_nth_last_child($xpath, $expr)
@@ -160,8 +160,8 @@ class FunctionNode implements NodeInterface
/**
* undocumented function
*
- * @param XPathExpr $xpath
- * @param XPathExpr $expr
+ * @param XPathExpr $xpath
+ * @param XPathExpr $expr
* @return XPathExpr
*/
protected function _xpath_nth_of_type($xpath, $expr)
@@ -176,8 +176,8 @@ class FunctionNode implements NodeInterface
/**
* undocumented function
*
- * @param XPathExpr $xpath
- * @param XPathExpr $expr
+ * @param XPathExpr $xpath
+ * @param XPathExpr $expr
* @return XPathExpr
*/
protected function _xpath_nth_last_of_type($xpath, $expr)
@@ -188,8 +188,8 @@ class FunctionNode implements NodeInterface
/**
* undocumented function
*
- * @param XPathExpr $xpath
- * @param XPathExpr $expr
+ * @param XPathExpr $xpath
+ * @param XPathExpr $expr
* @return XPathExpr
*/
protected function _xpath_contains($xpath, $expr)
@@ -211,8 +211,8 @@ class FunctionNode implements NodeInterface
/**
* undocumented function
*
- * @param XPathExpr $xpath
- * @param XPathExpr $expr
+ * @param XPathExpr $xpath
+ * @param XPathExpr $expr
* @return XPathExpr
*/
protected function _xpath_not($xpath, $expr)
@@ -229,7 +229,7 @@ class FunctionNode implements NodeInterface
/**
* Parses things like '1n+2', or 'an+b' generally, returning (a, b)
*
- * @param mixed $s
+ * @param mixed $s
* @return array
*/
protected function parseSeries($s)
diff --git a/src/Symfony/Component/CssSelector/Node/HashNode.php b/src/Symfony/Component/CssSelector/Node/HashNode.php
index 9507277c8c..54d51ee045 100644
--- a/src/Symfony/Component/CssSelector/Node/HashNode.php
+++ b/src/Symfony/Component/CssSelector/Node/HashNode.php
@@ -38,7 +38,7 @@ class HashNode implements NodeInterface
$this->id = $id;
}
- /**
+ /**
* {@inheritDoc}
*/
public function __toString()
diff --git a/src/Symfony/Component/CssSelector/Node/PseudoNode.php b/src/Symfony/Component/CssSelector/Node/PseudoNode.php
index f1988c7092..d15f0e5289 100644
--- a/src/Symfony/Component/CssSelector/Node/PseudoNode.php
+++ b/src/Symfony/Component/CssSelector/Node/PseudoNode.php
@@ -119,7 +119,7 @@ class PseudoNode implements NodeInterface
return $xpath;
}
- /**
+ /**
* Sets the XPath to be the last child.
*
* @param XPathExpr $xpath The XPath expression
diff --git a/src/Symfony/Component/DependencyInjection/Alias.php b/src/Symfony/Component/DependencyInjection/Alias.php
index 76e7624a91..c6aa80c069 100644
--- a/src/Symfony/Component/DependencyInjection/Alias.php
+++ b/src/Symfony/Component/DependencyInjection/Alias.php
@@ -31,7 +31,7 @@ class Alias
/**
* Checks if this DI Alias should be public or not.
*
- * @return boolean
+ * @return boolean
*/
public function isPublic()
{
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php
index 928ef081d5..547e11c3ee 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php
@@ -23,7 +23,7 @@ class CheckDefinitionValidityPass implements CompilerPassInterface
/**
* Processes the ContainerBuilder to validate the Definition.
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
* @throws \RuntimeException When the Definition is invalid
*/
public function process(ContainerBuilder $container)
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php
new file mode 100644
index 0000000000..55bef03c10
--- /dev/null
+++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php
@@ -0,0 +1,55 @@
+
+ */
+class CheckExceptionOnInvalidReferenceBehaviorPass implements CompilerPassInterface
+{
+ private $container;
+ private $sourceId;
+
+ public function process(ContainerBuilder $container)
+ {
+ $this->container = $container;
+
+ foreach ($container->getDefinitions() as $id => $definition) {
+ $this->sourceId = $id;
+ $this->processDefinition($definition);
+ }
+ }
+
+ private function processDefinition(Definition $definition)
+ {
+ $this->processReferences($definition->getArguments());
+ $this->processReferences($definition->getMethodCalls());
+ $this->processReferences($definition->getProperties());
+ }
+
+ private function processReferences(array $arguments)
+ {
+ foreach ($arguments as $argument) {
+ if (is_array($argument)) {
+ $this->processReferences($argument);
+ } else if ($argument instanceof Definition) {
+ $this->processDefinition($argument);
+ } else if ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) {
+ $destId = (string) $argument;
+
+ if (!$this->container->has($destId)) {
+ throw new NonExistentServiceException($destId, $this->sourceId);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php
index bf41c8470d..9158d41f68 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php
@@ -22,9 +22,8 @@ use Symfony\Component\DependencyInjection\Compiler\PassConfig;
class Compiler
{
private $passConfig;
- private $currentPass;
- private $currentStartTime;
private $log;
+ private $loggingFormatter;
private $serviceReferenceGraph;
/**
@@ -34,6 +33,7 @@ class Compiler
{
$this->passConfig = new PassConfig();
$this->serviceReferenceGraph = new ServiceReferenceGraph();
+ $this->loggingFormatter = new LoggingFormatter();
$this->log = array();
}
@@ -57,6 +57,16 @@ class Compiler
return $this->serviceReferenceGraph;
}
+ /**
+ * Returns the logging formatter which can be used by compilation passes.
+ *
+ * @return LoggingFormatter
+ */
+ public function getLoggingFormatter()
+ {
+ return $this->loggingFormatter;
+ }
+
/**
* Adds a pass to the PassConfig.
*
@@ -71,7 +81,7 @@ class Compiler
/**
* Adds a log message.
*
- * @param string $string The log message
+ * @param string $string The log message
*/
public function addLogMessage($string)
{
@@ -91,36 +101,13 @@ class Compiler
/**
* Run the Compiler and process all Passes.
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
*/
public function compile(ContainerBuilder $container)
{
+ $start = microtime(true);
foreach ($this->passConfig->getPasses() as $pass) {
- $this->startPass($pass);
$pass->process($container);
- $this->endPass($pass);
}
}
-
- /**
- * Starts an individual pass.
- *
- * @param CompilerPassInterface $pass The pass to start
- */
- private function startPass(CompilerPassInterface $pass)
- {
- $this->currentPass = $pass;
- $this->currentStartTime = microtime(true);
- }
-
- /**
- * Ends an individual pass.
- *
- * @param CompilerPassInterface $pass The compiler pass
- */
- private function endPass(CompilerPassInterface $pass)
- {
- $this->currentPass = null;
- $this->addLogMessage(sprintf('%s finished in %.3fs', get_class($pass), microtime(true) - $this->currentStartTime));
- }
}
\ No newline at end of file
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php
index 842a5b3f65..1341745119 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php
@@ -25,6 +25,9 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
{
private $repeatedPass;
private $graph;
+ private $compiler;
+ private $formatter;
+ private $currentId;
/**
* {@inheritDoc}
@@ -41,9 +44,13 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
*/
public function process(ContainerBuilder $container)
{
- $this->graph = $container->getCompiler()->getServiceReferenceGraph();
+ $this->compiler = $container->getCompiler();
+ $this->formatter = $this->compiler->getLoggingFormatter();
+ $this->graph = $this->compiler->getServiceReferenceGraph();
+
+ foreach ($container->getDefinitions() as $id => $definition) {
+ $this->currentId = $id;
- foreach ($container->getDefinitions() as $definition) {
$definition->setArguments(
$this->inlineArguments($container, $definition->getArguments())
);
@@ -75,6 +82,8 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
}
if ($this->isInlinableDefinition($container, $id, $definition = $container->getDefinition($id))) {
+ $this->compiler->addLogMessage($this->formatter->formatInlineService($this, $id, $this->currentId));
+
if (ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope()) {
$arguments[$k] = $definition;
} else {
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php
new file mode 100644
index 0000000000..af359e5d2c
--- /dev/null
+++ b/src/Symfony/Component/DependencyInjection/Compiler/LoggingFormatter.php
@@ -0,0 +1,38 @@
+
+ */
+class LoggingFormatter
+{
+ public function formatRemoveService(CompilerPassInterface $pass, $id, $reason)
+ {
+ return $this->format($pass, sprintf('Removed service "%s"; reason: %s', $id, $reason));
+ }
+
+ public function formatInlineService(CompilerPassInterface $pass, $id, $target)
+ {
+ return $this->format($pass, sprintf('Inlined service "%s" to "%s".', $id, $target));
+ }
+
+ public function formatUpdateReference(CompilerPassInterface $pass, $serviceId, $oldDestId, $newDestId)
+ {
+ return $this->format($pass, sprintf('Changed reference of service "%s" previously pointing to "%s" to "%s".', $serviceId, $oldDestId, $newDestId));
+ }
+
+ public function formatResolveInheritance(CompilerPassInterface $pass, $childId, $parentId)
+ {
+ return $this->format($pass, sprintf('Resolving inheritance for "%s" (parent: %s).', $childId, $parentId));
+ }
+
+ public function format(CompilerPassInterface $pass, $message)
+ {
+ return sprintf('%s: %s', get_class($pass), $message);
+ }
+}
\ No newline at end of file
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php b/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php
index b340c38616..fc48e0b25f 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php
@@ -66,6 +66,7 @@ class PassConfig
new AnalyzeServiceReferencesPass(),
new RemoveUnusedDefinitionsPass(),
)),
+ new CheckExceptionOnInvalidReferenceBehaviorPass(),
);
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php
index 91882ac942..45857a1712 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveAbstractDefinitionsPass.php
@@ -13,13 +13,17 @@ class RemoveAbstractDefinitionsPass implements CompilerPassInterface
/**
* Removes abstract definitions from the ContainerBuilder
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
+ $compiler = $container->getCompiler();
+ $formatter = $compiler->getLoggingFormatter();
+
foreach ($container->getDefinitions() as $id => $definition) {
if ($definition->isAbstract()) {
- $container->remove($id);
+ $container->removeDefinition($id);
+ $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'abstract'));
}
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php
index 03fb92afa0..5b7d36289f 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/RemovePrivateAliasesPass.php
@@ -25,16 +25,20 @@ class RemovePrivateAliasesPass implements CompilerPassInterface
/**
* Removes private aliases from the ContainerBuilder
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
+ $compiler = $container->getCompiler();
+ $formatter = $compiler->getLoggingFormatter();
+
foreach ($container->getAliases() as $id => $alias) {
if ($alias->isPublic()) {
continue;
}
$container->removeAlias($id);
+ $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'private alias'));
}
}
}
\ No newline at end of file
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php
index c87e790b72..7c7974e4b1 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php
@@ -36,12 +36,14 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface
/**
* Processes the ContainerBuilder to remove unused definitions.
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
* @return void
*/
public function process(ContainerBuilder $container)
{
- $graph = $container->getCompiler()->getServiceReferenceGraph();
+ $compiler = $container->getCompiler();
+ $formatter = $compiler->getLoggingFormatter();
+ $graph = $compiler->getServiceReferenceGraph();
$hasChanged = false;
foreach ($container->getDefinitions() as $id => $definition) {
@@ -70,9 +72,11 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface
if (1 === count($referencingAliases) && false === $isReferenced) {
$container->setDefinition((string) reset($referencingAliases), $definition);
$definition->setPublic(true);
- $container->remove($id);
+ $container->removeDefinition($id);
+ $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases)));
} else if (0 === count($referencingAliases) && false === $isReferenced) {
- $container->remove($id);
+ $container->removeDefinition($id);
+ $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused'));
$hasChanged = true;
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php b/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php
index 43bbdf1ca5..a737052072 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/RepeatablePassInterface.php
@@ -22,7 +22,7 @@ interface RepeatablePassInterface extends CompilerPassInterface
/**
* Sets the RepeatedPass interface.
*
- * @param RepeatedPass $repeatedPass
+ * @param RepeatedPass $repeatedPass
*/
function setRepeatedPass(RepeatedPass $repeatedPass);
}
\ No newline at end of file
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php
index 4b14337ed6..7ed16bc7ca 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/RepeatedPass.php
@@ -44,7 +44,7 @@ class RepeatedPass implements CompilerPassInterface
/**
* Process the repeatable passes that run more than once.
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
@@ -53,9 +53,6 @@ class RepeatedPass implements CompilerPassInterface
foreach ($this->passes as $pass) {
$time = microtime(true);
$pass->process($container);
- $compiler->addLogMessage(sprintf(
- '%s finished in %.3fs', get_class($pass), microtime(true) - $time
- ));
}
if ($this->repeat) {
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php
index 509e9746db..17ccc9fa13 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php
@@ -22,13 +22,20 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface
{
+ private $compiler;
+ private $formatter;
+ private $sourceId;
+
/**
* Process the Container to replace aliases with service definitions.
*
- * @param ContainerBuilder $container
+ * @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
+ $this->compiler = $container->getCompiler();
+ $this->formatter = $this->compiler->getLoggingFormatter();
+
foreach ($container->getAliases() as $id => $alias) {
$aliasId = (string) $alias;
@@ -40,7 +47,7 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface
$definition->setPublic(true);
$container->setDefinition($id, $definition);
- $container->remove($aliasId);
+ $container->removeDefinition($aliasId);
$this->updateReferences($container, $aliasId, $id);
@@ -67,7 +74,9 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface
}
}
- foreach ($container->getDefinitions() as $definition) {
+ foreach ($container->getDefinitions() as $id => $definition) {
+ $this->sourceId = $id;
+
$definition->setArguments(
$this->updateArgumentReferences($definition->getArguments(), $currentId, $newId)
);
@@ -75,6 +84,10 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface
$definition->setMethodCalls(
$this->updateArgumentReferences($definition->getMethodCalls(), $currentId, $newId)
);
+
+ $definition->setProperties(
+ $this->updateArgumentReferences($definition->getProperties(), $currentId, $newId)
+ );
}
}
@@ -93,6 +106,7 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface
} else if ($argument instanceof Reference) {
if ($currentId === (string) $argument) {
$arguments[$k] = new Reference($newId, $argument->getInvalidBehavior());
+ $this->compiler->addLogMessage($this->formatter->formatUpdateReference($this, $this->sourceId, $currentId, $newId));
}
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php
index a19370e1ec..ca263d3a5c 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPass.php
@@ -15,6 +15,8 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
class ResolveDefinitionTemplatesPass implements CompilerPassInterface
{
private $container;
+ private $compiler;
+ private $formatter;
/**
* Process the ContainerBuilder to replace DefinitionDecorator instances with their real Definition instances.
@@ -24,6 +26,9 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
$this->container = $container;
+ $this->compiler = $container->getCompiler();
+ $this->formatter = $this->compiler->getLoggingFormatter();
+
foreach (array_keys($container->getDefinitions()) as $id) {
// yes, we are specifically fetching the definition from the
// container to ensure we are not operating on stale data
@@ -54,6 +59,7 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface
$parentDef = $this->resolveDefinition($parent, $parentDef);
}
+ $this->compiler->addLogMessage($this->formatter->formatResolveInheritance($this, $id, $parent));
$def = new Definition();
// merge in parent definition
@@ -105,7 +111,7 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface
}
$index = (integer) substr($k, strlen('index_'));
- $def->setArgument($index, $v);
+ $def->replaceArgument($index, $v);
}
// merge properties
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php
index ce512e7d64..8eb76ddb6a 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraph.php
@@ -46,7 +46,7 @@ class ServiceReferenceGraph
*
* @param string $id The id to retrieve
* @return ServiceReferenceGraphNode The node matching the supplied identifier
- * @throws \InvalidArgumentException
+ * @throws \InvalidArgumentException
*/
public function getNode($id)
{
@@ -78,11 +78,11 @@ class ServiceReferenceGraph
/**
* Connects 2 nodes together in the Graph.
*
- * @param string $sourceId
- * @param string $sourceValue
- * @param string $destId
- * @param string $destValue
- * @param string $reference
+ * @param string $sourceId
+ * @param string $sourceValue
+ * @param string $destId
+ * @param string $destValue
+ * @param string $reference
*/
public function connect($sourceId, $sourceValue, $destId, $destValue = null, $reference = null)
{
@@ -97,8 +97,8 @@ class ServiceReferenceGraph
/**
* Creates a graph node.
*
- * @param string $id
- * @param string $value
+ * @param string $id
+ * @param string $value
* @return ServiceReferenceGraphNode
*/
private function createNode($id, $value)
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php
index b768b59bf3..6331edc22c 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphEdge.php
@@ -27,9 +27,9 @@ class ServiceReferenceGraphEdge
/**
* Constructor.
*
- * @param ServiceReferenceGraphNode $sourceNode
- * @param ServiceReferenceGraphNode $destNode
- * @param string $value
+ * @param ServiceReferenceGraphNode $sourceNode
+ * @param ServiceReferenceGraphNode $destNode
+ * @param string $value
*/
public function __construct(ServiceReferenceGraphNode $sourceNode, ServiceReferenceGraphNode $destNode, $value = null)
{
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php
index 0070781ca9..6c71683d5f 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceReferenceGraphNode.php
@@ -45,7 +45,7 @@ class ServiceReferenceGraphNode
/**
* Adds an in edge to this node.
*
- * @param ServiceReferenceGraphEdge $edge
+ * @param ServiceReferenceGraphEdge $edge
*/
public function addInEdge(ServiceReferenceGraphEdge $edge)
{
@@ -55,7 +55,7 @@ class ServiceReferenceGraphNode
/**
* Adds an out edge to this node.
*
- * @param ServiceReferenceGraphEdge $edge
+ * @param ServiceReferenceGraphEdge $edge
*/
public function addOutEdge(ServiceReferenceGraphEdge $edge)
{
diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php
index 1cd5733aaa..2a0af61409 100644
--- a/src/Symfony/Component/DependencyInjection/Container.php
+++ b/src/Symfony/Component/DependencyInjection/Container.php
@@ -11,6 +11,7 @@
namespace Symfony\Component\DependencyInjection;
+use Symfony\Component\DependencyInjection\Exception\NonExistentServiceException;
use Symfony\Component\DependencyInjection\Exception\CircularReferenceException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
@@ -237,7 +238,7 @@ class Container implements ContainerInterface
}
if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
- throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $id));
+ throw new NonExistentServiceException($id);
}
}
@@ -256,7 +257,7 @@ class Container implements ContainerInterface
}
}
- return array_merge($ids, array_keys($this->services));
+ return array_unique(array_merge($ids, array_keys($this->services)));
}
/**
diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php
index 40a2a0affd..89408969ba 100644
--- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php
+++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php
@@ -241,11 +241,11 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
}
/**
- * Removes a service.
+ * Removes a service definition.
*
* @param string $id The service identifier
*/
- public function remove($id)
+ public function removeDefinition($id)
{
unset($this->definitions[strtolower($id)]);
}
diff --git a/src/Symfony/Component/DependencyInjection/Definition.php b/src/Symfony/Component/DependencyInjection/Definition.php
index 550aa59b20..b44983d61d 100644
--- a/src/Symfony/Component/DependencyInjection/Definition.php
+++ b/src/Symfony/Component/DependencyInjection/Definition.php
@@ -205,7 +205,7 @@ class Definition
*
* @return Definition The current instance
*/
- public function setArgument($index, $argument)
+ public function replaceArgument($index, $argument)
{
if ($index < 0 || $index > count($this->arguments) - 1) {
throw new \OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d].', $index, count($this->arguments) - 1));
diff --git a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php
index 0b68b7c215..53ac89a3b6 100644
--- a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php
+++ b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php
@@ -44,7 +44,7 @@ class DefinitionDecorator extends Definition
{
return $this->changes;
}
-
+
/**
* {@inheritDoc}
*/
@@ -54,7 +54,7 @@ class DefinitionDecorator extends Definition
return parent::setClass($class);
}
-
+
/**
* {@inheritDoc}
*/
@@ -64,7 +64,7 @@ class DefinitionDecorator extends Definition
return parent::setFactoryClass($class);
}
-
+
/**
* {@inheritDoc}
*/
@@ -74,7 +74,7 @@ class DefinitionDecorator extends Definition
return parent::setFactoryMethod($method);
}
-
+
/**
* {@inheritDoc}
*/
@@ -84,7 +84,7 @@ class DefinitionDecorator extends Definition
return parent::setFactoryService($service);
}
-
+
/**
* {@inheritDoc}
*/
@@ -94,7 +94,7 @@ class DefinitionDecorator extends Definition
return parent::setConfigurator($callable);
}
-
+
/**
* {@inheritDoc}
*/
@@ -104,7 +104,7 @@ class DefinitionDecorator extends Definition
return parent::setFile($file);
}
-
+
/**
* {@inheritDoc}
*/
@@ -129,7 +129,7 @@ class DefinitionDecorator extends Definition
* @return DefinitionDecorator the current instance
* @throws \InvalidArgumentException when $index isnt an integer
*/
- public function setArgument($index, $value)
+ public function replaceArgument($index, $value)
{
if (!is_int($index)) {
throw new \InvalidArgumentException('$index must be an integer.');
diff --git a/src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php b/src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php
new file mode 100644
index 0000000000..ee42ea9972
--- /dev/null
+++ b/src/Symfony/Component/DependencyInjection/Exception/NonExistentServiceException.php
@@ -0,0 +1,38 @@
+
+ */
+class NonExistentServiceException extends InvalidArgumentException
+{
+ private $id;
+ private $sourceId;
+
+ public function __construct($id, $sourceId = null)
+ {
+ if (null === $sourceId) {
+ $msg = sprintf('You have requested a non-existent service "%s".', $id);
+ } else {
+ $msg = sprintf('The service "%s" has a dependency on a non-existent service "%s".', $sourceId, $id);
+ }
+
+ parent::__construct($msg);
+
+ $this->id = $id;
+ $this->sourceId = $sourceId;
+ }
+
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ public function getSourceId()
+ {
+ return $this->sourceId;
+ }
+}
\ No newline at end of file
diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php
index 75cc168b4d..e9590933cd 100644
--- a/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php
+++ b/src/Symfony/Component/DependencyInjection/ParameterBag/FrozenParameterBag.php
@@ -12,7 +12,7 @@
namespace Symfony\Component\DependencyInjection\ParameterBag;
/**
- *
+ *
* @author Fabien Potencier
*/
class FrozenParameterBag extends ParameterBag
diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php
index cb3de82639..75d862d5b4 100644
--- a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php
+++ b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php
@@ -12,7 +12,7 @@
namespace Symfony\Component\DependencyInjection\ParameterBag;
/**
- *
+ *
* @author Fabien Potencier
*/
class ParameterBag implements ParameterBagInterface
@@ -149,7 +149,7 @@ class ParameterBag implements ParameterBagInterface
*
* @see resolveValue
*
- * @param array $match
+ * @param array $match
* @return string
*/
private function resolveValueCallback($match)
diff --git a/src/Symfony/Component/DependencyInjection/Variable.php b/src/Symfony/Component/DependencyInjection/Variable.php
index 894107b4a4..11f255649f 100644
--- a/src/Symfony/Component/DependencyInjection/Variable.php
+++ b/src/Symfony/Component/DependencyInjection/Variable.php
@@ -31,7 +31,7 @@ class Variable
/**
* Constructor
*
- * @param string $name
+ * @param string $name
*/
public function __construct($name)
{
diff --git a/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php b/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php
index aa1a1ad01a..fc6ea5e807 100644
--- a/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php
+++ b/src/Symfony/Component/HttpFoundation/File/Exception/AccessDeniedException.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php b/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php
index ff1c2dbb81..7d8310909f 100644
--- a/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php
+++ b/src/Symfony/Component/HttpFoundation/File/Exception/FileException.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php b/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php
index 07d368b611..60ba964745 100644
--- a/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php
+++ b/src/Symfony/Component/HttpFoundation/File/Exception/FileNotFoundException.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/File/File.php b/src/Symfony/Component/HttpFoundation/File/File.php
index 4675332e17..bda63e9a6b 100644
--- a/src/Symfony/Component/HttpFoundation/File/File.php
+++ b/src/Symfony/Component/HttpFoundation/File/File.php
@@ -491,7 +491,7 @@ class File
throw new FileNotFoundException($path);
}
- $this->path = realpath($path);
+ $this->path = $path;
}
/**
diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php
index f0a1fdecad..fb900b2bc2 100644
--- a/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php
+++ b/src/Symfony/Component/HttpFoundation/File/MimeType/ContentTypeMimeTypeGuesser.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php
index e9a352f0ec..84862b0124 100644
--- a/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php
+++ b/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
@@ -48,7 +48,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
if (!self::isSupported()) {
return null;
}
-
+
ob_start();
// need to use --mime instead of -i. see #6641
diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php
index e55e7d54cb..f3b39a3eb0 100644
--- a/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php
+++ b/src/Symfony/Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php
index 2cecb141b7..cfb0cb8fcd 100644
--- a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php
+++ b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php
index adf29479d5..0665970c79 100644
--- a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php
+++ b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesserInterface.php
@@ -2,7 +2,7 @@
/*
* This file is part of the Symfony package.
- *
+ *
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php
index c390c4b6d6..466236da67 100644
--- a/src/Symfony/Component/HttpFoundation/Request.php
+++ b/src/Symfony/Component/HttpFoundation/Request.php
@@ -126,7 +126,7 @@ class Request
*
* @return Request A new request
*/
- static public function createfromGlobals()
+ static public function createFromGlobals()
{
return new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
}
@@ -311,7 +311,8 @@ class Request
public function hasSession()
{
- return $this->cookies->has(session_name());
+ // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
+ return $this->cookies->has(session_name()) && null !== $this->session;
}
public function setSession(Session $session)
@@ -408,7 +409,7 @@ class Request
public function getScheme()
{
- return ($this->server->get('HTTPS') == 'on') ? 'https' : 'http';
+ return $this->isSecure() ? 'https' : 'http';
}
public function getPort()
diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php
index 1d90e67875..813cab9c60 100644
--- a/src/Symfony/Component/HttpFoundation/Response.php
+++ b/src/Symfony/Component/HttpFoundation/Response.php
@@ -738,7 +738,7 @@ class Response
public function isRedirect()
{
- return in_array($this->statusCode, array(301, 302, 303, 307));
+ return in_array($this->statusCode, array(201, 301, 302, 303, 307));
}
public function isEmpty()
diff --git a/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php b/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php
index e174be7a94..5cc70ff452 100644
--- a/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php
+++ b/src/Symfony/Component/HttpFoundation/SessionStorage/FilesystemSessionStorage.php
@@ -20,17 +20,19 @@ class FilesystemSessionStorage extends NativeSessionStorage
{
private $path;
private $data;
+ private $started;
public function __construct($path, array $options = array())
{
$this->path = $path;
+ $this->started = false;
parent::__construct($options);
}
public function start()
{
- if (self::$sessionStarted) {
+ if ($this->started) {
return;
}
@@ -57,6 +59,16 @@ class FilesystemSessionStorage extends NativeSessionStorage
$file = $this->path.'/'.session_id().'.session';
$this->data = file_exists($file) ? unserialize(file_get_contents($file)) : array();
+ $this->started = true;
+ }
+
+ public function getId()
+ {
+ if (!$this->started) {
+ throw new \RuntimeException('The session must be started before reading its ID');
+ }
+
+ return session_id();
}
public function read($key, $default = null)
@@ -85,6 +97,7 @@ class FilesystemSessionStorage extends NativeSessionStorage
if ($destroy) {
$this->data = array();
}
+
return true;
}
}
diff --git a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
index c4ddddbdcf..ce95590f97 100644
--- a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
+++ b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
@@ -60,7 +60,7 @@ class ControllerResolver implements ControllerResolverInterface
return false;
}
- if ($controller instanceof \Closure) {
+ if (is_array($controller) || method_exists($controller, '__invoke')) {
return $controller;
}
@@ -92,15 +92,21 @@ class ControllerResolver implements ControllerResolverInterface
if (is_array($controller)) {
$r = new \ReflectionMethod($controller[0], $controller[1]);
$repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
+ } elseif (is_object($controller)) {
+ $r = new \ReflectionObject($controller);
+ $r = $r->getMethod('__invoke');
+ $repr = get_class($controller);
} else {
$r = new \ReflectionFunction($controller);
- $repr = 'Closure';
+ $repr = $controller;
}
$arguments = array();
foreach ($r->getParameters() as $param) {
if (array_key_exists($param->getName(), $attributes)) {
$arguments[] = $attributes[$param->getName()];
+ } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
+ $arguments[] = $request;
} elseif ($param->isDefaultValueAvailable()) {
$arguments[] = $param->getDefaultValue();
} else {
diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php
index 12d7fbc59d..69c38f59ab 100644
--- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php
+++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php
@@ -44,8 +44,17 @@ class RequestDataCollector extends DataCollector
$attributes[$key] = is_object($value) ? sprintf('Object(%s)', get_class($value)) : $value;
}
+ $content = null;
+ try {
+ $content = $request->getContent();
+ } catch (\LogicException $e) {
+ // the user already got the request content as a resource
+ $content = false;
+ }
+
$this->data = array(
'format' => $request->getRequestFormat(),
+ 'content' => $content,
'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html',
'status_code' => $response->getStatusCode(),
'request_query' => $request->query->all(),
@@ -99,6 +108,11 @@ class RequestDataCollector extends DataCollector
return $this->data['session_attributes'];
}
+ public function getContent()
+ {
+ return $this->data['content'];
+ }
+
public function getContentType()
{
return $this->data['content_type'];
diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php
index a758242faf..8a2da2f19f 100644
--- a/src/Symfony/Component/HttpKernel/Kernel.php
+++ b/src/Symfony/Component/HttpKernel/Kernel.php
@@ -435,6 +435,18 @@ abstract class Kernel implements KernelInterface
return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
}
+ /**
+ * Gets the container's base class.
+ *
+ * All names except Container must be fully qualified.
+ *
+ * @return string
+ */
+ protected function getContainerBaseClass()
+ {
+ return 'Container';
+ }
+
/**
* Initializes the service container.
*
@@ -448,7 +460,7 @@ abstract class Kernel implements KernelInterface
$fresh = true;
if (!$cache->isFresh()) {
$container = $this->buildContainer();
- $this->dumpContainer($cache, $container, $class);
+ $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
$fresh = false;
}
@@ -556,12 +568,13 @@ abstract class Kernel implements KernelInterface
* @param ConfigCache $cache The config cache
* @param ContainerBuilder $container The service container
* @param string $class The name of the class to generate
+ * @param string $baseClass The name of the container's base class
*/
- protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class)
+ protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
{
// cache the container
$dumper = new PhpDumper($container);
- $content = $dumper->dump(array('class' => $class));
+ $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));
if (!$this->debug) {
$content = self::stripComments($content);
}
diff --git a/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php b/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php
index 87e85dad3a..4649ed961e 100644
--- a/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php
+++ b/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php
@@ -54,10 +54,7 @@ class PhpGeneratorDumper extends GeneratorDumper
$compiledRoute = $route->compile();
$variables = str_replace("\n", '', var_export($compiledRoute->getVariables(), true));
- $defaultsMerge = '';
- foreach ($compiledRoute->getDefaults() as $key => $value) {
- $defaultsMerge .= ' $defaults[\''.$key.'\'] = '.str_replace("\n", '', var_export($value, true)).';'."\n";
- }
+ $defaults = str_replace("\n", '', var_export($compiledRoute->getDefaults(), true));
$requirements = str_replace("\n", '', var_export($compiledRoute->getRequirements(), true));
$tokens = str_replace("\n", '', var_export($compiledRoute->getTokens(), true));
@@ -66,9 +63,7 @@ class PhpGeneratorDumper extends GeneratorDumper
$methods[] = <<defaults;
-$defaultsMerge
- return array($variables, \$defaults, $requirements, $tokens);
+ return array($variables, $defaults, $requirements, $tokens);
}
EOF
@@ -107,6 +102,8 @@ EOF;
return <<context = \$context;
- \$this->defaults = \$defaults;
}
EOF;
diff --git a/src/Symfony/Component/Routing/Generator/UrlGenerator.php b/src/Symfony/Component/Routing/Generator/UrlGenerator.php
index e83d40d612..5c02f2f69d 100644
--- a/src/Symfony/Component/Routing/Generator/UrlGenerator.php
+++ b/src/Symfony/Component/Routing/Generator/UrlGenerator.php
@@ -13,6 +13,7 @@ namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
+use Symfony\Component\Routing\RequestContext;
/**
* UrlGenerator generates URL based on a set of routes.
@@ -21,7 +22,6 @@ use Symfony\Component\Routing\RouteCollection;
*/
class UrlGenerator implements UrlGeneratorInterface
{
- protected $defaults;
protected $context;
private $routes;
@@ -31,27 +31,35 @@ class UrlGenerator implements UrlGeneratorInterface
* Constructor.
*
* @param RouteCollection $routes A RouteCollection instance
- * @param array $context The context
- * @param array $defaults The default values
+ * @param RequestContext $context The context
*/
- public function __construct(RouteCollection $routes, array $context = array(), array $defaults = array())
+ public function __construct(RouteCollection $routes, RequestContext $context)
{
$this->routes = $routes;
$this->context = $context;
- $this->defaults = $defaults;
$this->cache = array();
}
/**
* Sets the request context.
*
- * @param array $context The context
+ * @param RequestContext $context The context
*/
- public function setContext(array $context = array())
+ public function setContext(RequestContext $context)
{
$this->context = $context;
}
+ /**
+ * Gets the request context.
+ *
+ * @return RequestContext The context
+ */
+ public function getContext()
+ {
+ return $this->context;
+ }
+
/**
* Generates a URL from the given parameters.
*
@@ -81,8 +89,9 @@ class UrlGenerator implements UrlGeneratorInterface
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
{
- $defaults = array_merge($this->defaults, $defaults);
- $tparams = array_merge($defaults, $parameters);
+ $originParameters = $parameters;
+ $parameters = array_replace($this->context->getParameters(), $parameters);
+ $tparams = array_replace($defaults, $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $tparams)) {
@@ -99,8 +108,11 @@ class UrlGenerator implements UrlGeneratorInterface
throw new \InvalidArgumentException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $requirements[$token[3]], $tparams[$token[3]]));
}
- // %2F is not valid in a URL, so we don't encode it (which is fine as the requirements explicitely allowed it)
- $url = $token[1].str_replace('%2F', '/', urlencode($tparams[$token[3]])).$url;
+ if (isset($tparams[$token[3]])) {
+ // %2F is not valid in a URL, so we don't encode it (which is fine as the requirements explicitly allowed it)
+ $url = $token[1].str_replace('%2F', '/', urlencode($tparams[$token[3]])).$url;
+ }
+
$optional = false;
}
} elseif ('text' === $token[0]) {
@@ -120,20 +132,29 @@ class UrlGenerator implements UrlGeneratorInterface
}
// add a query string if needed
- if ($extra = array_diff_key($parameters, $variables, $defaults)) {
+ if ($extra = array_diff_key($originParameters, $variables, $defaults)) {
$url .= '?'.http_build_query($extra);
}
- $url = (isset($this->context['base_url']) ? $this->context['base_url'] : '').$url;
+ $url = $this->context->getBaseUrl().$url;
- if ($absolute && isset($this->context['host'])) {
- $isSecure = (isset($this->context['is_secure']) && $this->context['is_secure']);
- $port = isset($this->context['port']) ? $this->context['port'] : 80;
- $urlBeginning = 'http'.($isSecure ? 's' : '').'://'.$this->context['host'];
- if (($isSecure && $port != 443) || (!$isSecure && $port != 80)) {
- $urlBeginning .= ':'.$port;
+ if ($this->context->getHost()) {
+ $scheme = $this->context->getScheme();
+ if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) {
+ $absolute = true;
+ $scheme = $req;
+ }
+
+ if ($absolute) {
+ $port = '';
+ if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
+ $port = ':'.$this->context->getHttpPort();
+ } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
+ $port = ':'.$this->context->getHttpsPort();
+ }
+
+ $url = $scheme.'://'.$this->context->getHost().$port.$url;
}
- $url = $urlBeginning.$url;
}
return $url;
diff --git a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php
index 032d6883c9..3d7dbac5c6 100644
--- a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php
+++ b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php
@@ -84,7 +84,7 @@ class AnnotationFileLoader extends FileLoader
*
* @param string $file A PHP file path
*
- * @return string|false Full class name if found, false otherwise
+ * @return string|false Full class name if found, false otherwise
*/
protected function findClass($file)
{
diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
index b882ad57de..339715be64 100644
--- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
+++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
@@ -41,17 +41,17 @@ class PhpMatcherDumper extends MatcherDumper
// trailing slash support is only enabled if we know how to redirect the user
$interfaces = class_implements($options['base_class']);
- $supportsTrailingSlash = isset($interfaces['Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface']);
+ $supportsRedirections = isset($interfaces['Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface']);
return
$this->startClass($options['class'], $options['base_class']).
$this->addConstructor().
- $this->addMatcher($supportsTrailingSlash).
+ $this->addMatcher($supportsRedirections).
$this->endClass()
;
}
- private function addMatcher($supportsTrailingSlash)
+ private function addMatcher($supportsRedirections)
{
$code = array();
@@ -61,7 +61,7 @@ class PhpMatcherDumper extends MatcherDumper
$hasTrailingSlash = false;
$matches = false;
if (!count($compiledRoute->getVariables()) && false !== preg_match('#^(.)\^(?P.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
- if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
+ if ($supportsRedirections && substr($m['url'], -1) === '/') {
$conditions[] = sprintf("rtrim(\$pathinfo, '/') === '%s'", rtrim(str_replace('\\', '', $m['url']), '/'));
$hasTrailingSlash = true;
} else {
@@ -73,7 +73,7 @@ class PhpMatcherDumper extends MatcherDumper
}
$regex = $compiledRoute->getRegex();
- if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
+ if ($supportsRedirections && $pos = strpos($regex, '/$')) {
$regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
$hasTrailingSlash = true;
}
@@ -92,13 +92,23 @@ class PhpMatcherDumper extends MatcherDumper
EOF;
if ($req = $route->getRequirement('_method')) {
- $req = implode('\', \'', array_map('strtolower', explode('|', $req)));
- $code[] = <<context['method']) && !in_array(strtolower(\$this->context['method']), array('$req'))) {
- \$allow = array_merge(\$allow, array('$req'));
+ $methods = array_map('strtolower', explode('|', $req));
+ if (1 === count($methods)) {
+ $code[] = <<context->getMethod() != '$methods[0]') {
+ \$allow[] = '$methods[0]';
goto $gotoname;
}
EOF;
+ } else {
+ $methods = implode('\', \'', $methods);
+ $code[] = <<context->getMethod(), array('$methods'))) {
+ \$allow = array_merge(\$allow, array('$methods'));
+ goto $gotoname;
+ }
+EOF;
+ }
}
if ($hasTrailingSlash) {
@@ -110,6 +120,19 @@ EOF
, $name);
}
+ if ($scheme = $route->getRequirement('_scheme')) {
+ if (!$supportsRedirections) {
+ throw new \LogicException('The "_scheme" requirement is only supported for route dumper that implements RedirectableUrlMatcherInterface.');
+ }
+
+ $code[] = sprintf(<<context->getScheme() !== '$scheme') {
+ return \$this->redirect(\$pathinfo, '%s', '$scheme');
+ }
+EOF
+ , $name);
+ }
+
// optimize parameters array
if (true === $matches && $compiledRoute->getDefaults()) {
$code[] = sprintf(" return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));"
@@ -152,6 +175,7 @@ EOF;
use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
+use Symfony\Component\Routing\RequestContext;
/**
* $class
@@ -171,10 +195,9 @@ EOF;
/**
* Constructor.
*/
- public function __construct(array \$context = array(), array \$defaults = array())
+ public function __construct(RequestContext \$context)
{
\$this->context = \$context;
- \$this->defaults = \$defaults;
}
EOF;
diff --git a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php
new file mode 100644
index 0000000000..e18ea8df2f
--- /dev/null
+++ b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php
@@ -0,0 +1,49 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Routing\Matcher;
+
+use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
+
+/**
+ * @author Fabien Potencier
+ */
+abstract class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface
+{
+ private $trailingSlashTest = false;
+
+ /**
+ * @see UrlMatcher::match()
+ */
+ public function match($pathinfo)
+ {
+ try {
+ $parameters = parent::match($pathinfo);
+ } catch (NotFoundException $e) {
+ if ('/' === substr($pathinfo, -1)) {
+ throw $e;
+ }
+
+ // try with a / at the end
+ $this->trailingSlashTest = true;
+
+ return $this->match($pathinfo.'/');
+ }
+
+ if ($this->trailingSlashTest) {
+ $this->trailingSlashTest = false;
+
+ return $this->redirect($pathinfo, null);
+ }
+
+ return $parameters;
+ }
+}
diff --git a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php
index b1e4cd4b41..3ed93e7a52 100644
--- a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php
+++ b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php
@@ -21,17 +21,11 @@ interface RedirectableUrlMatcherInterface
/**
* Redirects the user to another URL.
*
- * As the Routing component does not know know to redirect the user,
- * the default implementation throw an exception.
- *
- * Override this method to implement your own logic.
- *
- * If you are using a Dumper, don't forget to change the default base.
- *
- * @param string $pathinfo The path info to redirect to.
- * @param string $route The route that matched
+ * @param string $path The path info to redirect to.
+ * @param string $route The route that matched
+ * @param string $scheme The URL scheme (null to keep the current one)
*
* @return array An array of parameters
*/
- function redirect($pathinfo, $route);
+ function redirect($path, $route, $scheme = null);
}
diff --git a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php
index ab47ed1bf2..aa1ddf4db6 100644
--- a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php
+++ b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php
@@ -15,6 +15,7 @@ use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
+use Symfony\Component\Routing\RequestContext;
/**
* UrlMatcher matches URL based on a set of routes.
@@ -23,7 +24,6 @@ use Symfony\Component\Routing\RouteCollection;
*/
class UrlMatcher implements UrlMatcherInterface
{
- protected $defaults;
protected $context;
private $routes;
@@ -32,26 +32,34 @@ class UrlMatcher implements UrlMatcherInterface
* Constructor.
*
* @param RouteCollection $routes A RouteCollection instance
- * @param array $context The context
- * @param array $defaults The default values
+ * @param RequestContext $context The context
*/
- public function __construct(RouteCollection $routes, array $context = array(), array $defaults = array())
+ public function __construct(RouteCollection $routes, RequestContext $context)
{
$this->routes = $routes;
$this->context = $context;
- $this->defaults = $defaults;
}
/**
* Sets the request context.
*
- * @param array $context The context
+ * @param RequestContext $context The context
*/
- public function setContext(array $context = array())
+ public function setContext(RequestContext $context)
{
$this->context = $context;
}
+ /**
+ * Gets the request context.
+ *
+ * @return RequestContext The context
+ */
+ public function getContext()
+ {
+ return $this->context;
+ }
+
/**
* Tries to match a URL with a set of routes.
*
@@ -79,7 +87,7 @@ class UrlMatcher implements UrlMatcherInterface
}
// check HTTP method requirement
- if (isset($this->context['method']) && $route->getRequirement('_method') && ($req = explode('|', $route->getRequirement('_method'))) && !in_array(strtolower($this->context['method']), array_map('strtolower', $req))) {
+ if ($route->getRequirement('_method') && ($req = explode('|', $route->getRequirement('_method'))) && !in_array($this->context->getMethod(), array_map('strtolower', $req))) {
$allow = array_merge($allow, $req);
continue;
}
@@ -94,7 +102,7 @@ class UrlMatcher implements UrlMatcherInterface
protected function mergeDefaults($params, $defaults)
{
- $parameters = array_merge($this->defaults, $defaults);
+ $parameters = $defaults;
foreach ($params as $key => $value) {
if (!is_int($key)) {
$parameters[$key] = urldecode($value);
diff --git a/src/Symfony/Component/Routing/RequestContext.php b/src/Symfony/Component/Routing/RequestContext.php
new file mode 100644
index 0000000000..1110efe222
--- /dev/null
+++ b/src/Symfony/Component/Routing/RequestContext.php
@@ -0,0 +1,230 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Routing;
+
+/**
+ * Holds information about the current request.
+ *
+ * @author Fabien Potencier
+ */
+class RequestContext
+{
+ private $baseUrl;
+ private $method;
+ private $host;
+ private $scheme;
+ private $httpPort;
+ private $httpsPort;
+ private $parameters;
+
+ /**
+ * Constructor.
+ *
+ * @param string $baseUrl The base URL
+ * @param string $method The HTTP method
+ * @param string $host The HTTP host name
+ * @param string $scheme The HTTP scheme
+ * @param integer $httpPort The HTTP port
+ * @param integer $httpsPort The HTTPS port
+ */
+ public function __construct($baseUrl = '', $method = 'get', $host = 'localhost', $scheme = 'http', $httpPort = 80, $httpsPort = 443)
+ {
+ $this->baseUrl = $baseUrl;
+ $this->method = strtolower($method);
+ $this->host = $host;
+ $this->scheme = strtolower($scheme);
+ $this->httpPort = $httpPort;
+ $this->httpsPort = $httpsPort;
+ $this->parameters = array();
+ }
+
+ /**
+ * Gets the base URL.
+ *
+ * @return string The base URL
+ */
+ public function getBaseUrl()
+ {
+ return $this->baseUrl;
+ }
+
+ /**
+ * Sets the base URL.
+ *
+ * @param string $baseUrl The base URL
+ */
+ public function setBaseUrl($baseUrl)
+ {
+ $this->baseUrl = $baseUrl;
+ }
+
+ /**
+ * Gets the HTTP method.
+ *
+ * @return string The HTTP method
+ */
+ public function getMethod()
+ {
+ return $this->method;
+ }
+
+ /**
+ * Sets the HTTP method.
+ *
+ * @param string $method The HTTP method
+ */
+ public function setMethod($method)
+ {
+ $this->method = strtolower($method);
+ }
+
+ /**
+ * Gets the HTTP host.
+ *
+ * @return string The HTTP host
+ */
+ public function getHost()
+ {
+ return $this->host;
+ }
+
+ /**
+ * Sets the HTTP host.
+ *
+ * @param string $host The HTTP host
+ */
+ public function setHost($host)
+ {
+ $this->host = $host;
+ }
+
+ /**
+ * Gets the HTTP scheme.
+ *
+ * @return string The HTTP scheme
+ */
+ public function getScheme()
+ {
+ return $this->scheme;
+ }
+
+ /**
+ * Sets the HTTP scheme.
+ *
+ * @param string $scheme The HTTP scheme
+ */
+ public function setScheme($scheme)
+ {
+ $this->scheme = strtolower($scheme);
+ }
+
+ /**
+ * Gets the HTTP port.
+ *
+ * @return string The HTTP port
+ */
+ public function getHttpPort()
+ {
+ return $this->httpPort;
+ }
+
+ /**
+ * Sets the HTTP port.
+ *
+ * @param string $httpPort The HTTP port
+ */
+ public function setHttpPort($httpPort)
+ {
+ $this->httpPort = $httpPort;
+ }
+
+ /**
+ * Gets the HTTPS port.
+ *
+ * @return string The HTTPS port
+ */
+ public function getHttpsPort()
+ {
+ return $this->httpsPort;
+ }
+
+ /**
+ * Sets the HTTPS port.
+ *
+ * @param string $httpsPort The HTTPS port
+ */
+ public function setHttpsPort($httpsPort)
+ {
+ $this->httpsPort = $httpsPort;
+ }
+
+ /**
+ * Returns the parameters.
+ *
+ * @return array The parameters
+ */
+ public function getParameters()
+ {
+ return $this->parameters;
+ }
+
+ /**
+ * Sets the parameters.
+ *
+ * This method implements a fluent interface.
+ *
+ * @param array $parameters The parameters
+ *
+ * @return Route The current Route instance
+ */
+ public function setParameters(array $parameters)
+ {
+ $this->parameters = $parameters;
+
+ return $this;
+ }
+
+ /**
+ * Gets a parameter value.
+ *
+ * @param string $name A parameter name
+ *
+ * @return mixed The parameter value
+ */
+ public function getParameter($name)
+ {
+ return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
+ }
+
+ /**
+ * Checks if a parameter value is set for the given parameter.
+ *
+ * @param string $name A parameter name
+ *
+ * @return Boolean true if the parameter value is set, false otherwise
+ */
+ public function hasParameter($name)
+ {
+ return array_key_exists($name, $this->parameters);
+ }
+
+ /**
+ * Sets a parameter value.
+ *
+ * @param string $name A parameter name
+ * @param mixed $parameter The parameter value
+ */
+ public function setParameter($name, $parameter)
+ {
+ $this->parameters[$name] = $parameter;
+ }
+}
diff --git a/src/Symfony/Component/Routing/Route.php b/src/Symfony/Component/Routing/Route.php
index fb2e90507d..bcd54e506e 100644
--- a/src/Symfony/Component/Routing/Route.php
+++ b/src/Symfony/Component/Routing/Route.php
@@ -159,6 +159,18 @@ class Route
return isset($this->defaults[$name]) ? $this->defaults[$name] : null;
}
+ /**
+ * Checks if a default value is set for the given variable.
+ *
+ * @param string $name A variable name
+ *
+ * @return Boolean true if the default value is set, false otherwise
+ */
+ public function hasDefault($name)
+ {
+ return array_key_exists($name, $this->defaults);
+ }
+
/**
* Sets a default value.
*
diff --git a/src/Symfony/Component/Routing/RouteCompiler.php b/src/Symfony/Component/Routing/RouteCompiler.php
index 0bff64903e..7c1bd5da5e 100644
--- a/src/Symfony/Component/Routing/RouteCompiler.php
+++ b/src/Symfony/Component/Routing/RouteCompiler.php
@@ -212,7 +212,7 @@ class RouteCompiler implements RouteCompilerInterface
$this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$requirement.')';
$this->variables[$variable] = $name;
- if (null === $this->route->getDefault($variable)) {
+ if (!$this->route->hasDefault($variable)) {
$this->firstOptional = count($this->segments);
}
}
diff --git a/src/Symfony/Component/Routing/Router.php b/src/Symfony/Component/Routing/Router.php
index 5e5961d5e4..6459fc658e 100644
--- a/src/Symfony/Component/Routing/Router.php
+++ b/src/Symfony/Component/Routing/Router.php
@@ -48,11 +48,11 @@ class Router implements RouterInterface
*
* @throws \InvalidArgumentException When unsupported option is provided
*/
- public function __construct(LoaderInterface $loader, $resource, array $options = array(), array $context = array(), array $defaults = array())
+ public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, array $defaults = array())
{
$this->loader = $loader;
$this->resource = $resource;
- $this->context = $context;
+ $this->context = null === $context ? new RequestContext() : $context;
$this->defaults = $defaults;
$this->options = array(
'cache_dir' => null,
@@ -102,14 +102,26 @@ class Router implements RouterInterface
/**
* Sets the request context.
*
- * @param array $context The context
+ * @param RequestContext $context The context
*/
- public function setContext(array $context = array())
+ public function setContext(RequestContext $context)
{
+ $this->context = $context;
+
$this->getMatcher()->setContext($context);
$this->getGenerator()->setContext($context);
}
+ /**
+ * Gets the request context.
+ *
+ * @return RequestContext The context
+ */
+ public function getContext()
+ {
+ return $this->context;
+ }
+
/**
* Generates a URL from the given parameters.
*
diff --git a/src/Symfony/Component/Security/Acl/Domain/Acl.php b/src/Symfony/Component/Security/Acl/Domain/Acl.php
index 20f300b539..09bcb34390 100644
--- a/src/Symfony/Component/Security/Acl/Domain/Acl.php
+++ b/src/Symfony/Component/Security/Acl/Domain/Acl.php
@@ -10,6 +10,7 @@
namespace Symfony\Component\Security\Acl\Domain;
+use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\PropertyChangedListener;
use Symfony\Component\Security\Acl\Model\AclInterface;
use Symfony\Component\Security\Acl\Model\AuditableAclInterface;
@@ -33,7 +34,7 @@ use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface;
*
* @author Johannes M. Schmitt
*/
-class Acl implements AuditableAclInterface
+class Acl implements AuditableAclInterface, NotifyPropertyChanged
{
private $parentAcl;
private $permissionGrantingStrategy;
diff --git a/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php b/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php
index 0f71237831..1510df2411 100644
--- a/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php
+++ b/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php
@@ -12,7 +12,7 @@
namespace Symfony\Component\Security\Acl\Domain;
use Symfony\Component\Security\Acl\Model\AclInterface;
-use Symfony\Component\Security\Acl\Model\FieldAwareEntryInterface;
+use Symfony\Component\Security\Acl\Model\FieldEntryInterface;
use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface;
/**
@@ -20,7 +20,7 @@ use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface;
*
* @author Johannes M. Schmitt
*/
-class FieldEntry extends Entry implements FieldAwareEntryInterface
+class FieldEntry extends Entry implements FieldEntryInterface
{
private $field;
diff --git a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php
index 8bee157ae4..37bbe4eb0f 100644
--- a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php
+++ b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php
@@ -30,16 +30,8 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
const ALL = 'all';
const ANY = 'any';
- private static $noAceException;
private $auditLogger;
- public function __construct()
- {
- if (null === static::$noAceException) {
- static::$noAceException = new NoAceFoundException('No ACE.');
- }
- }
-
/**
* Sets the audit logger
*
@@ -61,7 +53,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
$aces = $acl->getObjectAces();
if (!$aces) {
- throw static::$noAceException;
+ throw new NoAceFoundException();
}
return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode);
@@ -69,7 +61,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
$aces = $acl->getClassAces();
if (!$aces) {
- throw static::$noAceException;
+ throw $noObjectAce;
}
return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode);
@@ -79,7 +71,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
return $parentAcl->isGranted($masks, $sids, $administrativeMode);
}
- throw new NoAceFoundException('No applicable ACE was found.');
+ throw $noClassAce;
}
}
@@ -92,14 +84,14 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
try {
$aces = $acl->getObjectFieldAces($field);
if (!$aces) {
- throw static::$noAceException;
+ throw new NoAceFoundException();
}
return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode);
} catch (NoAceFoundException $noObjectAces) {
$aces = $acl->getClassFieldAces($field);
if (!$aces) {
- throw static::$noAceException;
+ throw $noObjectAces;
}
return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode);
@@ -109,7 +101,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
return $parentAcl->isFieldGranted($field, $masks, $sids, $administrativeMode);
}
- throw new NoAceFoundException('No applicable ACE was found.');
+ throw $noClassAces;
}
}
@@ -177,7 +169,7 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
return false;
}
- throw static::$noAceException;
+ throw new NoAceFoundException();
}
/**
diff --git a/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php b/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php
index 0ecad61349..994efc012b 100644
--- a/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php
+++ b/src/Symfony/Component/Security/Acl/Exception/NoAceFoundException.php
@@ -19,4 +19,8 @@ namespace Symfony\Component\Security\Acl\Exception;
*/
class NoAceFoundException extends Exception
{
+ public function __construct()
+ {
+ parent::__construct('No applicable ACE was found.');
+ }
}
\ No newline at end of file
diff --git a/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php b/src/Symfony/Component/Security/Acl/Model/FieldEntryInterface.php
similarity index 75%
rename from src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php
rename to src/Symfony/Component/Security/Acl/Model/FieldEntryInterface.php
index 032d6e34a1..68aa10c9f1 100644
--- a/src/Symfony/Component/Security/Acl/Model/FieldAwareEntryInterface.php
+++ b/src/Symfony/Component/Security/Acl/Model/FieldEntryInterface.php
@@ -16,7 +16,12 @@ namespace Symfony\Component\Security\Acl\Model;
*
* @author Johannes M. Schmitt
*/
-interface FieldAwareEntryInterface
+interface FieldEntryInterface extends EntryInterface
{
+ /**
+ * Returns the field used for this entry.
+ *
+ * @return string
+ */
function getField();
}
\ No newline at end of file
diff --git a/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php b/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php
index 4e52e65cef..fdd671236b 100644
--- a/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php
+++ b/src/Symfony/Component/Security/Acl/Model/MutableAclInterface.php
@@ -11,8 +11,6 @@
namespace Symfony\Component\Security\Acl\Model;
-use Doctrine\Common\NotifyPropertyChanged;
-
/**
* This interface adds mutators for the AclInterface.
*
@@ -21,7 +19,7 @@ use Doctrine\Common\NotifyPropertyChanged;
*
* @author Johannes M. Schmitt
*/
-interface MutableAclInterface extends AclInterface, NotifyPropertyChanged
+interface MutableAclInterface extends AclInterface
{
/**
* Deletes a class-based ACE
diff --git a/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php b/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php
index bfd077e151..fe1db512d6 100644
--- a/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php
+++ b/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentTokenInterface.php
@@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Core\Authentication\RememberMe;
/**
* Interface to be implemented by persistent token classes (such as
* Doctrine entities representing a remember-me token)
- *
+ *
* @author Johannes M. Schmitt
*/
interface PersistentTokenInterface
@@ -24,19 +24,19 @@ interface PersistentTokenInterface
* @return string
*/
function getUsername();
-
+
/**
* Returns the series
* @return string
*/
function getSeries();
-
+
/**
* Returns the token value
* @return string
*/
function getTokenValue();
-
+
/**
* Returns the last time the cookie was used
* @return \DateTime
diff --git a/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php b/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php
index 6dbead5462..83e61d737f 100644
--- a/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php
+++ b/src/Symfony/Component/Security/Core/Exception/CookieTheftException.php
@@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Core\Exception;
/**
* This exception is thrown when the RememberMeServices implementation
* detects that a presented cookie has already been used by someone else.
- *
+ *
* @author Johannes M. Schmitt
*/
class CookieTheftException extends AuthenticationException
diff --git a/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php b/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php
index f25905d3f7..593f3ad269 100644
--- a/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php
+++ b/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php
@@ -1,4 +1,4 @@
-alwaysAuthenticate = $alwaysAuthenticate;
}
+ /**
+ * Checks if the attributes are granted against the current token.
+ *
+ * @throws AuthenticationCredentialsNotFoundException when the security context has no authentication token.
+ * @param mixed $attributes
+ * @param mixed|null $object
+ * @return boolean
+ */
public final function isGranted($attributes, $object = null)
{
if (null === $this->token) {
diff --git a/src/Symfony/Component/Security/Core/SecurityContextInterface.php b/src/Symfony/Component/Security/Core/SecurityContextInterface.php
index a811557727..c54ca0e3c9 100644
--- a/src/Symfony/Component/Security/Core/SecurityContextInterface.php
+++ b/src/Symfony/Component/Security/Core/SecurityContextInterface.php
@@ -15,7 +15,27 @@ interface SecurityContextInterface
const AUTHENTICATION_ERROR = '_security.last_error';
const LAST_USERNAME = '_security.last_username';
+ /**
+ * Returns the current security token.
+ *
+ * @return TokenInterface|null A TokenInterface instance or null if no authentication information is available
+ */
function getToken();
- function setToken(TokenInterface $token);
+
+ /**
+ * Sets the authentication token.
+ *
+ * @param TokenInterface $token
+ * @return void
+ */
+ function setToken(TokenInterface $token = null);
+
+ /**
+ * Checks if the attributes are granted against the current authentication token and optionally supplied object.
+ *
+ * @param array $attributes
+ * @param mixed $object
+ * @return boolean
+ */
function isGranted($attributes, $object = null);
}
\ No newline at end of file
diff --git a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php
index 5d69aa25d4..0977cb16fe 100644
--- a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php
+++ b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php
@@ -11,6 +11,7 @@
namespace Symfony\Component\Security\Http\Firewall;
+use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
@@ -112,7 +113,9 @@ class SwitchUserListener implements ListenerInterface
throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername()));
}
- $this->accessDecisionManager->decide($token, array($this->role));
+ if (false === $this->accessDecisionManager->decide($token, array($this->role))) {
+ throw new AccessDeniedException();
+ }
$username = $request->get($this->usernameParameter);
diff --git a/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php b/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php
index eb7245d6f7..a2e9035696 100644
--- a/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php
+++ b/src/Symfony/Component/Serializer/Encoder/AbstractEncoder.php
@@ -3,6 +3,7 @@
namespace Symfony\Component\Serializer\Encoder;
use Symfony\Component\Serializer\SerializerInterface;
+use Symfony\Component\Serializer\SerializerAwareInterface;
/*
* This file is part of the Symfony framework.
@@ -18,7 +19,7 @@ use Symfony\Component\Serializer\SerializerInterface;
*
* @author Jordi Boggiano
*/
-abstract class AbstractEncoder implements EncoderInterface
+abstract class AbstractEncoder implements SerializerAwareInterface, EncoderInterface
{
protected $serializer;
@@ -37,4 +38,4 @@ abstract class AbstractEncoder implements EncoderInterface
{
return $this->serializer;
}
-}
\ No newline at end of file
+}
diff --git a/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php b/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php
new file mode 100644
index 0000000000..ab49c69fab
--- /dev/null
+++ b/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php
@@ -0,0 +1,32 @@
+
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+/**
+ * Defines the interface of encoders
+ *
+ * @author Jordi Boggiano
+ */
+interface DecoderInterface
+{
+ /**
+ * Decodes a string into PHP data
+ *
+ * @param string $data data to decode
+ * @param string $format format to decode from
+ * @return mixed
+ * @api
+ */
+ function decode($data, $format);
+}
diff --git a/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php b/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php
index b7401e0451..e2044404ea 100644
--- a/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php
+++ b/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php
@@ -29,30 +29,4 @@ interface EncoderInterface
* @api
*/
function encode($data, $format);
-
- /**
- * Decodes a string into PHP data
- *
- * @param string $data data to decode
- * @param string $format format to decode from
- * @return mixed
- * @api
- */
- function decode($data, $format);
-
- /**
- * Sets the owning Serializer object
- *
- * @param SerializerInterface $serializer
- * @api
- */
- function setSerializer(SerializerInterface $serializer);
-
- /**
- * Gets the owning Serializer object
- *
- * @return SerializerInterface
- * @api
- */
- function getSerializer();
}
diff --git a/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php b/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php
index 31e4b001c0..5ab6876430 100644
--- a/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php
+++ b/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php
@@ -18,7 +18,7 @@ use Symfony\Component\Serializer\SerializerInterface;
*
* @author Jordi Boggiano
*/
-class JsonEncoder extends AbstractEncoder
+class JsonEncoder extends AbstractEncoder implements DecoderInterface
{
/**
* {@inheritdoc}
diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
index 2e0c0af51e..19ff4b476c 100644
--- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
+++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
@@ -20,7 +20,7 @@ use Symfony\Component\Serializer\SerializerInterface;
* @author John Wards
* @author Fabian Vogler
*/
-class XmlEncoder extends AbstractEncoder
+class XmlEncoder extends AbstractEncoder implements DecoderInterface
{
private $dom;
private $format;
@@ -174,7 +174,7 @@ class XmlEncoder extends AbstractEncoder
} else {
$value = (string) $subnode;
}
-
+
if ($key === 'item') {
if (isset($value['@key'])) {
$data[(string)$value['@key']] = $value['#'];
diff --git a/src/Symfony/Component/Serializer/SerializerAwareInterface.php b/src/Symfony/Component/Serializer/SerializerAwareInterface.php
new file mode 100644
index 0000000000..625601e701
--- /dev/null
+++ b/src/Symfony/Component/Serializer/SerializerAwareInterface.php
@@ -0,0 +1,38 @@
+
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+/**
+ * Defines the interface of encoders
+ *
+ * @author Jordi Boggiano
+ */
+interface SerializerAwareInterface
+{
+ /**
+ * Sets the owning Serializer object
+ *
+ * @param SerializerInterface $serializer
+ * @api
+ */
+ function setSerializer(SerializerInterface $serializer);
+
+ /**
+ * Gets the owning Serializer object
+ *
+ * @return SerializerInterface
+ * @api
+ */
+ function getSerializer();
+}
diff --git a/src/Symfony/Component/Templating/EngineInterface.php b/src/Symfony/Component/Templating/EngineInterface.php
index 7b26da0320..1a9a342672 100644
--- a/src/Symfony/Component/Templating/EngineInterface.php
+++ b/src/Symfony/Component/Templating/EngineInterface.php
@@ -19,7 +19,7 @@ namespace Symfony\Component\Templating;
* a path on the filesystem (in fact, the template can be stored
* anywhere, like in a database).
*
- * The methods should accept any name. If the name is not an instance of
+ * The methods should accept any name. If the name is not an instance of
* TemplateReferenceInterface, a TemplateNameParserInterface should be used to
* convert the name to a TemplateReferenceInterface instance.
*
diff --git a/src/Symfony/Component/Translation/Interval.php b/src/Symfony/Component/Translation/Interval.php
index 63c89c5605..8e0d22f788 100644
--- a/src/Symfony/Component/Translation/Interval.php
+++ b/src/Symfony/Component/Translation/Interval.php
@@ -57,7 +57,7 @@ class Interval
$leftNumber = self::convertNumber($matches['left']);
$rightNumber = self::convertNumber($matches['right']);
- return
+ return
('[' === $matches['left_delimiter'] ? $number >= $leftNumber : $number > $leftNumber)
&& (']' === $matches['right_delimiter'] ? $number <= $rightNumber : $number < $rightNumber)
;
diff --git a/src/Symfony/Component/Translation/Loader/CsvFileLoader.php b/src/Symfony/Component/Translation/Loader/CsvFileLoader.php
index daf95189c1..95ac3823c1 100644
--- a/src/Symfony/Component/Translation/Loader/CsvFileLoader.php
+++ b/src/Symfony/Component/Translation/Loader/CsvFileLoader.php
@@ -30,13 +30,13 @@ class CsvFileLoader extends ArrayLoader implements LoaderInterface
public function load($resource, $locale, $domain = 'messages')
{
$messages = array();
-
+
try {
$file = new \SplFileObject($resource, 'rb');
} catch(\RuntimeException $e) {
throw new \InvalidArgumentException(sprintf('Error opening file "%s".', $resource));
}
-
+
$file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
$file->setCsvControl(';');
diff --git a/src/Symfony/Component/Yaml/Escaper.php b/src/Symfony/Component/Yaml/Escaper.php
index 9ff9272ff8..81a7d5fe1b 100644
--- a/src/Symfony/Component/Yaml/Escaper.php
+++ b/src/Symfony/Component/Yaml/Escaper.php
@@ -49,7 +49,7 @@ class Escaper
{
return preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value);
}
-
+
/**
* Escapes and surrounds a PHP value with double quotes.
*
diff --git a/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php b/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php
index a3b6cb7df2..c141336bff 100644
--- a/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php
+++ b/tests/Symfony/Tests/Bridge/Twig/Extension/TranslationExtensionTest.php
@@ -47,16 +47,9 @@ class TranslationExtensionTest extends TestCase
{
return array(
// trans tag
- array('{% trans "Hello" %}', 'Hello'),
- array('{% trans "Hello %name%" %}', 'Hello Symfony2', array('name' => 'Symfony2')),
- array('{% trans name %}', 'Symfony2', array('name' => 'Symfony2')),
- array('{% trans hello with { \'%name%\': \'Symfony2\' } %}', 'Hello Symfony2', array('hello' => 'Hello %name%')),
- array('{% set vars = { \'%name%\': \'Symfony2\' } %}{% trans hello with vars %}', 'Hello Symfony2', array('hello' => 'Hello %name%')),
-
array('{% trans %}Hello{% endtrans %}', 'Hello'),
array('{% trans %}%name%{% endtrans %}', 'Symfony2', array('name' => 'Symfony2')),
- array('{% trans "Hello" from elsewhere %}', 'Hello'),
array('{% trans from elsewhere %}Hello{% endtrans %}', 'Hello'),
array('{% trans %}Hello %name%{% endtrans %}', 'Hello Symfony2', array('name' => 'Symfony2')),
@@ -84,8 +77,8 @@ class TranslationExtensionTest extends TestCase
array('{% set vars = { \'%name%\': \'Symfony2\' } %}{{ hello|trans(vars) }}', 'Hello Symfony2', array('hello' => 'Hello %name%')),
// transchoice filter
- array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count, {\'%count%\': count}) }}', 'There is 5 apples', array('count' => 5)),
- array('{{ text|transchoice(5, {\'%count%\': 5, \'%name%\': \'Symfony2\'}) }}', 'There is 5 apples (Symfony2)', array('text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)')),
+ array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count) }}', 'There is 5 apples', array('count' => 5)),
+ array('{{ text|transchoice(5, {\'%name%\': \'Symfony2\'}) }}', 'There is 5 apples (Symfony2)', array('text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)')),
);
}
diff --git a/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php b/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php
index f64c9ff94e..7a9de55dd2 100644
--- a/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php
+++ b/tests/Symfony/Tests/Component/BrowserKit/ClientTest.php
@@ -308,4 +308,27 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$this->assertInstanceof('RuntimeException', $e, '->request() throws a \RuntimeException if the script has an error');
}
}
+
+ public function testGetServerParameter()
+ {
+ $client = new TestClient();
+ $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST'));
+ $this->assertEquals('Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3', $client->getServerParameter('HTTP_USER_AGENT'));
+
+ $this->assertEquals('testvalue', $client->getServerParameter('testkey', 'testvalue'));
+ }
+
+ public function testSetServerParameter()
+ {
+ $client = new TestClient();
+
+ $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST'));
+ $this->assertEquals('Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3', $client->getServerParameter('HTTP_USER_AGENT'));
+
+ $client->setServerParameter('HTTP_HOST', 'testhost');
+ $this->assertEquals('testhost', $client->getServerParameter('HTTP_HOST'));
+
+ $client->setServerParameter('HTTP_USER_AGENT', 'testua');
+ $this->assertEquals('testua', $client->getServerParameter('HTTP_USER_AGENT'));
+ }
}
diff --git a/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php b/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php
index 347a8fe21f..6e0f52b909 100644
--- a/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php
+++ b/tests/Symfony/Tests/Component/BrowserKit/ResponseTest.php
@@ -61,14 +61,14 @@ class ResponseTest extends \PHPUnit_Framework_TestCase
{
$headers = array(
'content-type' => 'text/html; charset=utf-8',
- 'set-cookie' => array('foo=bar', 'bar=foo')
+ 'set-cookie' => array('foo=bar', 'bar=foo')
);
-
+
$expected = 'content-type: text/html; charset=utf-8'."\n";
$expected.= 'set-cookie: foo=bar'."\n";
$expected.= 'set-cookie: bar=foo'."\n\n";
$expected.= 'foo';
-
+
$response = new Response('foo', 304, $headers);
$this->assertEquals($expected, $response->__toString(), '->__toString() returns the headers and the content as a string');
diff --git a/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php b/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php
index 8fc6bc248b..34ddb51f9a 100644
--- a/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php
+++ b/tests/Symfony/Tests/Component/Config/Definition/Builder/NodeBuilderTest.php
@@ -30,7 +30,7 @@ class NodeBuilderTest extends \PHPUnit_Framework_TestCase
public function testAddingANewNodeType()
{
$class = __NAMESPACE__.'\\SomeNodeDefinition';
-
+
$builder = new BaseNodeBuilder();
$node = $builder
->setNodeClass('newtype', $class)
@@ -66,7 +66,7 @@ class NodeBuilderTest extends \PHPUnit_Framework_TestCase
$node2 = $builder->node('', 'custom');
$this->assertEquals(get_class($node1), get_class($node2));
- }
+ }
}
class SomeNodeDefinition extends BaseVariableNodeDefinition
diff --git a/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php b/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php
index 3ce18790c1..697969f257 100644
--- a/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php
+++ b/tests/Symfony/Tests/Component/Config/Definition/PrototypedArrayNodeTest.php
@@ -8,7 +8,7 @@ use Symfony\Component\Config\Definition\ScalarNode;
class PrototypedArrayNodeTest extends \PHPUnit_Framework_TestCase
{
-
+
public function testGetDefaultValueReturnsAnEmptyArrayForPrototypes()
{
$node = new PrototypedArrayNode('root');
diff --git a/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php b/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php
index a3ae249d4f..fb582d6c46 100644
--- a/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php
+++ b/tests/Symfony/Tests/Component/Config/Fixtures/Builder/NodeBuilder.php
@@ -20,6 +20,6 @@ class NodeBuilder extends BaseNodeBuilder
return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition';
default:
return parent::getNodeClass($type);
- }
+ }
}
}
\ No newline at end of file
diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php
new file mode 100644
index 0000000000..4db6b8a990
--- /dev/null
+++ b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php
@@ -0,0 +1,62 @@
+register('a', '\stdClass')
+ ->addArgument(new Reference('b'))
+ ;
+ $container->register('b', '\stdClass');
+ }
+
+ /**
+ * @expectedException Symfony\Component\DependencyInjection\Exception\NonExistentServiceException
+ */
+ public function testProcessThrowsExceptionOnInvalidReference()
+ {
+ $container = new ContainerBuilder();
+
+ $container
+ ->register('a', '\stdClass')
+ ->addArgument(new Reference('b'))
+ ;
+
+ $this->process($container);
+ }
+
+ /**
+ * @expectedException Symfony\Component\DependencyInjection\Exception\NonExistentServiceException
+ */
+ public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition()
+ {
+ $container = new ContainerBuilder();
+
+ $def = new Definition();
+ $def->addArgument(new Reference('b'));
+
+ $container
+ ->register('a', '\stdClass')
+ ->addArgument($def)
+ ;
+
+ $this->process($container);
+ }
+
+ private function process(ContainerBuilder $container)
+ {
+ $pass = new CheckExceptionOnInvalidReferenceBehaviorPass();
+ $pass->process($container);
+ }
+}
\ No newline at end of file
diff --git a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php
index 4e29373e22..3ae83af9d5 100644
--- a/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php
+++ b/tests/Symfony/Tests/Component/DependencyInjection/Compiler/ResolveDefinitionTemplatesPassTest.php
@@ -14,7 +14,7 @@ class ResolveDefinitionTemplatesPassTest extends \PHPUnit_Framework_TestCase
$container = new ContainerBuilder();
$container->register('parent', 'foo')->setArguments(array('moo', 'b'))->setProperty('foo', 'moo');
$container->setDefinition('child', new DefinitionDecorator('parent'))
- ->setArgument(0, 'a')
+ ->replaceArgument(0, 'a')
->setProperty('foo', 'bar')
->setClass('bar')
;
@@ -119,12 +119,12 @@ class ResolveDefinitionTemplatesPassTest extends \PHPUnit_Framework_TestCase
$container
->setDefinition('child2', new DefinitionDecorator('child1'))
- ->setArgument(1, 'b')
+ ->replaceArgument(1, 'b')
;
$container
->setDefinition('child1', new DefinitionDecorator('parent'))
- ->setArgument(0, 'a')
+ ->replaceArgument(0, 'a')
;
$this->process($container);
diff --git a/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php b/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php
index 5dc890b433..fc307babbb 100644
--- a/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php
+++ b/tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php
@@ -161,8 +161,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
$sc->get('');
$this->fail('->get() throws a \InvalidArgumentException exception if the service is empty');
} catch (\Exception $e) {
- $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws a \InvalidArgumentException exception if the service is empty');
- $this->assertEquals('The service "" does not exist.', $e->getMessage(), '->get() throws a \InvalidArgumentException exception if the service is empty');
+ $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\NonExistentServiceException', $e, '->get() throws a NonExistentServiceException exception if the service is empty');
}
$this->assertNull($sc->get('', ContainerInterface::NULL_ON_INVALID_REFERENCE));
}
diff --git a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php
index 6c74adfe4a..165d26df63 100644
--- a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php
+++ b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionDecoratorTest.php
@@ -57,7 +57,7 @@ class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase
$def = new DefinitionDecorator('foo');
$this->assertEquals(array(), $def->getArguments());
- $this->assertSame($def, $def->setArgument(0, 'foo'));
+ $this->assertSame($def, $def->replaceArgument(0, 'foo'));
$this->assertEquals(array('index_0' => 'foo'), $def->getArguments());
}
}
\ No newline at end of file
diff --git a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php
index d1880d706b..9ff87e09b7 100644
--- a/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php
+++ b/tests/Symfony/Tests/Component/DependencyInjection/DefinitionTest.php
@@ -201,7 +201,7 @@ class DefinitionTest extends \PHPUnit_Framework_TestCase
}
/**
- * @covers Symfony\Component\DependencyInjection\Definition::setArgument
+ * @covers Symfony\Component\DependencyInjection\Definition::replaceArgument
*/
public function testSetArgument()
{
@@ -210,13 +210,13 @@ class DefinitionTest extends \PHPUnit_Framework_TestCase
$def->addArgument('foo');
$this->assertSame(array('foo'), $def->getArguments());
- $this->assertSame($def, $def->setArgument(0, 'moo'));
+ $this->assertSame($def, $def->replaceArgument(0, 'moo'));
$this->assertSame(array('moo'), $def->getArguments());
$def->addArgument('moo');
$def
- ->setArgument(0, 'foo')
- ->setArgument(1, 'bar')
+ ->replaceArgument(0, 'foo')
+ ->replaceArgument(1, 'bar')
;
$this->assertSame(array('foo', 'bar'), $def->getArguments());
}
diff --git a/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php b/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php
index aa65b26db4..b2e869c589 100644
--- a/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php
+++ b/tests/Symfony/Tests/Component/HttpFoundation/CookieTest.php
@@ -69,13 +69,13 @@ class CookieTest extends \PHPUnit_Framework_TestCase
{
new Cookie('MyCookie', $value);
}
-
+
/**
* @expectedException InvalidArgumentException
*/
public function testInvalidExpiration()
{
- $cookie = new Cookie('MyCookie', 'foo','bar');
+ $cookie = new Cookie('MyCookie', 'foo','bar');
}
/**
diff --git a/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php b/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php
index d93359a7db..019fa215f0 100644
--- a/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php
+++ b/tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php
@@ -116,7 +116,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase
public function testGetFormatFromMimeType($format, $mimeTypes)
{
$request = new Request();
- foreach ($mimeTypes as $mime) {
+ foreach ($mimeTypes as $mime) {
$this->assertEquals($format, $request->getFormat($mime));
}
$request->setFormat($format, $mimeTypes);
@@ -634,7 +634,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase
$request = new Request();
$request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
$this->assertEquals(array('ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'), $request->getCharsets());
-
+
$request = new Request();
$request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7');
$this->assertEquals(array('ISO-8859-1', '*', 'utf-8'), $request->getCharsets());
diff --git a/tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php b/tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php
new file mode 100644
index 0000000000..7f4503b405
--- /dev/null
+++ b/tests/Symfony/Tests/Component/HttpFoundation/SessionStorage/FilesystemSessionStorageTest.php
@@ -0,0 +1,59 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Tests\Component\HttpFoundation\SessionStorage;
+
+use Symfony\Component\HttpFoundation\SessionStorage\FilesystemSessionStorage;
+
+class FilesystemSessionStorageTest extends \PHPUnit_Framework_TestCase
+{
+ private $path;
+
+ protected function setUp()
+ {
+ $this->path = sys_get_temp_dir().'/sf2/session_test';
+ if (!file_exists($this->path)) {
+ mkdir($this->path, 0777, true);
+ }
+ }
+
+ protected function tearDown()
+ {
+ array_map('unlink', glob($this->path.'/*.session'));
+ rmdir($this->path);
+ }
+
+ public function testMultipleInstances()
+ {
+ $storage = new FilesystemSessionStorage($this->path);
+ $storage->start();
+ $storage->write('foo', 'bar');
+
+ $storage = new FilesystemSessionStorage($this->path);
+ $storage->start();
+ $this->assertEquals('bar', $storage->read('foo'), 'values persist between instances');
+ }
+
+ public function testGetIdThrowsErrorBeforeStart()
+ {
+ $this->setExpectedException('RuntimeException');
+
+ $storage = new FilesystemSessionStorage($this->path);
+ $storage->getId();
+ }
+
+ public function testGetIdWorksAfterStart()
+ {
+ $storage = new FilesystemSessionStorage($this->path);
+ $storage->start();
+ $storage->getId();
+ }
+}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php b/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php
index eb50422611..8028edc7ab 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/Bundle/BundleTest.php
@@ -24,13 +24,13 @@ class BundleTest extends \PHPUnit_Framework_TestCase
$cmd = new FooCommand();
$app = $this->getMock('Symfony\Component\Console\Application');
$app->expects($this->once())->method('add')->with($this->equalTo($cmd));
-
+
$bundle = new ExtensionPresentBundle();
$bundle->registerCommands($app);
-
+
$bundle2 = new ExtensionAbsentBundle();
-
+
$this->assertNull($bundle2->registerCommands($app));
-
+
}
}
\ No newline at end of file
diff --git a/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php b/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php
index d2e4940702..334fcb2af9 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/Controller/ControllerResolverTest.php
@@ -36,6 +36,18 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
$controller = $resolver->getController($request);
$this->assertSame($lambda, $controller);
+ $request->attributes->set('_controller', $this);
+ $controller = $resolver->getController($request);
+ $this->assertSame($this, $controller);
+
+ $request->attributes->set('_controller', array($this, 'controllerMethod1'));
+ $controller = $resolver->getController($request);
+ $this->assertSame(array($this, 'controllerMethod1'), $controller);
+
+ $request->attributes->set('_controller', array('Symfony\Tests\Component\HttpKernel\ControllerResolverTest', 'controllerMethod4'));
+ $controller = $resolver->getController($request);
+ $this->assertSame(array('Symfony\Tests\Component\HttpKernel\ControllerResolverTest', 'controllerMethod4'), $controller);
+
$request->attributes->set('_controller', 'foo');
try {
$resolver->getController($request);
@@ -98,6 +110,14 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
}
+
+ $request = Request::create('/');
+ $controller = array(new self(), 'controllerMethod5');
+ $this->assertEquals(array($request), $resolver->getArguments($request, $controller), '->getArguments() injects the request');
+ }
+
+ public function __invoke()
+ {
}
protected function controllerMethod1($foo)
@@ -111,4 +131,12 @@ class ControllerResolverTest extends \PHPUnit_Framework_TestCase
protected function controllerMethod3($foo, $bar = null, $foobar)
{
}
+
+ static protected function controllerMethod4()
+ {
+ }
+
+ protected function controllerMethod5(Request $request)
+ {
+ }
}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php
index 4e105d6694..88360c6f0f 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/ExceptionDataCollectorTest.php
@@ -24,11 +24,11 @@ class ExceptionDataCollectorTest extends \PHPUnit_Framework_TestCase
$c = new ExceptionDataCollector();
$flattened = FlattenException::create($e);
$trace = $flattened->getTrace();
-
+
$this->assertFalse($c->hasException());
-
+
$c->collect(new Request(), new Response(),$e);
-
+
$this->assertTrue($c->hasException());
$this->assertEquals($flattened,$c->getException());
$this->assertSame('foo',$c->getMessage());
@@ -36,5 +36,5 @@ class ExceptionDataCollectorTest extends \PHPUnit_Framework_TestCase
$this->assertSame('exception',$c->getName());
$this->assertSame($trace,$c->getTrace());
}
-
+
}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php
index 84033306e7..529211e89f 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/LoggerDataCollectorTest.php
@@ -22,14 +22,14 @@ class LoggerDataCollectorTest extends \PHPUnit_Framework_TestCase
public function testCollect()
{
$c = new LoggerDataCollector(new TestLogger());
-
+
$c->collect(new Request(), new Response());
-
+
$this->assertSame('logger',$c->getName());
$this->assertSame(1337,$c->countErrors());
$this->assertSame(array('foo'),$c->getLogs());
}
-
+
}
class TestLogger extends Logger implements DebugLoggerInterface
@@ -38,12 +38,12 @@ class TestLogger extends Logger implements DebugLoggerInterface
{
return 1337;
}
-
+
public function getDebugLogger()
{
return new static();
}
-
+
public function getLogs($priority = false)
{
return array('foo');
diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php
index 2d0c4ff503..d52f5a9b2b 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/MemoryDataCollectorTest.php
@@ -20,11 +20,11 @@ class MemoryDataCollectorTest extends \PHPUnit_Framework_TestCase
public function testCollect()
{
$c = new MemoryDataCollector();
-
+
$c->collect(new Request(), new Response());
-
+
$this->assertInternalType('integer',$c->getMemory());
$this->assertSame('memory',$c->getName());
}
-
+
}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php
index 09736efbb1..e8e4ce4d60 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/DataCollector/RequestDataCollectorTest.php
@@ -24,9 +24,9 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
public function testCollect(Request $request, Response $response)
{
$c = new RequestDataCollector();
-
+
$c->collect($request, $response);
-
+
$this->assertSame('request',$c->getName());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getRequestHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestServer());
@@ -36,27 +36,27 @@ class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestQuery());
$this->assertEquals('html',$c->getFormat());
$this->assertEquals(array(),$c->getSessionAttributes());
-
+
$this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getResponseHeaders());
$this->assertEquals(200,$c->getStatusCode());
$this->assertEquals('application/json',$c->getContentType());
}
-
+
public function provider()
{
$request = Request::create('http://test.com/foo?bar=baz');
$request->attributes->set('foo', 'bar');
-
+
$response = new Response();
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/json');
$response->headers->setCookie(new Cookie('foo','bar',1,'/foo','localhost',true,true));
$response->headers->setCookie(new Cookie('bar','foo',new \DateTime('@946684800')));
$response->headers->setCookie(new Cookie('bazz','foo','2000-12-12'));
-
+
return array(
array($request,$response)
);
}
-
+
}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php b/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php
index 6e7607e1db..6c96cf3c9e 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/Debug/ErrorHandlerTest.php
@@ -21,27 +21,27 @@ use Symfony\Component\HttpKernel\Debug\ErrorException;
*/
class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
{
-
+
public function testConstruct()
{
$e = new ErrorHandler(3);
-
+
$this->assertInstanceOf('Symfony\Component\HttpKernel\Debug\ErrorHandler',$e);
-
+
$level = new \ReflectionProperty(get_class($e),'level');
$level->setAccessible(true);
-
+
$this->assertEquals(3,$level->getValue($e));
}
-
+
public function testRegister()
{
$e = new ErrorHandler(3);
$e = $this->getMock(get_class($e), array('handle'));
$e->expects($this->once())->method('handle');
-
+
$e->register();
-
+
try{
trigger_error('foo');
}catch(\Exception $e){
@@ -52,10 +52,10 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
{
$e = new ErrorHandler(0);
$this->assertFalse($e->handle(0,'foo','foo.php',12,'foo'));
-
+
$e = new ErrorHandler(3);
$this->assertFalse($e->handle(4,'foo','foo.php',12,'foo'));
-
+
$e = new ErrorHandler(3);
try{
$e->handle(1, 'foo', 'foo.php', 12,'foo');
diff --git a/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php b/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php
index 3a4f577be3..48dcd77886 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/Exception/FlattenExceptionTest.php
@@ -21,7 +21,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
{
$flattened = FlattenException::create($exception);
$flattened2 = FlattenException::create($exception);
-
+
$flattened->setPrevious($flattened2);
$this->assertEquals($exception->getMessage(), $flattened->getMessage(), 'The message is copied from the original exception.');
@@ -29,7 +29,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(get_class($exception), $flattened->getClass(), 'The class is set to the class of the original exception');
}
-
+
/**
* @dataProvider flattenDataProvider
*/
@@ -37,14 +37,14 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
{
$flattened = FlattenException::create($exception);
$flattened2 = FlattenException::create($exception);
-
+
$flattened->setPrevious($flattened2);
-
+
$this->assertSame($flattened2,$flattened->getPrevious());
-
+
$this->assertSame(array($flattened2),$flattened->getPreviouses());
}
-
+
/**
* @dataProvider flattenDataProvider
*/
@@ -52,7 +52,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
{
$flattened = FlattenException::create($exception);
$flattened->setTrace(array(),'foo.php',123);
-
+
$this->assertEquals(array(
array(
'message'=> 'test',
@@ -64,7 +64,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
)
),$flattened->toArray());
}
-
+
public function flattenDataProvider()
{
return array(
diff --git a/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php b/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php
index 1914ad70a0..398cb817fc 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/Fixtures/ExtensionPresentBundle/Command/FooCommand.php
@@ -19,5 +19,5 @@ class FooCommand extends Command
{
$this->setName('foo');
}
-
+
}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php b/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php
index 2e86b88b83..852c9f2bcd 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/HttpKernelTest.php
@@ -88,6 +88,47 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
$kernel->handle(new Request());
}
+ public function testHandleWhenNoControllerIsAClosure()
+ {
+ $response = new Response('foo');
+ $dispatcher = new EventDispatcher();
+ $kernel = new HttpKernel($dispatcher, $this->getResolver(function () use ($response) { return $response; }));
+
+ $this->assertSame($response, $kernel->handle(new Request()));
+ }
+
+ public function testHandleWhenNoControllerIsAnObjectWithInvoke()
+ {
+ $dispatcher = new EventDispatcher();
+ $kernel = new HttpKernel($dispatcher, $this->getResolver(new Controller()));
+
+ $this->assertEquals(new Response('foo'), $kernel->handle(new Request()));
+ }
+
+ public function testHandleWhenNoControllerIsAFunction()
+ {
+ $dispatcher = new EventDispatcher();
+ $kernel = new HttpKernel($dispatcher, $this->getResolver('Symfony\Tests\Component\HttpKernel\controller_func'));
+
+ $this->assertEquals(new Response('foo'), $kernel->handle(new Request()));
+ }
+
+ public function testHandleWhenNoControllerIsAnArray()
+ {
+ $dispatcher = new EventDispatcher();
+ $kernel = new HttpKernel($dispatcher, $this->getResolver(array(new Controller(), 'controller')));
+
+ $this->assertEquals(new Response('foo'), $kernel->handle(new Request()));
+ }
+
+ public function testHandleWhenNoControllerIsAStaticArray()
+ {
+ $dispatcher = new EventDispatcher();
+ $kernel = new HttpKernel($dispatcher, $this->getResolver(array('Symfony\Tests\Component\HttpKernel\Controller', 'staticcontroller')));
+
+ $this->assertEquals(new Response('foo'), $kernel->handle(new Request()));
+ }
+
/**
* @expectedException LogicException
*/
@@ -140,3 +181,26 @@ class HttpKernelTest extends \PHPUnit_Framework_TestCase
return $resolver;
}
}
+
+class Controller
+{
+ public function __invoke()
+ {
+ return new Response('foo');
+ }
+
+ public function controller()
+ {
+ return new Response('foo');
+ }
+
+ static public function staticController()
+ {
+ return new Response('foo');
+ }
+}
+
+function controller_func()
+{
+ return new Response('foo');
+}
diff --git a/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php b/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php
index 9bce11e431..aa5c1aba60 100644
--- a/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php
+++ b/tests/Symfony/Tests/Component/HttpKernel/KernelTest.php
@@ -341,7 +341,7 @@ EOF;
$kernel->locateResource('@Bundle1Bundle/config/routing.xml');
}
-
+
public function testLocateResourceReturnsTheFirstThatMatches()
{
$kernel = $this->getKernel();
diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php b/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php
index c1d4e34c90..81f021afee 100644
--- a/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php
+++ b/tests/Symfony/Tests/Component/Routing/Fixtures/RedirectableUrlMatcher.php
@@ -19,11 +19,12 @@ use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface;
*/
class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface
{
- public function redirect($pathinfo, $route)
+ public function redirect($path, $route, $scheme = null)
{
return array(
'_controller' => 'Some controller reference...',
- 'url' => $this->context['base_url'].$pathinfo,
+ 'path' => $path,
+ 'scheme' => $scheme,
);
}
}
diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php
index 26395f0bb9..3250215125 100644
--- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php
+++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.php
@@ -2,6 +2,7 @@
use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
+use Symfony\Component\Routing\RequestContext;
/**
* ProjectUrlMatcher
@@ -14,10 +15,9 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher
/**
* Constructor.
*/
- public function __construct(array $context = array(), array $defaults = array())
+ public function __construct(RequestContext $context)
{
$this->context = $context;
- $this->defaults = $defaults;
}
public function match($pathinfo)
@@ -31,7 +31,7 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher
// bar
if (0 === strpos($pathinfo, '/bar') && preg_match('#^/bar/(?P[^/\.]+?)$#x', $pathinfo, $matches)) {
- if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('get', 'head'))) {
+ if (!in_array($this->context->getMethod(), array('get', 'head'))) {
$allow = array_merge($allow, array('get', 'head'));
goto not_bar;
}
@@ -63,8 +63,8 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher
// baz5
if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/$#x', $pathinfo, $matches)) {
- if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('post'))) {
- $allow = array_merge($allow, array('post'));
+ if ($this->context->getMethod() != 'post') {
+ $allow[] = 'post';
goto not_baz5;
}
$matches['_route'] = 'baz5';
@@ -74,8 +74,8 @@ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher
// baz.baz6
if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/$#x', $pathinfo, $matches)) {
- if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('put'))) {
- $allow = array_merge($allow, array('put'));
+ if ($this->context->getMethod() != 'put') {
+ $allow[] = 'put';
goto not_bazbaz6;
}
$matches['_route'] = 'baz.baz6';
diff --git a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php
index 370ba5ba71..db003bb89d 100644
--- a/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php
+++ b/tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher2.php
@@ -2,6 +2,7 @@
use Symfony\Component\Routing\Matcher\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
+use Symfony\Component\Routing\RequestContext;
/**
* ProjectUrlMatcher
@@ -14,10 +15,9 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec
/**
* Constructor.
*/
- public function __construct(array $context = array(), array $defaults = array())
+ public function __construct(RequestContext $context)
{
$this->context = $context;
- $this->defaults = $defaults;
}
public function match($pathinfo)
@@ -31,7 +31,7 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec
// bar
if (0 === strpos($pathinfo, '/bar') && preg_match('#^/bar/(?P[^/\.]+?)$#x', $pathinfo, $matches)) {
- if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('get', 'head'))) {
+ if (!in_array($this->context->getMethod(), array('get', 'head'))) {
$allow = array_merge($allow, array('get', 'head'));
goto not_bar;
}
@@ -69,8 +69,8 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec
// baz5
if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/?$#x', $pathinfo, $matches)) {
- if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('post'))) {
- $allow = array_merge($allow, array('post'));
+ if ($this->context->getMethod() != 'post') {
+ $allow[] = 'post';
goto not_baz5;
}
if (substr($pathinfo, -1) !== '/') {
@@ -83,8 +83,8 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec
// baz.baz6
if (0 === strpos($pathinfo, '/test') && preg_match('#^/test/(?P[^/\.]+?)/?$#x', $pathinfo, $matches)) {
- if (isset($this->context['method']) && !in_array(strtolower($this->context['method']), array('put'))) {
- $allow = array_merge($allow, array('put'));
+ if ($this->context->getMethod() != 'put') {
+ $allow[] = 'put';
goto not_bazbaz6;
}
if (substr($pathinfo, -1) !== '/') {
@@ -100,6 +100,22 @@ class ProjectUrlMatcher extends Symfony\Tests\Component\Routing\Fixtures\Redirec
return array ( 'def' => 'test', '_route' => 'foofoo',);
}
+ // secure
+ if ($pathinfo === '/secure') {
+ if ($this->context->getScheme() !== 'https') {
+ return $this->redirect($pathinfo, 'secure', 'https');
+ }
+ return array('_route' => 'secure');
+ }
+
+ // nonsecure
+ if ($pathinfo === '/nonsecure') {
+ if ($this->context->getScheme() !== 'http') {
+ return $this->redirect($pathinfo, 'nonsecure', 'http');
+ }
+ return array('_route' => 'nonsecure');
+ }
+
throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new NotFoundException();
}
}
diff --git a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php
index 1374024521..5d5466de67 100644
--- a/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php
+++ b/tests/Symfony/Tests/Component/Routing/Generator/Dumper/PhpGeneratorDumperTest.php
@@ -14,6 +14,7 @@ namespace Symfony\Tests\Component\Routing\Generator\Dumper\PhpGeneratorDumper;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper;
+use Symfony\Component\Routing\RequestContext;
class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
{
@@ -21,12 +22,12 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
* @var RouteCollection
*/
private $routeCollection;
-
+
/**
* @var PhpGeneratorDumper
*/
private $generatorDumper;
-
+
/**
* @var string
*/
@@ -37,7 +38,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
parent::setUp();
$this->routeCollection = new RouteCollection();
- $this->generatorDumper = new PhpGeneratorDumper($this->routeCollection);
+ $this->generatorDumper = new PhpGeneratorDumper($this->routeCollection, new RequestContext());
$this->testTmpFilepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'php_generator.php';
@unlink($this->testTmpFilepath);
}
@@ -45,7 +46,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
protected function tearDown()
{
parent::tearDown();
-
+
@unlink($this->testTmpFilepath);
}
@@ -53,18 +54,12 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
{
$this->routeCollection->add('Test', new Route('/testing/{foo}'));
$this->routeCollection->add('Test2', new Route('/testing2'));
-
+
file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump());
include ($this->testTmpFilepath);
- $projectUrlGenerator = new \ProjectUrlGenerator(array(
- 'base_url' => '/app.php',
- 'method' => 'GET',
- 'host' => 'localhost',
- 'port' => 80,
- 'is_secure' => false
- ));
-
+ $projectUrlGenerator = new \ProjectUrlGenerator(new RequestContext('/app.php'));
+
$absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), true);
$absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), true);
$relativeUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), false);
@@ -75,7 +70,7 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($relativeUrlWithParameter, '/app.php/testing/bar');
$this->assertEquals($relativeUrlWithoutParameter, '/app.php/testing2');
}
-
+
/**
* @expectedException \InvalidArgumentException
*/
@@ -84,25 +79,19 @@ class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'WithoutRoutesUrlGenerator')));
include ($this->testTmpFilepath);
- $projectUrlGenerator = new \WithoutRoutesUrlGenerator(array(
- 'base_url' => '/app.php',
- 'method' => 'GET',
- 'host' => 'localhost',
- 'port' => 80,
- 'is_secure' => false
- ));
-
+ $projectUrlGenerator = new \WithoutRoutesUrlGenerator(new RequestContext('/app.php'));
+
$projectUrlGenerator->generate('Test', array());
}
-
+
public function testDumpForRouteWithDefaults()
{
$this->routeCollection->add('Test', new Route('/testing/{foo}', array('foo' => 'bar')));
-
+
file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'DefaultRoutesUrlGenerator')));
include ($this->testTmpFilepath);
-
- $projectUrlGenerator = new \DefaultRoutesUrlGenerator(array());
+
+ $projectUrlGenerator = new \DefaultRoutesUrlGenerator(new RequestContext());
$url = $projectUrlGenerator->generate('Test', array());
$this->assertEquals($url, '/testing');
diff --git a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php
index 5cdf04393a..03d9f997da 100644
--- a/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php
+++ b/tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php
@@ -14,176 +14,177 @@ namespace Symfony\Tests\Component\Routing\Generator;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
+use Symfony\Component\Routing\RequestContext;
class UrlGeneratorTest extends \PHPUnit_Framework_TestCase
{
- /** @var RouteCollection */
- private $routeCollection;
- /** @var UrlGenerator */
- private $generator;
-
- protected function setUp()
- {
- parent::setUp();
-
- $this->routeCollection = new RouteCollection();
- $this->generator = new UrlGenerator($this->routeCollection);
- }
-
public function testAbsoluteUrlWithPort80()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>80,
- 'is_secure'=>false));
-
- $url = $this->generator->generate('test', array(), true);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes)->generate('test', array(), true);
$this->assertEquals('http://localhost/app.php/testing', $url);
}
public function testAbsoluteSecureUrlWithPort443()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>443,
- 'is_secure'=>true));
-
- $url = $this->generator->generate('test', array(), true);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes, array('scheme' => 'https'))->generate('test', array(), true);
$this->assertEquals('https://localhost/app.php/testing', $url);
}
public function testAbsoluteUrlWithNonStandardPort()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>8080,
- 'is_secure'=>false));
-
- $url = $this->generator->generate('test', array(), true);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes, array('httpPort' => 8080))->generate('test', array(), true);
$this->assertEquals('http://localhost:8080/app.php/testing', $url);
}
public function testAbsoluteSecureUrlWithNonStandardPort()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>8080,
- 'is_secure'=>true));
-
- $url = $this->generator->generate('test', array(), true);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes, array('httpsPort' => 8080, 'scheme' => 'https'))->generate('test', array(), true);
$this->assertEquals('https://localhost:8080/app.php/testing', $url);
}
public function testRelativeUrlWithoutParameters()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>80,
- 'is_secure'=>false));
-
- $url = $this->generator->generate('test', array(), false);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes)->generate('test', array(), false);
$this->assertEquals('/app.php/testing', $url);
}
-
+
public function testRelativeUrlWithParameter()
{
- $this->routeCollection->add('test', new Route('/testing/{foo}'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>80,
- 'is_secure'=>false));
-
- $url = $this->generator->generate('test', array('foo' => 'bar'), false);
+ $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
+ $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), false);
$this->assertEquals('/app.php/testing/bar', $url);
}
-
+
+ public function testRelativeUrlWithNullParameter()
+ {
+ $routes = $this->getRoutes('test', new Route('/testing.{format}', array('format' => null)));
+ $url = $this->getGenerator($routes)->generate('test', array(), false);
+
+ $this->assertEquals('/app.php/testing', $url);
+ }
+
public function testRelativeUrlWithExtraParameters()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>80,
- 'is_secure'=>false));
-
- $url = $this->generator->generate('test', array('foo' => 'bar'), false);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), false);
$this->assertEquals('/app.php/testing?foo=bar', $url);
}
-
+
public function testAbsoluteUrlWithExtraParameters()
{
- $this->routeCollection->add('test', new Route('/testing'));
- $this->generator->setContext(array(
- 'base_url'=>'/app.php',
- 'method'=>'GET',
- 'host'=>'localhost',
- 'port'=>80,
- 'is_secure'=>false));
-
- $url = $this->generator->generate('test', array('foo' => 'bar'), true);
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true);
$this->assertEquals('http://localhost/app.php/testing?foo=bar', $url);
}
-
+
+ public function testUrlWithExtraParametersFromGlobals()
+ {
+ $routes = $this->getRoutes('test', new Route('/testing'));
+ $generator = $this->getGenerator($routes);
+ $context = new RequestContext('/app.php');
+ $context->setParameter('bar', 'bar');
+ $generator->setContext($context);
+ $url = $generator->generate('test', array('foo' => 'bar'));
+
+ $this->assertEquals('/app.php/testing?foo=bar', $url);
+ }
+
+ public function testUrlWithGlobalParameter()
+ {
+ $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
+ $generator = $this->getGenerator($routes);
+ $context = new RequestContext('/app.php');
+ $context->setParameter('foo', 'bar');
+ $generator->setContext($context);
+ $url = $generator->generate('test', array());
+
+ $this->assertEquals('/app.php/testing/bar', $url);
+ }
+
/**
* @expectedException \InvalidArgumentException
*/
public function testGenerateWithoutRoutes()
- {
- $this->generator->generate('test', array(), true);
+ {
+ $routes = $this->getRoutes('foo', new Route('/testing/{foo}'));
+ $this->getGenerator($routes)->generate('test', array(), true);
}
-
+
/**
* @expectedException \InvalidArgumentException
*/
public function testGenerateForRouteWithoutManditoryParameter()
{
- $this->routeCollection->add('test', new Route('/testing/{foo}'));
- $this->generator->generate('test', array(), true);
+ $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
+ $this->getGenerator($routes)->generate('test', array(), true);
}
-
+
/**
* @expectedException \InvalidArgumentException
*/
public function testGenerateForRouteWithInvalidOptionalParameter()
{
- $route = new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+'));
- $this->routeCollection->add('test', $route);
- $this->generator->generate('test', array('foo' => 'bar'), true);
+ $routes = $this->getRoutes('test', new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+')));
+ $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true);
}
-
+
/**
* @expectedException \InvalidArgumentException
*/
public function testGenerateForRouteWithInvalidManditoryParameter()
{
- $route = new Route('/testing/{foo}', array(), array('foo' => 'd+'));
- $this->routeCollection->add('test', $route);
- $this->generator->generate('test', array('foo' => 'bar'), true);
- }
+ $routes = $this->getRoutes('test', new Route('/testing/{foo}', array(), array('foo' => 'd+')));
+ $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true);
+ }
+
+ public function testSchemeRequirementDoesNothingIfSameCurrentScheme()
+ {
+ $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'http')));
+ $this->assertEquals('/app.php/', $this->getGenerator($routes)->generate('test'));
+
+ $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'https')));
+ $this->assertEquals('/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test'));
+ }
+
+ public function testSchemeRequirementForcesAbsoluteUrl()
+ {
+ $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'https')));
+ $this->assertEquals('https://localhost/app.php/', $this->getGenerator($routes)->generate('test'));
+
+ $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'http')));
+ $this->assertEquals('http://localhost/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test'));
+ }
+
+ protected function getGenerator(RouteCollection $routes, array $parameters = array())
+ {
+ $context = new RequestContext('/app.php');
+ foreach ($parameters as $key => $value) {
+ $method = 'set'.$key;
+ $context->$method($value);
+ }
+ $generator = new UrlGenerator($routes, $context);
+
+ return $generator;
+ }
+
+ protected function getRoutes($name, Route $route)
+ {
+ $routes = new RouteCollection();
+ $routes->add($name, $route);
+
+ return $routes;
+ }
}
diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php
index 138425fba9..5286a9a851 100644
--- a/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php
+++ b/tests/Symfony/Tests/Component/Routing/Matcher/Dumper/PhpMatcherDumperTest.php
@@ -14,16 +14,10 @@ namespace Symfony\Tests\Component\Routing;
use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
+use Symfony\Component\Routing\RequestContext;
class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase
{
- static protected $fixturesPath;
-
- static public function setUpBeforeClass()
- {
- self::$fixturesPath = realpath(__DIR__.'/../../Fixtures/');
- }
-
public function testDump()
{
$collection = new RouteCollection();
@@ -74,8 +68,38 @@ class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase
array('def' => 'test')
));
- $dumper = new PhpMatcherDumper($collection);
- $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher1.php', $dumper->dump(), '->dump() dumps basic routes to the correct PHP file.');
- $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher2.php', $dumper->dump(array('base_class' => 'Symfony\Tests\Component\Routing\Fixtures\RedirectableUrlMatcher')), '->dump() dumps basic routes to the correct PHP file.');
+ $dumper = new PhpMatcherDumper($collection, new RequestContext());
+ $this->assertStringEqualsFile(__DIR__.'/../../Fixtures/dumper/url_matcher1.php', $dumper->dump(), '->dump() dumps basic routes to the correct PHP file.');
+
+ // force HTTPS redirection
+ $collection->add('secure', new Route(
+ '/secure',
+ array(),
+ array('_scheme' => 'https')
+ ));
+
+ // force HTTP redirection
+ $collection->add('nonsecure', new Route(
+ '/nonsecure',
+ array(),
+ array('_scheme' => 'http')
+ ));
+
+ $this->assertStringEqualsFile(__DIR__.'/../../Fixtures/dumper/url_matcher2.php', $dumper->dump(array('base_class' => 'Symfony\Tests\Component\Routing\Fixtures\RedirectableUrlMatcher')), '->dump() dumps basic routes to the correct PHP file.');
+ }
+
+ /**
+ * @expectedException \LogicException
+ */
+ public function testDumpWhenSchemeIsUsedWithoutAProperDumper()
+ {
+ $collection = new RouteCollection();
+ $collection->add('secure', new Route(
+ '/secure',
+ array(),
+ array('_scheme' => 'https')
+ ));
+ $dumper = new PhpMatcherDumper($collection, new RequestContext());
+ $dumper->dump();
}
}
diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php
new file mode 100644
index 0000000000..20ff970649
--- /dev/null
+++ b/tests/Symfony/Tests/Component/Routing/Matcher/RedirectableUrlMatcherTest.php
@@ -0,0 +1,29 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Tests\Component\Routing\Matcher;
+
+use Symfony\Component\Routing\Route;
+use Symfony\Component\Routing\RouteCollection;
+use Symfony\Component\Routing\RequestContext;
+
+class RedirectableUrlMatcherTest extends \PHPUnit_Framework_TestCase
+{
+ public function testNoMethodSoAllowed()
+ {
+ $coll = new RouteCollection();
+ $coll->add('foo', new Route('/foo/'));
+
+ $matcher = $this->getMockForAbstractClass('Symfony\Component\Routing\Matcher\RedirectableUrlMatcher', array($coll, new RequestContext()));
+ $matcher->expects($this->once())->method('redirect');
+ $matcher->match('/foo');
+ }
+}
diff --git a/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php b/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php
index 7efbef6bda..034ecfcc4e 100644
--- a/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php
+++ b/tests/Symfony/Tests/Component/Routing/Matcher/UrlMatcherTest.php
@@ -16,6 +16,7 @@ use Symfony\Component\Routing\Matcher\Exception\NotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
+use Symfony\Component\Routing\RequestContext;
class UrlMatcherTest extends \PHPUnit_Framework_TestCase
{
@@ -24,7 +25,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase
$coll = new RouteCollection();
$coll->add('foo', new Route('/foo'));
- $matcher = new UrlMatcher($coll, array('method' => 'get'));
+ $matcher = new UrlMatcher($coll, new RequestContext());
$matcher->match('/foo');
}
@@ -33,7 +34,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase
$coll = new RouteCollection();
$coll->add('foo', new Route('/foo', array(), array('_method' => 'post')));
- $matcher = new UrlMatcher($coll, array('method' => 'get'));
+ $matcher = new UrlMatcher($coll, new RequestContext());
try {
$matcher->match('/foo');
@@ -49,7 +50,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase
$coll->add('foo1', new Route('/foo', array(), array('_method' => 'post')));
$coll->add('foo2', new Route('/foo', array(), array('_method' => 'put|delete')));
- $matcher = new UrlMatcher($coll, array('method' => 'get'));
+ $matcher = new UrlMatcher($coll, new RequestContext());
try {
$matcher->match('/foo');
@@ -64,7 +65,7 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase
// test the patterns are matched are parameters are returned
$collection = new RouteCollection();
$collection->add('foo', new Route('/foo/{bar}'));
- $matcher = new UrlMatcher($collection, array(), array());
+ $matcher = new UrlMatcher($collection, new RequestContext(), array());
try {
$matcher->match('/no-match');
$this->fail();
@@ -74,26 +75,26 @@ class UrlMatcherTest extends \PHPUnit_Framework_TestCase
// test that defaults are merged
$collection = new RouteCollection();
$collection->add('foo', new Route('/foo/{bar}', array('def' => 'test')));
- $matcher = new UrlMatcher($collection, array(), array());
+ $matcher = new UrlMatcher($collection, new RequestContext(), array());
$this->assertEquals(array('_route' => 'foo', 'bar' => 'baz', 'def' => 'test'), $matcher->match('/foo/baz'));
// test that route "method" is ignored if no method is given in the context
$collection = new RouteCollection();
$collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head')));
- $matcher = new UrlMatcher($collection, array(), array());
+ $matcher = new UrlMatcher($collection, new RequestContext(), array());
$this->assertInternalType('array', $matcher->match('/foo'));
// route does not match with POST method context
- $matcher = new UrlMatcher($collection, array('method' => 'POST'), array());
+ $matcher = new UrlMatcher($collection, new RequestContext('', 'post'), array());
try {
$matcher->match('/foo');
$this->fail();
} catch (MethodNotAllowedException $e) {}
// route does match with GET or HEAD method context
- $matcher = new UrlMatcher($collection, array('method' => 'GET'), array());
+ $matcher = new UrlMatcher($collection, new RequestContext(), array());
$this->assertInternalType('array', $matcher->match('/foo'));
- $matcher = new UrlMatcher($collection, array('method' => 'HEAD'), array());
+ $matcher = new UrlMatcher($collection, new RequestContext('', 'head'), array());
$this->assertInternalType('array', $matcher->match('/foo'));
}
}
diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php
index 4974559986..0061c5993f 100644
--- a/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php
+++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/AuditLoggerTest.php
@@ -20,14 +20,14 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = $this->getLogger();
$ace = $this->getEntry();
-
+
if (true === $granting) {
$ace
->expects($this->once())
->method('isAuditSuccess')
->will($this->returnValue($audit))
;
-
+
$ace
->expects($this->never())
->method('isAuditFailure')
@@ -37,7 +37,7 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
->expects($this->never())
->method('isAuditSuccess')
;
-
+
$ace
->expects($this->once())
->method('isAuditFailure')
@@ -57,10 +57,10 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
->method('doLog')
;
}
-
+
$logger->logIfNeeded($granting, $ace);
}
-
+
public function getTestLogData()
{
return array(
@@ -70,12 +70,12 @@ class AuditLoggerTest extends \PHPUnit_Framework_TestCase
array(false, true),
);
}
-
+
protected function getEntry()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\AuditableEntryInterface');
}
-
+
protected function getLogger()
{
return $this->getMockForAbstractClass('Symfony\Component\Security\Acl\Domain\AuditLogger');
diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php
index a484694915..0916462296 100644
--- a/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php
+++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/EntryTest.php
@@ -18,7 +18,7 @@ class EntryTest extends \PHPUnit_Framework_TestCase
public function testConstructor()
{
$ace = $this->getAce($acl = $this->getAcl(), $sid = $this->getSid());
-
+
$this->assertEquals(123, $ace->getId());
$this->assertSame($acl, $ace->getAcl());
$this->assertSame($sid, $ace->getSecurityIdentity());
@@ -28,54 +28,54 @@ class EntryTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($ace->isAuditSuccess());
$this->assertFalse($ace->isAuditFailure());
}
-
+
public function testSetAuditSuccess()
{
$ace = $this->getAce();
-
+
$this->assertTrue($ace->isAuditSuccess());
$ace->setAuditSuccess(false);
$this->assertFalse($ace->isAuditSuccess());
$ace->setAuditsuccess(true);
$this->assertTrue($ace->isAuditSuccess());
}
-
+
public function testSetAuditFailure()
{
$ace = $this->getAce();
-
+
$this->assertFalse($ace->isAuditFailure());
$ace->setAuditFailure(true);
$this->assertTrue($ace->isAuditFailure());
$ace->setAuditFailure(false);
$this->assertFalse($ace->isAuditFailure());
}
-
+
public function testSetMask()
{
$ace = $this->getAce();
-
+
$this->assertEquals(123456, $ace->getMask());
$ace->setMask(4321);
$this->assertEquals(4321, $ace->getMask());
}
-
+
public function testSetStrategy()
{
$ace = $this->getAce();
-
+
$this->assertEquals('foostrat', $ace->getStrategy());
$ace->setStrategy('foo');
$this->assertEquals('foo', $ace->getStrategy());
}
-
+
public function testSerializeUnserialize()
{
$ace = $this->getAce();
-
+
$serialized = serialize($ace);
$uAce = unserialize($serialized);
-
+
$this->assertNull($uAce->getAcl());
$this->assertInstanceOf('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface', $uAce->getSecurityIdentity());
$this->assertEquals($ace->getId(), $uAce->getId());
@@ -85,7 +85,7 @@ class EntryTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($ace->isAuditSuccess(), $uAce->isAuditSuccess());
$this->assertEquals($ace->isAuditFailure(), $uAce->isAuditFailure());
}
-
+
protected function getAce($acl = null, $sid = null)
{
if (null === $acl) {
@@ -94,24 +94,24 @@ class EntryTest extends \PHPUnit_Framework_TestCase
if (null === $sid) {
$sid = $this->getSid();
}
-
+
return new Entry(
- 123,
- $acl,
- $sid,
- 'foostrat',
- 123456,
- true,
- false,
+ 123,
+ $acl,
+ $sid,
+ 'foostrat',
+ 123456,
+ true,
+ false,
true
- );
+ );
}
-
+
protected function getAcl()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
}
-
+
protected function getSid()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php
index 4b2e31ab2c..c8dc733826 100644
--- a/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php
+++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/FieldEntryTest.php
@@ -18,17 +18,17 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase
public function testConstructor()
{
$ace = $this->getAce();
-
+
$this->assertEquals('foo', $ace->getField());
}
-
+
public function testSerializeUnserialize()
{
$ace = $this->getAce();
-
+
$serialized = serialize($ace);
$uAce = unserialize($serialized);
-
+
$this->assertNull($uAce->getAcl());
$this->assertInstanceOf('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface', $uAce->getSecurityIdentity());
$this->assertEquals($ace->getId(), $uAce->getId());
@@ -39,7 +39,7 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($ace->isAuditSuccess(), $uAce->isAuditSuccess());
$this->assertEquals($ace->isAuditFailure(), $uAce->isAuditFailure());
}
-
+
protected function getAce($acl = null, $sid = null)
{
if (null === $acl) {
@@ -48,25 +48,25 @@ class FieldEntryTest extends \PHPUnit_Framework_TestCase
if (null === $sid) {
$sid = $this->getSid();
}
-
+
return new FieldEntry(
- 123,
- $acl,
+ 123,
+ $acl,
'foo',
- $sid,
- 'foostrat',
- 123456,
- true,
- false,
+ $sid,
+ 'foostrat',
+ 123456,
+ true,
+ false,
true
- );
+ );
}
-
+
protected function getAcl()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
}
-
+
protected function getSid()
{
return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
diff --git a/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php b/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php
index 3ab64b41cc..2a5b5ed92d 100644
--- a/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php
+++ b/tests/Symfony/Tests/Component/Security/Acl/Permission/MaskBuilderTest.php
@@ -23,7 +23,7 @@ class MaskBuilderTest extends \PHPUnit_Framework_TestCase
{
new MaskBuilder($invalidMask);
}
-
+
public function getInvalidConstructorData()
{
return array(
@@ -33,32 +33,32 @@ class MaskBuilderTest extends \PHPUnit_Framework_TestCase
array(new \stdClass()),
);
}
-
+
public function testConstructorWithoutArguments()
{
$builder = new MaskBuilder();
-
+
$this->assertEquals(0, $builder->get());
}
-
+
public function testConstructor()
{
$builder = new MaskBuilder(123456);
-
+
$this->assertEquals(123456, $builder->get());
}
-
+
public function testAddAndRemove()
{
$builder = new MaskBuilder();
-
+
$builder
->add('view')
->add('eDiT')
->add('ownEr')
;
$mask = $builder->get();
-
+
$this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW);
$this->assertEquals(MaskBuilder::MASK_EDIT, $mask & MaskBuilder::MASK_EDIT);
$this->assertEquals(MaskBuilder::MASK_OWNER, $mask & MaskBuilder::MASK_OWNER);
@@ -66,37 +66,37 @@ class MaskBuilderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(0, $mask & MaskBuilder::MASK_CREATE);
$this->assertEquals(0, $mask & MaskBuilder::MASK_DELETE);
$this->assertEquals(0, $mask & MaskBuilder::MASK_UNDELETE);
-
+
$builder->remove('edit')->remove('OWner');
$mask = $builder->get();
$this->assertEquals(0, $mask & MaskBuilder::MASK_EDIT);
$this->assertEquals(0, $mask & MaskBuilder::MASK_OWNER);
$this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW);
}
-
+
public function testGetPattern()
{
$builder = new MaskBuilder;
$this->assertEquals(MaskBuilder::ALL_OFF, $builder->getPattern());
-
+
$builder->add('view');
$this->assertEquals(str_repeat('.', 31).'V', $builder->getPattern());
-
+
$builder->add('owner');
$this->assertEquals(str_repeat('.', 24).'N......V', $builder->getPattern());
-
+
$builder->add(1 << 10);
$this->assertEquals(str_repeat('.', 21).MaskBuilder::ON.'..N......V', $builder->getPattern());
}
-
+
public function testReset()
{
$builder = new MaskBuilder();
$this->assertEquals(0, $builder->get());
-
+
$builder->add('view');
$this->assertTrue($builder->get() > 0);
-
+
$builder->reset();
$this->assertEquals(0, $builder->get());
}
diff --git a/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php b/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php
index 94f35545e5..885304fb35 100644
--- a/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php
+++ b/tests/Symfony/Tests/Component/Security/Acl/Voter/AclVoterTest.php
@@ -360,13 +360,13 @@ class AclVoterTest extends \PHPUnit_Framework_TestCase
$this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
}
-
+
public function testWhenReceivingAnObjectIdentityInterfaceWeDontRetrieveANewObjectIdentity()
{
list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();
-
+
$oid = new ObjectIdentity('someID','someType');
-
+
$permissionMap
->expects($this->once())
->method('contains')
diff --git a/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php b/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php
index 737d41b350..80df994b61 100644
--- a/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php
+++ b/tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php
@@ -111,16 +111,16 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
-
+
public function testEncodeScalarWithAttribute()
{
$array = array(
'person' => array('@gender' => 'M', '#' => 'Peter'),
);
-
+
$expected = ''."\n".
''."\n";
-
+
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
@@ -147,19 +147,19 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(get_object_vars($obj), $this->encoder->decode($source, 'xml'));
}
-
+
public function testDecodeScalarWithAttribute()
{
$source = ''."\n".
'Peter'."\n";
-
+
$expected = array(
'person' => array('@gender' => 'M', '#' => 'Peter'),
);
-
+
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
-
+
public function testDecodeArray()
{
$source = ''."\n".
@@ -169,14 +169,14 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase
'DamienClay'.
''.
''."\n";
-
+
$expected = array(
'people' => array('person' => array(
array('firstname' => 'Benjamin', 'lastname' => 'Alexandre'),
array('firstname' => 'Damien', 'lastname' => 'Clay')
))
);
-
+
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
diff --git a/vendors.sh b/vendors.sh
index 957d28eb8c..3f2723ce44 100755
--- a/vendors.sh
+++ b/vendors.sh
@@ -38,26 +38,20 @@ install_git()
install_git assetic git://github.com/kriswallsmith/assetic.git
# Doctrine ORM
-install_git doctrine git://github.com/doctrine/doctrine2.git
+install_git doctrine git://github.com/doctrine/doctrine2.git 2.0.4
# Doctrine Data Fixtures Extension
install_git doctrine-data-fixtures git://github.com/doctrine/data-fixtures.git
# Doctrine DBAL
-install_git doctrine-dbal git://github.com/doctrine/dbal.git
+install_git doctrine-dbal git://github.com/doctrine/dbal.git 2.0.4
# Doctrine Common
-install_git doctrine-common git://github.com/doctrine/common.git
+install_git doctrine-common git://github.com/doctrine/common.git 2.0.2
# Doctrine migrations
install_git doctrine-migrations git://github.com/doctrine/migrations.git
-# Doctrine MongoDB
-install_git doctrine-mongodb git://github.com/doctrine/mongodb.git
-
-# Doctrine MongoDB
-install_git doctrine-mongodb-odm git://github.com/doctrine/mongodb-odm.git
-
# Monolog
install_git monolog git://github.com/Seldaek/monolog.git