Issue #2161397 by dawehner, Crell: Update to Symfony 2.4.1.

8.0.x
webchick 2014-01-13 18:48:55 -08:00
parent 91b465bdc5
commit 9e017ada4f
393 changed files with 8029 additions and 2464 deletions

View File

@ -10,15 +10,15 @@
], ],
"require": { "require": {
"sdboyer/gliph": "0.1.*", "sdboyer/gliph": "0.1.*",
"symfony/class-loader": "2.3.*", "symfony/class-loader": "2.4.*",
"symfony/dependency-injection": "2.3.*", "symfony/dependency-injection": "2.4.*",
"symfony/event-dispatcher": "2.3.*", "symfony/event-dispatcher": "2.4.*",
"symfony/http-foundation": "2.3.*", "symfony/http-foundation": "2.4.*",
"symfony/http-kernel": "2.3.*", "symfony/http-kernel": "2.4.*",
"symfony/routing": "2.3.*", "symfony/routing": "2.4.*",
"symfony/serializer": "2.3.*", "symfony/serializer": "2.4.*",
"symfony/validator": "2.3.*", "symfony/validator": "2.4.*",
"symfony/yaml": "2.3.*", "symfony/yaml": "2.4.*",
"twig/twig": "1.12.*", "twig/twig": "1.12.*",
"doctrine/common": "dev-bmaster#99b44f52a1b844f9c4c34e618b160664d5c27daf", "doctrine/common": "dev-bmaster#99b44f52a1b844f9c4c34e618b160664d5c27daf",
"doctrine/annotations": "dev-master#463d926a8dcc49271cb7db5a08364a70ed6e3cd3", "doctrine/annotations": "dev-master#463d926a8dcc49271cb7db5a08364a70ed6e3cd3",

193
composer.lock generated
View File

@ -3,7 +3,7 @@
"This file locks the dependencies of your project to a known state", "This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
], ],
"hash": "06006c1512fb829fcdb498b7e515901d", "hash": "b3a05b2f0a069c6d34b65b604a216a92",
"packages": [ "packages": [
{ {
"name": "doctrine/annotations", "name": "doctrine/annotations",
@ -1225,17 +1225,17 @@
}, },
{ {
"name": "symfony/class-loader", "name": "symfony/class-loader",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/ClassLoader", "target-dir": "Symfony/Component/ClassLoader",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/ClassLoader.git", "url": "https://github.com/symfony/ClassLoader.git",
"reference": "622d370a07321329f5259c6f96d5c636104ad46b" "reference": "6a2ebedbc780130f07b3a15363743d08eb46820c"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/ClassLoader/zipball/622d370a07321329f5259c6f96d5c636104ad46b", "url": "https://api.github.com/repos/symfony/ClassLoader/zipball/6a2ebedbc780130f07b3a15363743d08eb46820c",
"reference": "622d370a07321329f5259c6f96d5c636104ad46b", "reference": "6a2ebedbc780130f07b3a15363743d08eb46820c",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1247,7 +1247,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1271,7 +1271,7 @@
], ],
"description": "Symfony ClassLoader Component", "description": "Symfony ClassLoader Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-13 20:18:00" "time": "2013-11-26 16:40:27"
}, },
{ {
"name": "symfony/debug", "name": "symfony/debug",
@ -1331,17 +1331,17 @@
}, },
{ {
"name": "symfony/dependency-injection", "name": "symfony/dependency-injection",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/DependencyInjection", "target-dir": "Symfony/Component/DependencyInjection",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/DependencyInjection.git", "url": "https://github.com/symfony/DependencyInjection.git",
"reference": "3678aa969e5bfeb8515a1f3047c63e8104723f5c" "reference": "7e5bde3a607dde1f8ddef5180759068ad53d259c"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/DependencyInjection/zipball/3678aa969e5bfeb8515a1f3047c63e8104723f5c", "url": "https://api.github.com/repos/symfony/DependencyInjection/zipball/7e5bde3a607dde1f8ddef5180759068ad53d259c",
"reference": "3678aa969e5bfeb8515a1f3047c63e8104723f5c", "reference": "7e5bde3a607dde1f8ddef5180759068ad53d259c",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1349,6 +1349,7 @@
}, },
"require-dev": { "require-dev": {
"symfony/config": "~2.2", "symfony/config": "~2.2",
"symfony/expression-language": "~2.4",
"symfony/yaml": "~2.0" "symfony/yaml": "~2.0"
}, },
"suggest": { "suggest": {
@ -1359,7 +1360,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1383,21 +1384,21 @@
], ],
"description": "Symfony DependencyInjection Component", "description": "Symfony DependencyInjection Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-07-25 17:13:25" "time": "2014-01-01 09:02:49"
}, },
{ {
"name": "symfony/event-dispatcher", "name": "symfony/event-dispatcher",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/EventDispatcher", "target-dir": "Symfony/Component/EventDispatcher",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/EventDispatcher.git", "url": "https://github.com/symfony/EventDispatcher.git",
"reference": "41c9826457c65fa3cf746f214985b7ca9cba42f8" "reference": "e3ba42f6a70554ed05749e61b829550f6ac33601"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/41c9826457c65fa3cf746f214985b7ca9cba42f8", "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/e3ba42f6a70554ed05749e61b829550f6ac33601",
"reference": "41c9826457c65fa3cf746f214985b7ca9cba42f8", "reference": "e3ba42f6a70554ed05749e61b829550f6ac33601",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1413,7 +1414,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1437,21 +1438,21 @@
], ],
"description": "Symfony EventDispatcher Component", "description": "Symfony EventDispatcher Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-07-21 12:12:18" "time": "2013-12-28 08:12:03"
}, },
{ {
"name": "symfony/http-foundation", "name": "symfony/http-foundation",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/HttpFoundation", "target-dir": "Symfony/Component/HttpFoundation",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/HttpFoundation.git", "url": "https://github.com/symfony/HttpFoundation.git",
"reference": "fdf130fe65457aedbc4639a22f4ef9d3be5c002c" "reference": "6c6b8a7bcd7e2cc920cd6acace563fdbf121d844"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/HttpFoundation/zipball/fdf130fe65457aedbc4639a22f4ef9d3be5c002c", "url": "https://api.github.com/repos/symfony/HttpFoundation/zipball/6c6b8a7bcd7e2cc920cd6acace563fdbf121d844",
"reference": "fdf130fe65457aedbc4639a22f4ef9d3be5c002c", "reference": "6c6b8a7bcd7e2cc920cd6acace563fdbf121d844",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1460,7 +1461,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1487,21 +1488,21 @@
], ],
"description": "Symfony HttpFoundation Component", "description": "Symfony HttpFoundation Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-26 05:49:51" "time": "2014-01-05 02:10:50"
}, },
{ {
"name": "symfony/http-kernel", "name": "symfony/http-kernel",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/HttpKernel", "target-dir": "Symfony/Component/HttpKernel",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/HttpKernel.git", "url": "https://github.com/symfony/HttpKernel.git",
"reference": "9d35da40f07bbe7a4f8dfbc41555d2b69de674bf" "reference": "0605eedeb52c4d3a3144128d8336395a57be60d4"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/HttpKernel/zipball/9d35da40f07bbe7a4f8dfbc41555d2b69de674bf", "url": "https://api.github.com/repos/symfony/HttpKernel/zipball/0605eedeb52c4d3a3144128d8336395a57be60d4",
"reference": "9d35da40f07bbe7a4f8dfbc41555d2b69de674bf", "reference": "0605eedeb52c4d3a3144128d8336395a57be60d4",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1509,7 +1510,7 @@
"psr/log": "~1.0", "psr/log": "~1.0",
"symfony/debug": "~2.3", "symfony/debug": "~2.3",
"symfony/event-dispatcher": "~2.1", "symfony/event-dispatcher": "~2.1",
"symfony/http-foundation": "~2.2" "symfony/http-foundation": "~2.4"
}, },
"require-dev": { "require-dev": {
"symfony/browser-kit": "~2.2", "symfony/browser-kit": "~2.2",
@ -1534,7 +1535,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1558,7 +1559,7 @@
], ],
"description": "Symfony HttpKernel Component", "description": "Symfony HttpKernel Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-27 08:58:24" "time": "2014-01-05 02:12:11"
}, },
{ {
"name": "symfony/process", "name": "symfony/process",
@ -1607,39 +1608,99 @@
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-22 06:42:25" "time": "2013-08-22 06:42:25"
}, },
{
"name": "symfony/property-access",
"version": "v2.4.1",
"target-dir": "Symfony/Component/PropertyAccess",
"source": {
"type": "git",
"url": "https://github.com/symfony/PropertyAccess.git",
"reference": "274951234150e303c83099a2429be6be35629fe9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/PropertyAccess/zipball/274951234150e303c83099a2429be6be35629fe9",
"reference": "274951234150e303c83099a2429be6be35629fe9",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.4-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\PropertyAccess\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
}
],
"description": "Symfony PropertyAccess Component",
"homepage": "http://symfony.com",
"keywords": [
"access",
"array",
"extraction",
"index",
"injection",
"object",
"property",
"property path",
"reflection"
],
"time": "2013-11-13 21:30:16"
},
{ {
"name": "symfony/routing", "name": "symfony/routing",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/Routing", "target-dir": "Symfony/Component/Routing",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/Routing.git", "url": "https://github.com/symfony/Routing.git",
"reference": "69af3f07dbf3ae93dd513dbc373f561cb2e7f143" "reference": "4abfb500aab8be458c9e3a227ea56b190584f78a"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/Routing/zipball/69af3f07dbf3ae93dd513dbc373f561cb2e7f143", "url": "https://api.github.com/repos/symfony/Routing/zipball/4abfb500aab8be458c9e3a227ea56b190584f78a",
"reference": "69af3f07dbf3ae93dd513dbc373f561cb2e7f143", "reference": "4abfb500aab8be458c9e3a227ea56b190584f78a",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=5.3.3" "php": ">=5.3.3"
}, },
"require-dev": { "require-dev": {
"doctrine/common": "~2.2", "doctrine/annotations": "~1.0",
"psr/log": "~1.0", "psr/log": "~1.0",
"symfony/config": "~2.2", "symfony/config": "~2.2",
"symfony/expression-language": "~2.4",
"symfony/yaml": "~2.0" "symfony/yaml": "~2.0"
}, },
"suggest": { "suggest": {
"doctrine/common": "", "doctrine/annotations": "For using the annotation loader",
"symfony/config": "", "symfony/config": "For using the all-in-one router or any loader",
"symfony/yaml": "" "symfony/expression-language": "For using expression matching",
"symfony/yaml": "For using the YAML loader"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1663,21 +1724,27 @@
], ],
"description": "Symfony Routing Component", "description": "Symfony Routing Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-23 15:14:07" "keywords": [
"router",
"routing",
"uri",
"url"
],
"time": "2014-01-05 02:10:50"
}, },
{ {
"name": "symfony/serializer", "name": "symfony/serializer",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/Serializer", "target-dir": "Symfony/Component/Serializer",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/Serializer.git", "url": "https://github.com/symfony/Serializer.git",
"reference": "457ba76395955926a67ea692957b0872dead5278" "reference": "60c54346958604379392672a3a998650a169a7f4"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/Serializer/zipball/457ba76395955926a67ea692957b0872dead5278", "url": "https://api.github.com/repos/symfony/Serializer/zipball/60c54346958604379392672a3a998650a169a7f4",
"reference": "457ba76395955926a67ea692957b0872dead5278", "reference": "60c54346958604379392672a3a998650a169a7f4",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1686,7 +1753,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1710,7 +1777,7 @@
], ],
"description": "Symfony Serializer Component", "description": "Symfony Serializer Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-07-21 12:12:18" "time": "2014-01-01 08:14:50"
}, },
{ {
"name": "symfony/translation", "name": "symfony/translation",
@ -1769,31 +1836,35 @@
}, },
{ {
"name": "symfony/validator", "name": "symfony/validator",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/Validator", "target-dir": "Symfony/Component/Validator",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/Validator.git", "url": "https://github.com/symfony/Validator.git",
"reference": "8f6f6be47fb8e1179cd225b1f949630e26221e42" "reference": "7ea4e53f8d68bf3ae9cca28765d49d7930618730"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/Validator/zipball/8f6f6be47fb8e1179cd225b1f949630e26221e42", "url": "https://api.github.com/repos/symfony/Validator/zipball/7ea4e53f8d68bf3ae9cca28765d49d7930618730",
"reference": "8f6f6be47fb8e1179cd225b1f949630e26221e42", "reference": "7ea4e53f8d68bf3ae9cca28765d49d7930618730",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=5.3.3", "php": ">=5.3.3",
"symfony/property-access": "~2.2",
"symfony/translation": "~2.0" "symfony/translation": "~2.0"
}, },
"require-dev": { "require-dev": {
"doctrine/annotations": "~1.0",
"doctrine/cache": "~1.0",
"symfony/config": "~2.2", "symfony/config": "~2.2",
"symfony/http-foundation": "~2.1", "symfony/http-foundation": "~2.1",
"symfony/intl": "~2.3", "symfony/intl": "~2.3",
"symfony/yaml": "~2.0" "symfony/yaml": "~2.0"
}, },
"suggest": { "suggest": {
"doctrine/common": "", "doctrine/annotations": "For using the annotation mapping. You will also need doctrine/cache.",
"doctrine/cache": "For using the default cached annotation reader",
"symfony/config": "", "symfony/config": "",
"symfony/http-foundation": "", "symfony/http-foundation": "",
"symfony/intl": "", "symfony/intl": "",
@ -1802,7 +1873,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1826,21 +1897,21 @@
], ],
"description": "Symfony Validator Component", "description": "Symfony Validator Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-24 15:26:22" "time": "2014-01-01 08:14:50"
}, },
{ {
"name": "symfony/yaml", "name": "symfony/yaml",
"version": "v2.3.4", "version": "v2.4.1",
"target-dir": "Symfony/Component/Yaml", "target-dir": "Symfony/Component/Yaml",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/Yaml.git", "url": "https://github.com/symfony/Yaml.git",
"reference": "5a279f1b5f5e1045a6c432354d9ea727ff3a9847" "reference": "4e1a237fc48145fae114b96458d799746ad89aa0"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/Yaml/zipball/5a279f1b5f5e1045a6c432354d9ea727ff3a9847", "url": "https://api.github.com/repos/symfony/Yaml/zipball/4e1a237fc48145fae114b96458d799746ad89aa0",
"reference": "5a279f1b5f5e1045a6c432354d9ea727ff3a9847", "reference": "4e1a237fc48145fae114b96458d799746ad89aa0",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1849,7 +1920,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -1873,7 +1944,7 @@
], ],
"description": "Symfony Yaml Component", "description": "Symfony Yaml Component",
"homepage": "http://symfony.com", "homepage": "http://symfony.com",
"time": "2013-08-24 15:26:22" "time": "2013-12-28 08:12:03"
}, },
{ {
"name": "twig/twig", "name": "twig/twig",

View File

@ -143,7 +143,7 @@ class PathProcessorLanguage implements InboundPathProcessorInterface, OutboundPa
list( , $port) = explode(':', $normalized_base_url); list( , $port) = explode(':', $normalized_base_url);
$options['base_url'] .= ':' . $port; $options['base_url'] .= ':' . $port;
} }
elseif ($port != 80) { elseif (($url_scheme == 'http' && $port != 80) || ($url_scheme == 'https' && $port != 443)) {
$options['base_url'] .= ':' . $port; $options['base_url'] .= ':' . $port;
} }

View File

@ -125,7 +125,9 @@ class LanguageUrlRewritingTest extends WebTestBase {
// URLs as well. // URLs as well.
$index_php = strpos(url('', array('absolute' => TRUE)), 'index.php') !== FALSE; $index_php = strpos(url('', array('absolute' => TRUE)), 'index.php') !== FALSE;
$request = $this->prepareRequestForGenerator(TRUE, array('SERVER_PORT' => '88')); $request = Request::createFromGlobals();
$server = $request->server->all();
$request = $this->prepareRequestForGenerator(TRUE, array('HTTP_HOST' => $server['HTTP_HOST'] . ':88'));
// Create an absolute French link. // Create an absolute French link.
$language = language_load('fr'); $language = language_load('fr');

View File

@ -4,4 +4,4 @@
require_once __DIR__ . '/composer' . '/autoload_real.php'; require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit50432d86c534be2ddddf85d27e021721::getLoader(); return ComposerAutoloaderInit3a54ed71987dfc252758278dbd0c6099::getLoader();

View File

@ -15,6 +15,7 @@ return array(
'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'), 'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
'Symfony\\Component\\Serializer\\' => array($vendorDir . '/symfony/serializer'), 'Symfony\\Component\\Serializer\\' => array($vendorDir . '/symfony/serializer'),
'Symfony\\Component\\Routing\\' => array($vendorDir . '/symfony/routing'), 'Symfony\\Component\\Routing\\' => array($vendorDir . '/symfony/routing'),
'Symfony\\Component\\PropertyAccess\\' => array($vendorDir . '/symfony/property-access'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'), 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'), 'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'),
'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'), 'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'),

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer // autoload_real.php @generated by Composer
class ComposerAutoloaderInit50432d86c534be2ddddf85d27e021721 class ComposerAutoloaderInit3a54ed71987dfc252758278dbd0c6099
{ {
private static $loader; private static $loader;
@ -19,9 +19,9 @@ class ComposerAutoloaderInit50432d86c534be2ddddf85d27e021721
return self::$loader; return self::$loader;
} }
spl_autoload_register(array('ComposerAutoloaderInit50432d86c534be2ddddf85d27e021721', 'loadClassLoader'), true, true); spl_autoload_register(array('ComposerAutoloaderInit3a54ed71987dfc252758278dbd0c6099', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(); self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit50432d86c534be2ddddf85d27e021721', 'loadClassLoader')); spl_autoload_unregister(array('ComposerAutoloaderInit3a54ed71987dfc252758278dbd0c6099', 'loadClassLoader'));
$vendorDir = dirname(__DIR__); $vendorDir = dirname(__DIR__);
$baseDir = dirname(dirname($vendorDir)); $baseDir = dirname(dirname($vendorDir));

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,11 @@
CHANGELOG CHANGELOG
========= =========
2.4.0
-----
* deprecated the DebugClassLoader as it has been moved to the Debug component instead
2.3.0 2.3.0
----- -----

View File

@ -53,7 +53,7 @@ class ClassCollectionLoader
$classes = array_diff($classes, $declared); $classes = array_diff($classes, $declared);
// the cache is different depending on which classes are already declared // the cache is different depending on which classes are already declared
$name = $name.'-'.substr(md5(implode('|', $classes)), 0, 5); $name = $name.'-'.substr(hash('sha256', implode('|', $classes)), 0, 5);
} }
$classes = array_unique($classes); $classes = array_unique($classes);

View File

@ -39,7 +39,7 @@ class ClassMapGenerator
/** /**
* Iterate over all files in the given directory searching for classes * Iterate over all files in the given directory searching for classes
* *
* @param Iterator|string $dir The directory to search in or an iterator * @param \Iterator|string $dir The directory to search in or an iterator
* *
* @return array A class map array * @return array A class map array
*/ */

View File

@ -22,6 +22,8 @@ namespace Symfony\Component\ClassLoader;
* @author Christophe Coevoet <stof@notk.org> * @author Christophe Coevoet <stof@notk.org>
* *
* @api * @api
*
* @deprecated Deprecated since version 2.4, to be removed in 3.0. Use the DebugClassLoader provided by the Debug component instead.
*/ */
class DebugClassLoader class DebugClassLoader
{ {
@ -39,6 +41,16 @@ class DebugClassLoader
$this->classFinder = $classFinder; $this->classFinder = $classFinder;
} }
/**
* Gets the wrapped class loader.
*
* @return object a class loader instance
*/
public function getClassLoader()
{
return $this->classFinder;
}
/** /**
* Replaces all autoloaders implementing a findFile method by a DebugClassLoader wrapper. * Replaces all autoloaders implementing a findFile method by a DebugClassLoader wrapper.
*/ */

View File

@ -65,5 +65,5 @@ Resources
You can run the unit tests with the following command: You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/ClassLoader/ $ cd path/to/Symfony/Component/ClassLoader/
$ composer.phar install --dev $ composer.phar install
$ phpunit $ phpunit

View File

@ -189,7 +189,7 @@ class ClassCollectionLoaderTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException InvalidArgumentException * @expectedException \InvalidArgumentException
*/ */
public function testUnableToLoadClassException() public function testUnableToLoadClassException()
{ {

View File

@ -72,7 +72,7 @@ class ClassLoaderTest extends \PHPUnit_Framework_TestCase
public function getLoadNonexistentClassTests() public function getLoadNonexistentClassTests()
{ {
return array( return array(
array('\\Pearlike3_Bar', '\\Pearlike3_Bar', '->loadClass() loads non exising Pearlike3_Bar class with a leading slash'), array('\\Pearlike3_Bar', '\\Pearlike3_Bar', '->loadClass() loads non existing Pearlike3_Bar class with a leading slash'),
); );
} }

View File

@ -120,10 +120,6 @@ class ClassMapGeneratorTest extends \PHPUnit_Framework_TestCase
public function testCreateMapFinderSupport() public function testCreateMapFinderSupport()
{ {
if (!class_exists('Symfony\\Component\\Finder\\Finder')) {
$this->markTestSkipped('Finder component is not available');
}
$finder = new \Symfony\Component\Finder\Finder(); $finder = new \Symfony\Component\Finder\Finder();
$finder->files()->in(__DIR__.'/Fixtures/beta/NamespaceCollision'); $finder->files()->in(__DIR__.'/Fixtures/beta/NamespaceCollision');

View File

@ -1,52 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\ClassLoader\Tests;
use Symfony\Component\ClassLoader\ClassLoader;
use Symfony\Component\ClassLoader\DebugClassLoader;
class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
{
private $loader;
protected function setUp()
{
$this->loader = new ClassLoader();
spl_autoload_register(array($this->loader, 'loadClass'));
}
protected function tearDown()
{
spl_autoload_unregister(array($this->loader, 'loadClass'));
}
public function testIdempotence()
{
DebugClassLoader::enable();
DebugClassLoader::enable();
$functions = spl_autoload_functions();
foreach ($functions as $function) {
if (is_array($function) && $function[0] instanceof DebugClassLoader) {
$reflClass = new \ReflectionClass($function[0]);
$reflProp = $reflClass->getProperty('classFinder');
$reflProp->setAccessible(true);
$this->assertNotInstanceOf('Symfony\Component\ClassLoader\DebugClassLoader', $reflProp->getValue($function[0]));
return;
}
}
throw new \Exception('DebugClassLoader did not register');
}
}

View File

@ -28,7 +28,7 @@
"target-dir": "Symfony/Component/ClassLoader", "target-dir": "Symfony/Component/ClassLoader",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
} }
} }

View File

@ -1,6 +1,12 @@
CHANGELOG CHANGELOG
========= =========
2.4.0
-----
* added support for expressions in service definitions
* added ContainerAwareTrait to add default container aware behavior to a class
2.2.0 2.2.0
----- -----

View File

@ -28,6 +28,7 @@ class CheckCircularReferencesPass implements CompilerPassInterface
{ {
private $currentId; private $currentId;
private $currentPath; private $currentPath;
private $checkedNodes;
/** /**
* Checks the ContainerBuilder object for circular references. * Checks the ContainerBuilder object for circular references.
@ -38,6 +39,7 @@ class CheckCircularReferencesPass implements CompilerPassInterface
{ {
$graph = $container->getCompiler()->getServiceReferenceGraph(); $graph = $container->getCompiler()->getServiceReferenceGraph();
$this->checkedNodes = array();
foreach ($graph->getNodes() as $id => $node) { foreach ($graph->getNodes() as $id => $node) {
$this->currentId = $id; $this->currentId = $id;
$this->currentPath = array($id); $this->currentPath = array($id);
@ -58,6 +60,8 @@ class CheckCircularReferencesPass implements CompilerPassInterface
foreach ($edges as $edge) { foreach ($edges as $edge) {
$node = $edge->getDestNode(); $node = $edge->getDestNode();
$id = $node->getId(); $id = $node->getId();
if (empty($this->checkedNodes[$id])) {
$searchKey = array_search($id, $this->currentPath); $searchKey = array_search($id, $this->currentPath);
$this->currentPath[] = $id; $this->currentPath[] = $id;
@ -66,7 +70,10 @@ class CheckCircularReferencesPass implements CompilerPassInterface
} }
$this->checkOutEdges($node->getOutEdges()); $this->checkOutEdges($node->getOutEdges());
$this->checkedNodes[$id] = true;
array_pop($this->currentPath); array_pop($this->currentPath);
} }
} }
}
} }

View File

@ -74,6 +74,17 @@ class CheckDefinitionValidityPass implements CompilerPassInterface
$id $id
)); ));
} }
// tag attribute values must be scalars
foreach ($definition->getTags() as $name => $tags) {
foreach ($tags as $attributes) {
foreach ($attributes as $attribute => $value) {
if (!is_scalar($value) && null !== $value) {
throw new RuntimeException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s".', $id, $name, $attribute));
}
}
}
}
} }
} }
} }

View File

@ -12,7 +12,6 @@
namespace Symfony\Component\DependencyInjection\Compiler; namespace Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
/** /**
* This class is used to remove circular dependencies between individual passes. * This class is used to remove circular dependencies between individual passes.
@ -24,7 +23,7 @@ use Symfony\Component\DependencyInjection\Compiler\PassConfig;
class Compiler class Compiler
{ {
private $passConfig; private $passConfig;
private $log; private $log = array();
private $loggingFormatter; private $loggingFormatter;
private $serviceReferenceGraph; private $serviceReferenceGraph;
@ -36,7 +35,6 @@ class Compiler
$this->passConfig = new PassConfig(); $this->passConfig = new PassConfig();
$this->serviceReferenceGraph = new ServiceReferenceGraph(); $this->serviceReferenceGraph = new ServiceReferenceGraph();
$this->loggingFormatter = new LoggingFormatter(); $this->loggingFormatter = new LoggingFormatter();
$this->log = array();
} }
/** /**

View File

@ -117,7 +117,7 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
return true; return true;
} }
if ($definition->isPublic()) { if ($definition->isPublic() || $definition->isLazy()) {
return false; return false;
} }
@ -125,6 +125,10 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
return true; return true;
} }
if ($this->currentId == $id) {
return false;
}
$ids = array(); $ids = array();
foreach ($this->graph->getNode($id)->getInEdges() as $edge) { foreach ($this->graph->getNode($id)->getInEdges() as $edge) {
$ids[] = $edge->getSourceNode()->getId(); $ids[] = $edge->getSourceNode()->getId();

View File

@ -31,9 +31,9 @@ class PassConfig
const TYPE_REMOVE = 'removing'; const TYPE_REMOVE = 'removing';
private $mergePass; private $mergePass;
private $afterRemovingPasses; private $afterRemovingPasses = array();
private $beforeOptimizationPasses; private $beforeOptimizationPasses = array();
private $beforeRemovingPasses; private $beforeRemovingPasses = array();
private $optimizationPasses; private $optimizationPasses;
private $removingPasses; private $removingPasses;
@ -44,10 +44,6 @@ class PassConfig
{ {
$this->mergePass = new MergeExtensionConfigurationPass(); $this->mergePass = new MergeExtensionConfigurationPass();
$this->afterRemovingPasses = array();
$this->beforeOptimizationPasses = array();
$this->beforeRemovingPasses = array();
$this->optimizationPasses = array( $this->optimizationPasses = array(
new ResolveDefinitionTemplatesPass(), new ResolveDefinitionTemplatesPass(),
new ResolveParameterPlaceHoldersPass(), new ResolveParameterPlaceHoldersPass(),

View File

@ -112,7 +112,7 @@ class ResolveDefinitionTemplatesPass implements CompilerPassInterface
if (isset($changes['public'])) { if (isset($changes['public'])) {
$def->setPublic($definition->isPublic()); $def->setPublic($definition->isPublic());
} }
if (isset($changes['lazy'])){ if (isset($changes['lazy'])) {
$def->setLazy($definition->isLazy()); $def->setLazy($definition->isLazy());
} }

View File

@ -26,15 +26,7 @@ class ServiceReferenceGraph
/** /**
* @var ServiceReferenceGraphNode[] * @var ServiceReferenceGraphNode[]
*/ */
private $nodes; private $nodes = array();
/**
* Constructor.
*/
public function __construct()
{
$this->nodes = array();
}
/** /**
* Checks if the graph has a specific node. * Checks if the graph has a specific node.

View File

@ -24,8 +24,8 @@ use Symfony\Component\DependencyInjection\Alias;
class ServiceReferenceGraphNode class ServiceReferenceGraphNode
{ {
private $id; private $id;
private $inEdges; private $inEdges = array();
private $outEdges; private $outEdges = array();
private $value; private $value;
/** /**
@ -38,8 +38,6 @@ class ServiceReferenceGraphNode
{ {
$this->id = $id; $this->id = $id;
$this->value = $value; $this->value = $value;
$this->inEdges = array();
$this->outEdges = array();
} }
/** /**

View File

@ -67,13 +67,13 @@ class Container implements IntrospectableContainerInterface
*/ */
protected $parameterBag; protected $parameterBag;
protected $services; protected $services = array();
protected $methodMap; protected $methodMap = array();
protected $aliases; protected $aliases = array();
protected $scopes; protected $scopes = array();
protected $scopeChildren; protected $scopeChildren = array();
protected $scopedServices; protected $scopedServices = array();
protected $scopeStacks; protected $scopeStacks = array();
protected $loading = array(); protected $loading = array();
/** /**
@ -85,14 +85,7 @@ class Container implements IntrospectableContainerInterface
*/ */
public function __construct(ParameterBagInterface $parameterBag = null) public function __construct(ParameterBagInterface $parameterBag = null)
{ {
$this->parameterBag = null === $parameterBag ? new ParameterBag() : $parameterBag; $this->parameterBag = $parameterBag ?: new ParameterBag();
$this->services = array();
$this->aliases = array();
$this->scopes = array();
$this->scopeChildren = array();
$this->scopedServices = array();
$this->scopeStacks = array();
$this->set('service_container', $this); $this->set('service_container', $this);
} }
@ -214,7 +207,7 @@ class Container implements IntrospectableContainerInterface
$this->services[$id] = $service; $this->services[$id] = $service;
if (method_exists($this, $method = 'synchronize'.strtr($id, array('_' => '', '.' => '_')).'Service')) { if (method_exists($this, $method = 'synchronize'.strtr($id, array('_' => '', '.' => '_', '\\' => '_')).'Service')) {
$this->$method(); $this->$method();
} }
@ -240,9 +233,10 @@ class Container implements IntrospectableContainerInterface
{ {
$id = strtolower($id); $id = strtolower($id);
return array_key_exists($id, $this->services) return isset($this->services[$id])
|| array_key_exists($id, $this->aliases) || array_key_exists($id, $this->services)
|| method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service') || isset($this->aliases[$id])
|| method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_', '\\' => '_')).'Service')
; ;
} }
@ -267,17 +261,22 @@ class Container implements IntrospectableContainerInterface
*/ */
public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE) public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
{ {
// Attempt to retrieve the service by checking first aliases then
// available services. Service IDs are case insensitive, however since
// this method can be called thousands of times during a request, avoid
// calling strtolower() unless necessary.
foreach (array(false, true) as $strtolower) {
if ($strtolower) {
$id = strtolower($id); $id = strtolower($id);
}
// resolve aliases
if (isset($this->aliases[$id])) { if (isset($this->aliases[$id])) {
$id = $this->aliases[$id]; $id = $this->aliases[$id];
} }
// Re-use shared service instance if it exists.
// re-use shared service instance if it exists if (isset($this->services[$id]) || array_key_exists($id, $this->services)) {
if (array_key_exists($id, $this->services)) {
return $this->services[$id]; return $this->services[$id];
} }
}
if (isset($this->loading[$id])) { if (isset($this->loading[$id])) {
throw new ServiceCircularReferenceException($id, array_keys($this->loading)); throw new ServiceCircularReferenceException($id, array_keys($this->loading));
@ -285,7 +284,7 @@ class Container implements IntrospectableContainerInterface
if (isset($this->methodMap[$id])) { if (isset($this->methodMap[$id])) {
$method = $this->methodMap[$id]; $method = $this->methodMap[$id];
} elseif (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) { } elseif (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_', '\\' => '_')).'Service')) {
// $method is set to the right value, proceed // $method is set to the right value, proceed
} else { } else {
if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) { if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
@ -339,7 +338,9 @@ class Container implements IntrospectableContainerInterface
*/ */
public function initialized($id) public function initialized($id)
{ {
return array_key_exists(strtolower($id), $this->services); $id = strtolower($id);
return isset($this->services[$id]) || array_key_exists($id, $this->services);
} }
/** /**
@ -524,7 +525,7 @@ class Container implements IntrospectableContainerInterface
*/ */
public static function camelize($id) public static function camelize($id)
{ {
return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ '))), array(' ' => '')); return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
} }
/** /**

View File

@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection;
/**
* ContainerAware trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait ContainerAwareTrait
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* Sets the Container associated with this Controller.
*
* @param ContainerInterface $container A ContainerInterface instance
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}

View File

@ -24,6 +24,7 @@ use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
use Symfony\Component\ExpressionLanguage\Expression;
/** /**
* ContainerBuilder is a DI container that provides an API to easily describe services. * ContainerBuilder is a DI container that provides an API to easily describe services.
@ -78,6 +79,11 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/ */
private $proxyInstantiator; private $proxyInstantiator;
/**
* @var ExpressionLanguage|null
*/
private $expressionLanguage;
/** /**
* Sets the track resources flag. * Sets the track resources flag.
* *
@ -305,11 +311,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/ */
public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION) public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION)
{ {
if (null === $this->compiler) { $this->getCompiler()->addPass($pass, $type);
$this->compiler = new Compiler();
}
$this->compiler->addPass($pass, $type);
$this->addObjectResource($pass); $this->addObjectResource($pass);
@ -325,11 +327,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/ */
public function getCompilerPassConfig() public function getCompilerPassConfig()
{ {
if (null === $this->compiler) { return $this->getCompiler()->getPassConfig();
$this->compiler = new Compiler();
}
return $this->compiler->getPassConfig();
} }
/** /**
@ -610,15 +608,17 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/ */
public function compile() public function compile()
{ {
if (null === $this->compiler) { $compiler = $this->getCompiler();
$this->compiler = new Compiler();
}
if ($this->trackResources) { if ($this->trackResources) {
foreach ($this->compiler->getPassConfig()->getPasses() as $pass) { foreach ($compiler->getPassConfig()->getPasses() as $pass) {
$this->addObjectResource($pass); $this->addObjectResource($pass);
} }
}
$compiler->compile($this);
if ($this->trackResources) {
foreach ($this->definitions as $definition) { foreach ($this->definitions as $definition) {
if ($definition->isLazy() && ($class = $definition->getClass()) && class_exists($class)) { if ($definition->isLazy() && ($class = $definition->getClass()) && class_exists($class)) {
$this->addClassResource(new \ReflectionClass($class)); $this->addClassResource(new \ReflectionClass($class));
@ -626,8 +626,6 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
} }
} }
$this->compiler->compile($this);
$this->extensionConfigs = array(); $this->extensionConfigs = array();
parent::compile(); parent::compile();
@ -993,11 +991,12 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
} }
/** /**
* Replaces service references by the real service instance. * Replaces service references by the real service instance and evaluates expressions.
* *
* @param mixed $value A value * @param mixed $value A value
* *
* @return mixed The same value with all service references replaced by the real service instances * @return mixed The same value with all service references replaced by
* the real service instances and all expressions evaluated
*/ */
public function resolveServices($value) public function resolveServices($value)
{ {
@ -1009,6 +1008,8 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
$value = $this->get((string) $value, $value->getInvalidBehavior()); $value = $this->get((string) $value, $value->getInvalidBehavior());
} elseif ($value instanceof Definition) { } elseif ($value instanceof Definition) {
$value = $this->createService($value, null); $value = $this->createService($value, null);
} elseif ($value instanceof Expression) {
$value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this));
} }
return $value; return $value;
@ -1159,4 +1160,16 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
} }
} }
} }
private function getExpressionLanguage()
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage();
}
return $this->expressionLanguage;
}
} }

View File

@ -28,23 +28,23 @@ class Definition
private $factoryClass; private $factoryClass;
private $factoryMethod; private $factoryMethod;
private $factoryService; private $factoryService;
private $scope; private $scope = ContainerInterface::SCOPE_CONTAINER;
private $properties; private $properties = array();
private $calls; private $calls = array();
private $configurator; private $configurator;
private $tags; private $tags = array();
private $public; private $public = true;
private $synthetic; private $synthetic = false;
private $abstract; private $abstract = false;
private $synchronized; private $synchronized = false;
private $lazy; private $lazy = false;
protected $arguments; protected $arguments;
/** /**
* Constructor. * Constructor.
* *
* @param string $class The service class * @param string|null $class The service class
* @param array $arguments An array of arguments to pass to the service constructor * @param array $arguments An array of arguments to pass to the service constructor
* *
* @api * @api
@ -53,15 +53,6 @@ class Definition
{ {
$this->class = $class; $this->class = $class;
$this->arguments = $arguments; $this->arguments = $arguments;
$this->calls = array();
$this->scope = ContainerInterface::SCOPE_CONTAINER;
$this->tags = array();
$this->public = true;
$this->synthetic = false;
$this->synchronized = false;
$this->lazy = false;
$this->abstract = false;
$this->properties = array();
} }
/** /**
@ -84,7 +75,7 @@ class Definition
/** /**
* Gets the factory class. * Gets the factory class.
* *
* @return string The factory class name * @return string|null The factory class name
* *
* @api * @api
*/ */
@ -112,7 +103,7 @@ class Definition
/** /**
* Gets the factory method. * Gets the factory method.
* *
* @return string The factory method name * @return string|null The factory method name
* *
* @api * @api
*/ */
@ -140,7 +131,7 @@ class Definition
/** /**
* Gets the factory service id. * Gets the factory service id.
* *
* @return string The factory service id * @return string|null The factory service id
* *
* @api * @api
*/ */
@ -168,7 +159,7 @@ class Definition
/** /**
* Gets the service class. * Gets the service class.
* *
* @return string The service class * @return string|null The service class
* *
* @api * @api
*/ */
@ -508,7 +499,7 @@ class Definition
/** /**
* Gets the file to require before creating the service. * Gets the file to require before creating the service.
* *
* @return string The full pathname to include * @return string|null The full pathname to include
* *
* @api * @api
*/ */
@ -704,7 +695,7 @@ class Definition
/** /**
* Gets the configurator to call after the service is fully initialized. * Gets the configurator to call after the service is fully initialized.
* *
* @return callable The PHP callable to call * @return callable|null The PHP callable to call
* *
* @api * @api
*/ */

View File

@ -24,7 +24,7 @@ use Symfony\Component\DependencyInjection\Exception\OutOfBoundsException;
class DefinitionDecorator extends Definition class DefinitionDecorator extends Definition
{ {
private $parent; private $parent;
private $changes; private $changes = array();
/** /**
* Constructor. * Constructor.
@ -38,7 +38,6 @@ class DefinitionDecorator extends Definition
parent::__construct(); parent::__construct();
$this->parent = $parent; $this->parent = $parent;
$this->changes = array();
} }
/** /**

View File

@ -23,6 +23,8 @@ use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;
use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;
use Symfony\Component\DependencyInjection\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\Expression;
/** /**
* PhpDumper dumps a service container as a PHP class. * PhpDumper dumps a service container as a PHP class.
@ -51,6 +53,7 @@ class PhpDumper extends Dumper
private $referenceVariables; private $referenceVariables;
private $variableCount; private $variableCount;
private $reservedVariables = array('instance', 'class'); private $reservedVariables = array('instance', 'class');
private $expressionLanguage;
/** /**
* @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface
@ -86,6 +89,7 @@ class PhpDumper extends Dumper
* *
* * class: The class name * * class: The class name
* * base_class: The base class name * * base_class: The base class name
* * namespace: The class namespace
* *
* @param array $options An array of options * @param array $options An array of options
* *
@ -98,9 +102,10 @@ class PhpDumper extends Dumper
$options = array_merge(array( $options = array_merge(array(
'class' => 'ProjectServiceContainer', 'class' => 'ProjectServiceContainer',
'base_class' => 'Container', 'base_class' => 'Container',
'namespace' => '',
), $options); ), $options);
$code = $this->startClass($options['class'], $options['base_class']); $code = $this->startClass($options['class'], $options['base_class'], $options['namespace']);
if ($this->container->isFrozen()) { if ($this->container->isFrozen()) {
$code .= $this->addFrozenConstructor(); $code .= $this->addFrozenConstructor();
@ -188,7 +193,7 @@ class PhpDumper extends Dumper
*/ */
private function addProxyClasses() private function addProxyClasses()
{ {
/* @var $proxyDefinitions Definition[] */ /* @var $definitions Definition[] */
$definitions = array_filter( $definitions = array_filter(
$this->container->getDefinitions(), $this->container->getDefinitions(),
array($this->getProxyDumper(), 'isProxyCandidate') array($this->getProxyDumper(), 'isProxyCandidate')
@ -441,6 +446,12 @@ class PhpDumper extends Dumper
continue; continue;
} }
// if the instance is simple, the return statement has already been generated
// so, the only possible way to get there is because of a circular reference
if ($this->isSimpleInstance($id, $definition)) {
throw new ServiceCircularReferenceException($id, array($id));
}
$name = (string) $this->definitionVariables->offsetGet($iDefinition); $name = (string) $this->definitionVariables->offsetGet($iDefinition);
$code .= $this->addServiceMethodCalls(null, $iDefinition, $name); $code .= $this->addServiceMethodCalls(null, $iDefinition, $name);
$code .= $this->addServiceProperties(null, $iDefinition, $name); $code .= $this->addServiceProperties(null, $iDefinition, $name);
@ -700,24 +711,24 @@ EOF;
* *
* @param string $class Class name * @param string $class Class name
* @param string $baseClass The name of the base class * @param string $baseClass The name of the base class
* @param string $namespace The class namespace
* *
* @return string * @return string
*/ */
private function startClass($class, $baseClass) private function startClass($class, $baseClass, $namespace)
{ {
$bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;'; $bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;';
$namespaceLine = $namespace ? "namespace $namespace;\n" : '';
return <<<EOF return <<<EOF
<?php <?php
$namespaceLine
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException; use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
$bagClass $bagClass
/** /**
@ -969,6 +980,8 @@ EOF;
throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', $value->getClass(), $path.'/'.$key)); throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', $value->getClass(), $path.'/'.$key));
} elseif ($value instanceof Reference) { } elseif ($value instanceof Reference) {
throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', $value, $path.'/'.$key)); throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', $value, $path.'/'.$key));
} elseif ($value instanceof Expression) {
throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key));
} else { } else {
$value = var_export($value, true); $value = var_export($value, true);
} }
@ -1105,7 +1118,7 @@ EOF;
* *
* @return Boolean * @return Boolean
*/ */
private function hasReference($id, array $arguments, $deep = false, $visited = array()) private function hasReference($id, array $arguments, $deep = false, array $visited = array())
{ {
foreach ($arguments as $argument) { foreach ($arguments as $argument) {
if (is_array($argument)) { if (is_array($argument)) {
@ -1113,14 +1126,15 @@ EOF;
return true; return true;
} }
} elseif ($argument instanceof Reference) { } elseif ($argument instanceof Reference) {
if ($id === (string) $argument) { $argumentId = (string) $argument;
if ($id === $argumentId) {
return true; return true;
} }
if ($deep && !isset($visited[(string) $argument])) { if ($deep && !isset($visited[$argumentId])) {
$visited[(string) $argument] = true; $visited[$argumentId] = true;
$service = $this->container->getDefinition((string) $argument); $service = $this->container->getDefinition($argumentId);
$arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties()); $arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties());
if ($this->hasReference($id, $arguments, $deep, $visited)) { if ($this->hasReference($id, $arguments, $deep, $visited)) {
@ -1192,6 +1206,8 @@ EOF;
} }
return $this->getServiceCall((string) $value, $value); return $this->getServiceCall((string) $value, $value);
} elseif ($value instanceof Expression) {
return $this->getExpressionLanguage()->compile((string) $value, array('container'));
} elseif ($value instanceof Parameter) { } elseif ($value instanceof Parameter) {
return $this->dumpParameter($value); return $this->dumpParameter($value);
} elseif (true === $interpolate && is_string($value)) { } elseif (true === $interpolate && is_string($value)) {
@ -1314,4 +1330,16 @@ EOF;
return $name; return $name;
} }
} }
private function getExpressionLanguage()
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage();
}
return $this->expressionLanguage;
}
} }

View File

@ -17,6 +17,7 @@ use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\ExpressionLanguage\Expression;
/** /**
* XmlDumper dumps a service container as an XML string. * XmlDumper dumps a service container as an XML string.
@ -259,6 +260,10 @@ class XmlDumper extends Dumper
} elseif ($value instanceof Definition) { } elseif ($value instanceof Definition) {
$element->setAttribute('type', 'service'); $element->setAttribute('type', 'service');
$this->addService($value, null, $element); $this->addService($value, null, $element);
} elseif ($value instanceof Expression) {
$element->setAttribute('type', 'expression');
$text = $this->document->createTextNode(self::phpToXml((string) $value));
$element->appendChild($text);
} else { } else {
if (in_array($value, array('null', 'true', 'false'), true)) { if (in_array($value, array('null', 'true', 'false'), true)) {
$element->setAttribute('type', 'string'); $element->setAttribute('type', 'string');

View File

@ -19,6 +19,7 @@ use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\ExpressionLanguage\Expression;
/** /**
* YamlDumper dumps a service container as a YAML string. * YamlDumper dumps a service container as a YAML string.
@ -74,6 +75,10 @@ class YamlDumper extends Dumper
$code .= sprintf(" class: %s\n", $definition->getClass()); $code .= sprintf(" class: %s\n", $definition->getClass());
} }
if (!$definition->isPublic()) {
$code .= " public: false\n";
}
$tagsCode = ''; $tagsCode = '';
foreach ($definition->getTags() as $name => $tags) { foreach ($definition->getTags() as $name => $tags) {
foreach ($tags as $attributes) { foreach ($tags as $attributes) {
@ -231,6 +236,8 @@ class YamlDumper extends Dumper
return $this->getServiceCall((string) $value, $value); return $this->getServiceCall((string) $value, $value);
} elseif ($value instanceof Parameter) { } elseif ($value instanceof Parameter) {
return $this->getParameterCall((string) $value); return $this->getParameterCall((string) $value);
} elseif ($value instanceof Expression) {
return $this->getExpressionCall((string) $value);
} elseif (is_object($value) || is_resource($value)) { } elseif (is_object($value) || is_resource($value)) {
throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
} }
@ -267,6 +274,11 @@ class YamlDumper extends Dumper
return sprintf('%%%s%%', $id); return sprintf('%%%s%%', $id);
} }
private function getExpressionCall($expression)
{
return sprintf('@=%s', $expression);
}
/** /**
* Prepares parameters. * Prepares parameters.
* *

View File

@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
/**
* Adds some function to the default ExpressionLanguage.
*
* To get a service, use service('request').
* To get a parameter, use parameter('kernel.debug').
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionLanguage extends BaseExpressionLanguage
{
protected function registerFunctions()
{
parent::registerFunctions();
$this->register('service', function ($arg) {
return sprintf('$this->get(%s)', $arg);
}, function (array $variables, $value) {
return $variables['container']->get($value);
});
$this->register('parameter', function ($arg) {
return sprintf('$this->getParameter(%s)', $arg);
}, function (array $variables, $value) {
return $variables['container']->getParameter($value);
});
}
}

View File

@ -28,7 +28,7 @@ interface ExtensionInterface
* @param array $config An array of configuration values * @param array $config An array of configuration values
* @param ContainerBuilder $container A ContainerBuilder instance * @param ContainerBuilder $container A ContainerBuilder instance
* *
* @throws InvalidArgumentException When provided tag is not defined in this extension * @throws \InvalidArgumentException When provided tag is not defined in this extension
* *
* @api * @api
*/ */

View File

@ -14,7 +14,7 @@ namespace Symfony\Component\DependencyInjection\LazyProxy\PhpDumper;
use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Definition;
/** /**
* Lazy proxy dumper capable of generating the instantiation logic php code for proxied services. * Lazy proxy dumper capable of generating the instantiation logic PHP code for proxied services.
* *
* @author Marco Pivetta <ocramius@gmail.com> * @author Marco Pivetta <ocramius@gmail.com>
*/ */

View File

@ -17,7 +17,7 @@ use Symfony\Component\Config\Resource\FileResource;
* PhpFileLoader loads service definitions from a PHP file. * PhpFileLoader loads service definitions from a PHP file.
* *
* The PHP file is required and the $container variable can be * The PHP file is required and the $container variable can be
* used form the file to change the container. * used within the file to change the container.
* *
* @author Fabien Potencier <fabien@symfony.com> * @author Fabien Potencier <fabien@symfony.com>
*/ */

View File

@ -187,6 +187,10 @@ class XmlFileLoader extends FileLoader
continue; continue;
} }
if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
$parameters[$normalizedName] = SimpleXMLElement::phpize($value);
}
// keep not normalized key for BC too
$parameters[$name] = SimpleXMLElement::phpize($value); $parameters[$name] = SimpleXMLElement::phpize($value);
} }
@ -233,10 +237,11 @@ class XmlFileLoader extends FileLoader
if (false !== $nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) { if (false !== $nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) {
foreach ($nodes as $node) { foreach ($nodes as $node) {
// give it a unique name // give it a unique name
$node['id'] = sprintf('%s_%d', md5($file), ++$count); $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
$node['id'] = $id;
$definitions[(string) $node['id']] = array($node->service, $file, false); $definitions[$id] = array($node->service, $file, false);
$node->service['id'] = (string) $node['id']; $node->service['id'] = $id;
} }
} }
@ -244,10 +249,11 @@ class XmlFileLoader extends FileLoader
if (false !== $nodes = $xml->xpath('//container:services/container:service[not(@id)]')) { if (false !== $nodes = $xml->xpath('//container:services/container:service[not(@id)]')) {
foreach ($nodes as $node) { foreach ($nodes as $node) {
// give it a unique name // give it a unique name
$node['id'] = sprintf('%s_%d', md5($file), ++$count); $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
$node['id'] = $id;
$definitions[(string) $node['id']] = array($node, $file, true); $definitions[$id] = array($node, $file, true);
$node->service['id'] = (string) $node['id']; $node->service['id'] = $id;
} }
} }

View File

@ -19,6 +19,7 @@ use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Yaml\Parser as YamlParser; use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\ExpressionLanguage\Expression;
/** /**
* YamlFileLoader loads YAML files service definitions. * YamlFileLoader loads YAML files service definitions.
@ -224,8 +225,8 @@ class YamlFileLoader extends FileLoader
unset($tag['name']); unset($tag['name']);
foreach ($tag as $attribute => $value) { foreach ($tag as $attribute => $value) {
if (!is_scalar($value)) { if (!is_scalar($value) && null !== $value) {
throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s" in %s.', $id, $name, $file)); throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s.', $id, $name, $attribute, $file));
} }
} }
@ -311,6 +312,8 @@ class YamlFileLoader extends FileLoader
{ {
if (is_array($value)) { if (is_array($value)) {
$value = array_map(array($this, 'resolveServices'), $value); $value = array_map(array($this, 'resolveServices'), $value);
} elseif (is_string($value) && 0 === strpos($value, '@=')) {
return new Expression(substr($value, 2));
} elseif (is_string($value) && 0 === strpos($value, '@')) { } elseif (is_string($value) && 0 === strpos($value, '@')) {
if (0 === strpos($value, '@@')) { if (0 === strpos($value, '@@')) {
$value = substr($value, 1); $value = substr($value, 1);

View File

@ -121,10 +121,12 @@
<xsd:complexType name="property" mixed="true"> <xsd:complexType name="property" mixed="true">
<xsd:choice minOccurs="0" maxOccurs="1"> <xsd:choice minOccurs="0" maxOccurs="1">
<xsd:element name="property" type="property" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="service" type="service" /> <xsd:element name="service" type="service" />
</xsd:choice> </xsd:choice>
<xsd:attribute name="type" type="argument_type" /> <xsd:attribute name="type" type="argument_type" />
<xsd:attribute name="id" type="xsd:string" /> <xsd:attribute name="id" type="xsd:string" />
<xsd:attribute name="key" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="on-invalid" type="xsd:string" /> <xsd:attribute name="on-invalid" type="xsd:string" />
<xsd:attribute name="strict" type="boolean" /> <xsd:attribute name="strict" type="boolean" />
@ -164,6 +166,7 @@
<xsd:restriction base="xsd:string"> <xsd:restriction base="xsd:string">
<xsd:enumeration value="collection" /> <xsd:enumeration value="collection" />
<xsd:enumeration value="service" /> <xsd:enumeration value="service" />
<xsd:enumeration value="expression" />
<xsd:enumeration value="string" /> <xsd:enumeration value="string" />
<xsd:enumeration value="constant" /> <xsd:enumeration value="constant" />
</xsd:restriction> </xsd:restriction>

View File

@ -24,8 +24,8 @@ use Symfony\Component\DependencyInjection\Exception\RuntimeException;
*/ */
class ParameterBag implements ParameterBagInterface class ParameterBag implements ParameterBagInterface
{ {
protected $parameters; protected $parameters = array();
protected $resolved; protected $resolved = false;
/** /**
* Constructor. * Constructor.
@ -36,9 +36,7 @@ class ParameterBag implements ParameterBagInterface
*/ */
public function __construct(array $parameters = array()) public function __construct(array $parameters = array())
{ {
$this->parameters = array();
$this->add($parameters); $this->add($parameters);
$this->resolved = false;
} }
/** /**

View File

@ -69,5 +69,5 @@ Resources
You can run the unit tests with the following command: You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/DependencyInjection/ $ cd path/to/Symfony/Component/DependencyInjection/
$ composer.phar install --dev $ composer.phar install
$ phpunit $ phpunit

View File

@ -47,7 +47,7 @@ class Reference
*/ */
public function __toString() public function __toString()
{ {
return (string) $this->id; return $this->id;
} }
/** /**

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection; namespace Symfony\Component\DependencyInjection;
use Symfony\Component\Config\Util\XmlUtils; use Symfony\Component\Config\Util\XmlUtils;
use Symfony\Component\ExpressionLanguage\Expression;
/** /**
* SimpleXMLElement class. * SimpleXMLElement class.
@ -21,7 +22,7 @@ use Symfony\Component\Config\Util\XmlUtils;
class SimpleXMLElement extends \SimpleXMLElement class SimpleXMLElement extends \SimpleXMLElement
{ {
/** /**
* Converts an attribute as a php type. * Converts an attribute as a PHP type.
* *
* @param string $name * @param string $name
* *
@ -33,7 +34,7 @@ class SimpleXMLElement extends \SimpleXMLElement
} }
/** /**
* Returns arguments as valid php types. * Returns arguments as valid PHP types.
* *
* @param string $name * @param string $name
* @param Boolean $lowercase * @param Boolean $lowercase
@ -77,6 +78,9 @@ class SimpleXMLElement extends \SimpleXMLElement
$arguments[$key] = new Reference((string) $arg['id'], $invalidBehavior, $strict); $arguments[$key] = new Reference((string) $arg['id'], $invalidBehavior, $strict);
break; break;
case 'expression':
$arguments[$key] = new Expression((string) $arg);
break;
case 'collection': case 'collection':
$arguments[$key] = $arg->getArgumentsAsPhp($name, false); $arguments[$key] = $arg->getArgumentsAsPhp($name, false);
break; break;
@ -95,7 +99,7 @@ class SimpleXMLElement extends \SimpleXMLElement
} }
/** /**
* Converts an xml value to a php type. * Converts an xml value to a PHP type.
* *
* @param mixed $value * @param mixed $value
* *

View File

@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase
{ {
/** /**
* @expectedException \RuntimeException * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/ */
public function testProcessDetectsSyntheticNonPublicDefinitions() public function testProcessDetectsSyntheticNonPublicDefinitions()
{ {
@ -29,7 +29,7 @@ class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException \RuntimeException * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/ */
public function testProcessDetectsSyntheticPrototypeDefinitions() public function testProcessDetectsSyntheticPrototypeDefinitions()
{ {
@ -40,7 +40,7 @@ class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException \RuntimeException * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/ */
public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass() public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass()
{ {
@ -61,6 +61,28 @@ class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase
$this->process($container); $this->process($container);
} }
public function testValidTags()
{
$container = new ContainerBuilder();
$container->register('a', 'class')->addTag('foo', array('bar' => 'baz'));
$container->register('b', 'class')->addTag('foo', array('bar' => null));
$container->register('c', 'class')->addTag('foo', array('bar' => 1));
$container->register('d', 'class')->addTag('foo', array('bar' => 1.1));
$this->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testInvalidTags()
{
$container = new ContainerBuilder();
$container->register('a', 'class')->addTag('foo', array('bar' => array('baz' => 'baz')));
$this->process($container);
}
protected function process(ContainerBuilder $container) protected function process(ContainerBuilder $container)
{ {
$pass = new CheckDefinitionValidityPass(); $pass = new CheckDefinitionValidityPass();

View File

@ -12,10 +12,8 @@
namespace Symfony\Component\DependencyInjection\Tests\Compiler; namespace Symfony\Component\DependencyInjection\Tests\Compiler;
use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
use Symfony\Component\DependencyInjection\Compiler\Compiler;
use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Compiler\RepeatedPass;
use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass; use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
@ -126,6 +124,41 @@ class InlineServiceDefinitionsPassTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($container->hasDefinition('a')); $this->assertTrue($container->hasDefinition('a'));
} }
public function testProcessDoesNotInlineWhenServiceIsPrivateButLazy()
{
$container = new ContainerBuilder();
$container
->register('foo')
->setPublic(false)
->setLazy(true)
;
$container
->register('service')
->setArguments(array($ref = new Reference('foo')))
;
$this->process($container);
$arguments = $container->getDefinition('service')->getArguments();
$this->assertSame($ref, $arguments[0]);
}
public function testProcessDoesNotInlineWhenServiceReferencesItself()
{
$container = new ContainerBuilder();
$container
->register('foo')
->setPublic(false)
->addMethodCall('foo', array($ref = new Reference('foo')))
;
$this->process($container);
$calls = $container->getDefinition('foo')->getMethodCalls();
$this->assertSame($ref, $calls[0][1][0]);
}
protected function process(ContainerBuilder $container) protected function process(ContainerBuilder $container)
{ {
$repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass())); $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass()));

View File

@ -21,10 +21,12 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\ExpressionLanguage\Expression;
class ContainerBuilderTest extends \PHPUnit_Framework_TestCase class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
{ {
@ -377,6 +379,15 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
$builder->get('foo'); $builder->get('foo');
} }
public function testCreateServiceWithExpression()
{
$builder = new ContainerBuilder();
$builder->setParameter('bar', 'bar');
$builder->register('bar', 'BarClass');
$builder->register('foo', 'FooClass')->addArgument(array('foo' => new Expression('service("bar").foo ~ parameter("bar")')));
$this->assertEquals('foobar', $builder->get('foo')->arguments['foo']);
}
/** /**
* @covers Symfony\Component\DependencyInjection\ContainerBuilder::resolveServices * @covers Symfony\Component\DependencyInjection\ContainerBuilder::resolveServices
*/ */
@ -386,6 +397,7 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
$builder->register('foo', 'FooClass'); $builder->register('foo', 'FooClass');
$this->assertEquals($builder->get('foo'), $builder->resolveServices(new Reference('foo')), '->resolveServices() resolves service references to service instances'); $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Reference('foo')), '->resolveServices() resolves service references to service instances');
$this->assertEquals(array('foo' => array('foo', $builder->get('foo'))), $builder->resolveServices(array('foo' => array('foo', new Reference('foo')))), '->resolveServices() resolves service references to service instances in nested arrays'); $this->assertEquals(array('foo' => array('foo', $builder->get('foo'))), $builder->resolveServices(array('foo' => array('foo', new Reference('foo')))), '->resolveServices() resolves service references to service instances in nested arrays');
$this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions');
} }
/** /**
@ -403,7 +415,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
$container->setResourceTracking(false); $container->setResourceTracking(false);
$config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%'))); $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%')));
$container->merge($config); $container->merge($config);
////// FIXME
$container->compile(); $container->compile();
$this->assertEquals(array('bar' => 'foo', 'foo' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones');
@ -411,7 +422,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
$container->setResourceTracking(false); $container->setResourceTracking(false);
$config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%', 'baz' => '%foo%'))); $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%', 'baz' => '%foo%')));
$container->merge($config); $container->merge($config);
////// FIXME
$container->compile(); $container->compile();
$this->assertEquals(array('bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones');
@ -439,7 +449,7 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
/** /**
* @covers Symfony\Component\DependencyInjection\ContainerBuilder::merge * @covers Symfony\Component\DependencyInjection\ContainerBuilder::merge
* @expectedException LogicException * @expectedException \LogicException
*/ */
public function testMergeLogicException() public function testMergeLogicException()
{ {
@ -487,10 +497,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
*/ */
public function testAddObjectResource() public function testAddObjectResource()
{ {
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$container->setResourceTracking(false); $container->setResourceTracking(false);
@ -517,10 +523,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
*/ */
public function testAddClassResource() public function testAddClassResource()
{ {
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$container->setResourceTracking(false); $container->setResourceTracking(false);
@ -547,10 +549,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
*/ */
public function testCompilesClassDefinitionsOfLazyServices() public function testCompilesClassDefinitionsOfLazyServices()
{ {
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking'); $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');
@ -577,10 +575,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
*/ */
public function testResources() public function testResources()
{ {
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$container->addResource($a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml')); $container->addResource($a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml'));
$container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml')); $container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml'));
@ -655,7 +649,7 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException BadMethodCallException * @expectedException \BadMethodCallException
*/ */
public function testThrowsExceptionWhenSetServiceOnAFrozenContainer() public function testThrowsExceptionWhenSetServiceOnAFrozenContainer()
{ {
@ -667,14 +661,10 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException BadMethodCallException * @expectedException \BadMethodCallException
*/ */
public function testThrowsExceptionWhenAddServiceOnAFrozenContainer() public function testThrowsExceptionWhenAddServiceOnAFrozenContainer()
{ {
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$container->compile(); $container->compile();
$container->set('a', new \stdClass()); $container->set('a', new \stdClass());
@ -682,10 +672,6 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
public function testNoExceptionWhenSetSyntheticServiceOnAFrozenContainer() public function testNoExceptionWhenSetSyntheticServiceOnAFrozenContainer()
{ {
if (!class_exists('Symfony\Component\Config\Resource\FileResource')) {
$this->markTestSkipped('The "Config" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$def = new Definition('stdClass'); $def = new Definition('stdClass');
$def->setSynthetic(true); $def->setSynthetic(true);
@ -742,7 +728,7 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException BadMethodCallException * @expectedException \BadMethodCallException
*/ */
public function testThrowsExceptionWhenSetDefinitionOnAFrozenContainer() public function testThrowsExceptionWhenSetDefinitionOnAFrozenContainer()
{ {
@ -773,6 +759,39 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
$configs = $container->getExtensionConfig('foo'); $configs = $container->getExtensionConfig('foo');
$this->assertEquals(array($second, $first), $configs); $this->assertEquals(array($second, $first), $configs);
} }
public function testLazyLoadedService()
{
$loader = new ClosureLoader($container = new ContainerBuilder());
$loader->load(function (ContainerBuilder $container) {
$container->set('a', new \BazClass());
$definition = new Definition('BazClass');
$definition->setLazy(true);
$container->setDefinition('a', $definition);
}
);
$container->setResourceTracking(true);
$container->compile();
$class = new \BazClass();
$reflectionClass = new \ReflectionClass($class);
$r = new \ReflectionProperty($container, 'resources');
$r->setAccessible(true);
$resources = $r->getValue($container);
$classInList = false;
foreach ($resources as $resource) {
if ($resource->getResource() === $reflectionClass->getFileName()) {
$classInList = true;
break;
}
}
$this->assertEquals(true, $classInList);
}
} }
class FooClass {} class FooClass {}

View File

@ -51,6 +51,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
array('.foo', '_Foo'), array('.foo', '_Foo'),
array('foo_', 'Foo'), array('foo_', 'Foo'),
array('foo.', 'Foo_'), array('foo.', 'Foo_'),
array('foo\bar', 'Foo_Bar'),
); );
} }
@ -187,6 +188,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($sc->__bar, $sc->get('bar'), '->get() returns the service for the given id'); $this->assertEquals($sc->__bar, $sc->get('bar'), '->get() returns the service for the given id');
$this->assertEquals($sc->__foo_bar, $sc->get('foo_bar'), '->get() returns the service if a get*Method() is defined'); $this->assertEquals($sc->__foo_bar, $sc->get('foo_bar'), '->get() returns the service if a get*Method() is defined');
$this->assertEquals($sc->__foo_baz, $sc->get('foo.baz'), '->get() returns the service if a get*Method() is defined'); $this->assertEquals($sc->__foo_baz, $sc->get('foo.baz'), '->get() returns the service if a get*Method() is defined');
$this->assertEquals($sc->__foo_baz, $sc->get('foo\\baz'), '->get() returns the service if a get*Method() is defined');
$sc->set('bar', $bar = new \stdClass()); $sc->set('bar', $bar = new \stdClass());
$this->assertEquals($bar, $sc->get('bar'), '->get() prefers to return a service defined with set() than one defined with a getXXXMethod()'); $this->assertEquals($bar, $sc->get('bar'), '->get() prefers to return a service defined with set() than one defined with a getXXXMethod()');
@ -258,6 +260,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($sc->has('bar'), '->has() returns true if a get*Method() is defined'); $this->assertTrue($sc->has('bar'), '->has() returns true if a get*Method() is defined');
$this->assertTrue($sc->has('foo_bar'), '->has() returns true if a get*Method() is defined'); $this->assertTrue($sc->has('foo_bar'), '->has() returns true if a get*Method() is defined');
$this->assertTrue($sc->has('foo.baz'), '->has() returns true if a get*Method() is defined'); $this->assertTrue($sc->has('foo.baz'), '->has() returns true if a get*Method() is defined');
$this->assertTrue($sc->has('foo\\baz'), '->has() returns true if a get*Method() is defined');
} }
/** /**

View File

@ -18,13 +18,6 @@ class CrossCheckTest extends \PHPUnit_Framework_TestCase
{ {
protected static $fixturesPath; protected static $fixturesPath;
protected function setUp()
{
if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
$this->markTestSkipped('The "Config" component is not available');
}
}
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
self::$fixturesPath = __DIR__.'/Fixtures/'; self::$fixturesPath = __DIR__.'/Fixtures/';

View File

@ -81,7 +81,7 @@ class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException InvalidArgumentException * @expectedException \InvalidArgumentException
*/ */
public function testReplaceArgumentShouldRequireIntegerIndex() public function testReplaceArgumentShouldRequireIntegerIndex()
{ {
@ -106,7 +106,7 @@ class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException OutOfBoundsException * @expectedException \OutOfBoundsException
*/ */
public function testGetArgumentShouldCheckBounds() public function testGetArgumentShouldCheckBounds()
{ {

View File

@ -275,7 +275,7 @@ class DefinitionTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException OutOfBoundsException * @expectedException \OutOfBoundsException
*/ */
public function testGetArgumentShouldCheckBounds() public function testGetArgumentShouldCheckBounds()
{ {
@ -286,7 +286,7 @@ class DefinitionTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException OutOfBoundsException * @expectedException \OutOfBoundsException
*/ */
public function testReplaceArgumentShouldCheckBounds() public function testReplaceArgumentShouldCheckBounds()
{ {

View File

@ -31,7 +31,7 @@ class PhpDumperTest extends \PHPUnit_Framework_TestCase
$dumper = new PhpDumper($container = new ContainerBuilder()); $dumper = new PhpDumper($container = new ContainerBuilder());
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class'); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class');
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(array('class' => 'Container', 'base_class' => 'AbstractContainer')), '->dump() takes a class and a base_class options'); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(array('class' => 'Container', 'base_class' => 'AbstractContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Dump')), '->dump() takes a class and a base_class options');
$container = new ContainerBuilder(); $container = new ContainerBuilder();
new PhpDumper($container); new PhpDumper($container);
@ -81,7 +81,7 @@ class PhpDumperTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException InvalidArgumentException * @expectedException \InvalidArgumentException
*/ */
public function testExportParameters() public function testExportParameters()
{ {
@ -121,7 +121,7 @@ class PhpDumperTest extends \PHPUnit_Framework_TestCase
} }
/** /**
* @expectedException InvalidArgumentException * @expectedException \InvalidArgumentException
* @expectedExceptionMessage Service id "bar$" cannot be converted to a valid PHP method name. * @expectedExceptionMessage Service id "bar$" cannot be converted to a valid PHP method name.
*/ */
public function testAddServiceInvalidServiceId() public function testAddServiceInvalidServiceId()
@ -181,4 +181,19 @@ class PhpDumperTest extends \PHPUnit_Framework_TestCase
$this->assertSame($bar, $container->get('foo')->bar, '->set() overrides an already defined service'); $this->assertSame($bar, $container->get('foo')->bar, '->set() overrides an already defined service');
} }
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
*/
public function testCircularReference()
{
$container = new ContainerBuilder();
$container->register('foo', 'stdClass')->addArgument(new Reference('bar'));
$container->register('bar', 'stdClass')->setPublic(false)->addMethodCall('setA', array(new Reference('baz')));
$container->register('baz', 'stdClass')->addMethodCall('setA', array(new Reference('foo')));
$container->compile();
$dumper = new PhpDumper($container);
$dumper->dump();
}
} }

View File

@ -18,13 +18,6 @@ class YamlDumperTest extends \PHPUnit_Framework_TestCase
{ {
protected static $fixturesPath; protected static $fixturesPath;
protected function setUp()
{
if (!class_exists('Symfony\Component\Yaml\Yaml')) {
$this->markTestSkipped('The "Yaml" component is not available');
}
}
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');

View File

@ -6,6 +6,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\ExpressionLanguage\Expression;
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$container-> $container->
@ -15,7 +16,7 @@ $container->
setFactoryClass('FooClass')-> setFactoryClass('FooClass')->
setFactoryMethod('getInstance')-> setFactoryMethod('getInstance')->
setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))-> setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))->
setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz')))-> setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')))->
addMethodCall('setBar', array(new Reference('bar')))-> addMethodCall('setBar', array(new Reference('bar')))->
addMethodCall('initialize')-> addMethodCall('initialize')->
setConfigurator('sc_configure') setConfigurator('sc_configure')
@ -50,7 +51,8 @@ $container->
addMethodCall('setBar', array(new Reference('foo')))-> addMethodCall('setBar', array(new Reference('foo')))->
addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)))-> addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)))->
addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))-> addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))->
addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))) addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))->
addMethodCall('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))
; ;
$container-> $container->
register('factory_service', 'Bar')-> register('factory_service', 'Bar')->

View File

@ -8,6 +8,7 @@ function sc_configure($instance)
class BarClass class BarClass
{ {
protected $baz; protected $baz;
public $foo = 'foo';
public function setBaz(BazClass $baz) public function setBaz(BazClass $baz)
{ {

View File

@ -6,8 +6,6 @@ use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/** /**

View File

@ -6,8 +6,6 @@ use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
/** /**

View File

@ -6,8 +6,6 @@ use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/** /**

View File

@ -6,8 +6,6 @@ use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/** /**
@ -125,6 +123,7 @@ class ProjectServiceContainer extends Container
$instance->initialize(); $instance->initialize();
$instance->foo = 'bar'; $instance->foo = 'bar';
$instance->moo = $a; $instance->moo = $a;
$instance->qux = array($this->getParameter('foo') => 'foo is '.$this->getParameter('foo').'', 'foobar' => $this->getParameter('foo'));
sc_configure($instance); sc_configure($instance);
return $instance; return $instance;
@ -198,6 +197,7 @@ class ProjectServiceContainer extends Container
if ($this->has('foobaz')) { if ($this->has('foobaz')) {
$instance->setBar($this->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE)); $instance->setBar($this->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE));
} }
$instance->setBar(($this->get("foo")->foo() . $this->getParameter("foo")));
return $instance; return $instance;
} }

View File

@ -6,8 +6,6 @@ use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
/** /**
@ -133,6 +131,7 @@ class ProjectServiceContainer extends Container
$instance->initialize(); $instance->initialize();
$instance->foo = 'bar'; $instance->foo = 'bar';
$instance->moo = $a; $instance->moo = $a;
$instance->qux = array('bar' => 'foo is bar', 'foobar' => 'bar');
sc_configure($instance); sc_configure($instance);
return $instance; return $instance;
@ -203,6 +202,7 @@ class ProjectServiceContainer extends Container
$instance->setBar($this->get('foo')); $instance->setBar($this->get('foo'));
$instance->setBar(NULL); $instance->setBar(NULL);
$instance->setBar(($this->get("foo")->foo() . $this->getParameter("foo")));
return $instance; return $instance;
} }

View File

@ -0,0 +1,16 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="foo" class="BarClass">
<tag name="foo_tag"
some-option="cat"
some_option="ciz"
other-option="lorem"
an_other-option="ipsum"
/>
</service>
</services>
</container>

View File

@ -27,5 +27,6 @@
<parameter key="MixedCase" type="collection"> <!-- Should be lower cased --> <parameter key="MixedCase" type="collection"> <!-- Should be lower cased -->
<parameter key="MixedCaseKey">value</parameter> <!-- Should stay mixed case --> <parameter key="MixedCaseKey">value</parameter> <!-- Should stay mixed case -->
</parameter> </parameter>
<parameter key="constant" type="constant">PHP_EOL</parameter>
</parameters> </parameters>
</container> </container>

View File

@ -32,6 +32,9 @@
</service> </service>
<service id="method_call1" class="FooClass"> <service id="method_call1" class="FooClass">
<call method="setBar" /> <call method="setBar" />
<call method="setBar">
<argument type="expression">service("foo").foo() ~ parameter("foo")</argument>
</call>
</service> </service>
<service id="method_call2" class="FooClass"> <service id="method_call2" class="FooClass">
<call method="setBar"> <call method="setBar">

View File

@ -19,6 +19,10 @@
<argument type="service" id="service_container"/> <argument type="service" id="service_container"/>
<property name="foo">bar</property> <property name="foo">bar</property>
<property name="moo" type="service" id="foo.baz"/> <property name="moo" type="service" id="foo.baz"/>
<property name="qux" type="collection">
<property key="%foo%">foo is %foo%</property>
<property key="foobar">%foo%</property>
</property>
<call method="setBar"> <call method="setBar">
<argument type="service" id="bar"/> <argument type="service" id="bar"/>
</call> </call>
@ -49,6 +53,9 @@
<call method="setBar"> <call method="setBar">
<argument type="service" id="foobaz" on-invalid="ignore"/> <argument type="service" id="foobaz" on-invalid="ignore"/>
</call> </call>
<call method="setBar">
<argument type="expression">service("foo").foo() ~ parameter("foo")</argument>
</call>
</service> </service>
<service id="factory_service" class="Bar" factory-method="getInstance" factory-service="foo.baz"/> <service id="factory_service" class="Bar" factory-method="getInstance" factory-service="foo.baz"/>
<service id="foo_with_inline" class="Foo"> <service id="foo_with_inline" class="Foo">

View File

@ -3,4 +3,4 @@ services:
class: FooClass class: FooClass
tags: tags:
# tag-attribute is not a scalar # tag-attribute is not a scalar
- { name: foo, foo: { foo: foo, bar: bar } } - { name: foo, bar: { foo: foo, bar: bar } }

View File

@ -15,6 +15,7 @@ services:
calls: calls:
- [ setBar, [] ] - [ setBar, [] ]
- [ setBar ] - [ setBar ]
- [ setBar, ['@=service("foo").foo() ~ parameter("foo")'] ]
method_call2: method_call2:
class: FooClass class: FooClass
calls: calls:

View File

@ -12,7 +12,7 @@ services:
factory_class: FooClass factory_class: FooClass
factory_method: getInstance factory_method: getInstance
arguments: [foo, '@foo.baz', { '%foo%': 'foo is %foo%', foobar: '%foo%' }, true, '@service_container'] arguments: [foo, '@foo.baz', { '%foo%': 'foo is %foo%', foobar: '%foo%' }, true, '@service_container']
properties: { foo: bar, moo: '@foo.baz' } properties: { foo: bar, moo: '@foo.baz', qux: { '%foo%': 'foo is %foo%', foobar: '%foo%' } }
calls: calls:
- [setBar, ['@bar']] - [setBar, ['@bar']]
- [initialize, { }] - [initialize, { }]
@ -38,6 +38,7 @@ services:
- [setBar, ['@?foo2']] - [setBar, ['@?foo2']]
- [setBar, ['@?foo3']] - [setBar, ['@?foo3']]
- [setBar, ['@?foobaz']] - [setBar, ['@?foobaz']]
- [setBar, ['@=service("foo").foo() ~ parameter("foo")']]
factory_service: factory_service:
class: Bar class: Bar
@ -50,6 +51,7 @@ services:
inlined: inlined:
class: Bar class: Bar
public: false
properties: { pub: pub } properties: { pub: pub }
calls: calls:
- [setBaz, ['@baz']] - [setBaz, ['@baz']]

View File

@ -16,13 +16,6 @@ use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
class ClosureLoaderTest extends \PHPUnit_Framework_TestCase class ClosureLoaderTest extends \PHPUnit_Framework_TestCase
{ {
protected function setUp()
{
if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
$this->markTestSkipped('The "Config" component is not available');
}
}
/** /**
* @covers Symfony\Component\DependencyInjection\Loader\ClosureLoader::supports * @covers Symfony\Component\DependencyInjection\Loader\ClosureLoader::supports
*/ */

View File

@ -29,10 +29,6 @@ class IniFileLoaderTest extends \PHPUnit_Framework_TestCase
protected function setUp() protected function setUp()
{ {
if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
$this->markTestSkipped('The "Config" component is not available');
}
$this->container = new ContainerBuilder(); $this->container = new ContainerBuilder();
$this->loader = new IniFileLoader($this->container, new FileLocator(self::$fixturesPath.'/ini')); $this->loader = new IniFileLoader($this->container, new FileLocator(self::$fixturesPath.'/ini'));
} }

View File

@ -18,13 +18,6 @@ use Symfony\Component\Config\FileLocator;
class PhpFileLoaderTest extends \PHPUnit_Framework_TestCase class PhpFileLoaderTest extends \PHPUnit_Framework_TestCase
{ {
protected function setUp()
{
if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
$this->markTestSkipped('The "Config" component is not available');
}
}
/** /**
* @covers Symfony\Component\DependencyInjection\Loader\PhpFileLoader::supports * @covers Symfony\Component\DependencyInjection\Loader\PhpFileLoader::supports
*/ */

View File

@ -22,18 +22,12 @@ use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\FileLocator;
use Symfony\Component\ExpressionLanguage\Expression;
class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
{ {
protected static $fixturesPath; protected static $fixturesPath;
protected function setUp()
{
if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
$this->markTestSkipped('The "Config" component is not available');
}
}
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
@ -99,17 +93,33 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$loader->load('services2.xml'); $loader->load('services2.xml');
$actual = $container->getParameterBag()->all(); $actual = $container->getParameterBag()->all();
$expected = array('a string', 'foo' => 'bar', 'values' => array(0, 'integer' => 4, 100 => null, 'true', true, false, 'on', 'off', 'float' => 1.3, 1000.3, 'a string', array('foo', 'bar')), 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value')); $expected = array(
'a string',
'foo' => 'bar',
'values' => array(
0,
'integer' => 4,
100 => null,
'true',
true,
false,
'on',
'off',
'float' => 1.3,
1000.3,
'a string',
array('foo', 'bar'),
),
'foo_bar' => new Reference('foo_bar'),
'mixedcase' => array('MixedCaseKey' => 'value'),
'constant' => PHP_EOL,
);
$this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones'); $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones');
} }
public function testLoadImports() public function testLoadImports()
{ {
if (!class_exists('Symfony\Component\Yaml\Yaml')) {
$this->markTestSkipped('The "Yaml" component is not available');
}
$container = new ContainerBuilder(); $container = new ContainerBuilder();
$resolver = new LoaderResolver(array( $resolver = new LoaderResolver(array(
new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
@ -120,7 +130,30 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$loader->load('services4.xml'); $loader->load('services4.xml');
$actual = $container->getParameterBag()->all(); $actual = $container->getParameterBag()->all();
$expected = array('a string', 'foo' => 'bar', 'values' => array(true, false), 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'bar' => '%foo%', 'imported_from_ini' => true, 'imported_from_yaml' => true); $expected = array(
'a string',
'foo' => 'bar',
'values' => array(
0,
'integer' => 4,
100 => null,
'true',
true,
false,
'on',
'off',
'float' => 1.3,
1000.3,
'a string',
array('foo', 'bar'),
),
'foo_bar' => new Reference('foo_bar'),
'mixedcase' => array('MixedCaseKey' => 'value'),
'constant' => PHP_EOL,
'bar' => '%foo%',
'imported_from_ini' => true,
'imported_from_yaml' => true
);
$this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
@ -179,7 +212,7 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array(array('setBar', array())), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertNull($services['factory_service']->getClass()); $this->assertNull($services['factory_service']->getClass());
$this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod()); $this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
@ -198,6 +231,29 @@ class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($aliases['another_alias_for_foo']->isPublic()); $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
} }
public function testParsesTags()
{
$container = new ContainerBuilder();
$loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
$loader->load('services10.xml');
$services = $container->findTaggedServiceIds('foo_tag');
$this->assertCount(1, $services);
foreach ($services as $id => $tagAttributes) {
foreach ($tagAttributes as $attributes) {
$this->assertArrayHasKey('other_option', $attributes);
$this->assertEquals('lorem', $attributes['other_option']);
$this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed');
$this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing');
$this->assertEquals('cat', $attributes['some-option']);
$this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found');
}
}
}
public function testConvertDomElementToArray() public function testConvertDomElementToArray()
{ {
$doc = new \DOMDocument("1.0"); $doc = new \DOMDocument("1.0");

View File

@ -20,22 +20,12 @@ use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\FileLocator;
use Symfony\Component\ExpressionLanguage\Expression;
class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
{ {
protected static $fixturesPath; protected static $fixturesPath;
protected function setUp()
{
if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
$this->markTestSkipped('The "Config" component is not available');
}
if (!class_exists('Symfony\Component\Yaml\Yaml')) {
$this->markTestSkipped('The "Yaml" component is not available');
}
}
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
@ -124,7 +114,7 @@ class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
$this->assertEquals(array(array('setBar', array()), array('setBar', array())), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array()), array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
$this->assertEquals('baz_factory', $services['factory_service']->getFactoryService()); $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
@ -209,7 +199,7 @@ class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
$this->fail('->load() should throw an exception when a tag-attribute is not a scalar'); $this->fail('->load() should throw an exception when a tag-attribute is not a scalar');
} catch (\Exception $e) { } catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar'); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
$this->assertStringStartsWith('A "tags" attribute must be of a scalar-type for service ', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar'); $this->assertStringStartsWith('A "tags" attribute must be of a scalar-type for service "foo_service", tag "foo", attribute "bar"', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
} }
} }
} }

View File

@ -20,7 +20,8 @@
}, },
"require-dev": { "require-dev": {
"symfony/yaml": "~2.0", "symfony/yaml": "~2.0",
"symfony/config": "~2.2" "symfony/config": "~2.2",
"symfony/expression-language": "~2.4"
}, },
"suggest": { "suggest": {
"symfony/yaml": "", "symfony/yaml": "",
@ -34,7 +35,7 @@
"minimum-stability": "dev", "minimum-stability": "dev",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
} }
} }

View File

@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="foo" class="BarClass" />
</services>
</container>

View File

@ -76,6 +76,8 @@ class Event
* *
* @param EventDispatcherInterface $dispatcher * @param EventDispatcherInterface $dispatcher
* *
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
*
* @api * @api
*/ */
public function setDispatcher(EventDispatcherInterface $dispatcher) public function setDispatcher(EventDispatcherInterface $dispatcher)
@ -88,6 +90,8 @@ class Event
* *
* @return EventDispatcherInterface * @return EventDispatcherInterface
* *
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
*
* @api * @api
*/ */
public function getDispatcher() public function getDispatcher()
@ -100,6 +104,8 @@ class Event
* *
* @return string * @return string
* *
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event name is passed to the listener call.
*
* @api * @api
*/ */
public function getName() public function getName()
@ -112,6 +118,8 @@ class Event
* *
* @param string $name The event name. * @param string $name The event name.
* *
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event name is passed to the listener call.
*
* @api * @api
*/ */
public function setName($name) public function setName($name)

View File

@ -154,14 +154,14 @@ class EventDispatcher implements EventDispatcherInterface
* This method can be overridden to add functionality that is executed * This method can be overridden to add functionality that is executed
* for each listener. * for each listener.
* *
* @param array[callback] $listeners The event listeners. * @param callable[] $listeners The event listeners.
* @param string $eventName The name of the event to dispatch. * @param string $eventName The name of the event to dispatch.
* @param Event $event The event object to pass to the event handlers/listeners. * @param Event $event The event object to pass to the event handlers/listeners.
*/ */
protected function doDispatch($listeners, $eventName, Event $event) protected function doDispatch($listeners, $eventName, Event $event)
{ {
foreach ($listeners as $listener) { foreach ($listeners as $listener) {
call_user_func($listener, $event); call_user_func($listener, $event, $eventName, $this);
if ($event->isPropagationStopped()) { if ($event->isPropagationStopped()) {
break; break;
} }

View File

@ -21,7 +21,7 @@ namespace Symfony\Component\EventDispatcher;
class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
{ {
/** /**
* Observer pattern subject. * Event subject.
* *
* @var mixed usually object or callable * @var mixed usually object or callable
*/ */

View File

@ -1,8 +1,8 @@
EventDispatcher Component EventDispatcher Component
========================= =========================
EventDispatcher implements a lightweight version of the Observer design The Symfony2 EventDispatcher component implements the Mediator pattern in a
pattern. simple and effective way to make your projects truly extensible.
use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\Event;
@ -21,5 +21,5 @@ Resources
You can run the unit tests with the following command: You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/EventDispatcher/ $ cd path/to/Symfony/Component/EventDispatcher/
$ composer.phar install --dev $ composer.phar install
$ phpunit $ phpunit

View File

@ -19,13 +19,6 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase
{ {
protected function setUp()
{
if (!class_exists('Symfony\Component\DependencyInjection\Container')) {
$this->markTestSkipped('The "DependencyInjection" component is not available');
}
}
public function testAddAListenerService() public function testAddAListenerService()
{ {
$event = new Event(); $event = new Event();

View File

@ -23,6 +23,9 @@ class EventDispatcherTest extends \PHPUnit_Framework_TestCase
const preBar = 'pre.bar'; const preBar = 'pre.bar';
const postBar = 'post.bar'; const postBar = 'post.bar';
/**
* @var EventDispatcher
*/
private $dispatcher; private $dispatcher;
private $listener; private $listener;
@ -237,7 +240,6 @@ class EventDispatcherTest extends \PHPUnit_Framework_TestCase
public function testEventReceivesTheDispatcherInstance() public function testEventReceivesTheDispatcherInstance()
{ {
$test = $this;
$this->dispatcher->addListener('test', function ($event) use (&$dispatcher) { $this->dispatcher->addListener('test', function ($event) use (&$dispatcher) {
$dispatcher = $event->getDispatcher(); $dispatcher = $event->getDispatcher();
}); });
@ -245,6 +247,17 @@ class EventDispatcherTest extends \PHPUnit_Framework_TestCase
$this->assertSame($this->dispatcher, $dispatcher); $this->assertSame($this->dispatcher, $dispatcher);
} }
public function testEventReceivesTheDispatcherInstanceAsArgument()
{
$listener = new TestWithDispatcher();
$this->dispatcher->addListener('test', array($listener, 'foo'));
$this->assertNull($listener->name);
$this->assertNull($listener->dispatcher);
$this->dispatcher->dispatch('test');
$this->assertEquals('test', $listener->name);
$this->assertSame($this->dispatcher, $listener->dispatcher);
}
/** /**
* @see https://bugs.php.net/bug.php?id=62976 * @see https://bugs.php.net/bug.php?id=62976
* *
@ -257,7 +270,7 @@ class EventDispatcherTest extends \PHPUnit_Framework_TestCase
{ {
$dispatcher = new EventDispatcher(); $dispatcher = new EventDispatcher();
$dispatcher->addListener('bug.62976', new CallableClass()); $dispatcher->addListener('bug.62976', new CallableClass());
$dispatcher->removeListener('bug.62976', function() {}); $dispatcher->removeListener('bug.62976', function () {});
$this->assertTrue($dispatcher->hasListeners('bug.62976')); $this->assertTrue($dispatcher->hasListeners('bug.62976'));
} }
} }
@ -289,6 +302,18 @@ class TestEventListener
} }
} }
class TestWithDispatcher
{
public $name;
public $dispatcher;
public function foo(Event $e, $name, $dispatcher)
{
$this->name = $name;
$this->dispatcher = $dispatcher;
}
}
class TestEventSubscriber implements EventSubscriberInterface class TestEventSubscriber implements EventSubscriberInterface
{ {
public static function getSubscribedEvents() public static function getSubscribedEvents()

View File

@ -35,7 +35,7 @@ class EventTest extends \PHPUnit_Framework_TestCase
*/ */
protected function setUp() protected function setUp()
{ {
$this->event = new Event; $this->event = new Event();
$this->dispatcher = new EventDispatcher(); $this->dispatcher = new EventDispatcher();
} }
@ -46,7 +46,7 @@ class EventTest extends \PHPUnit_Framework_TestCase
protected function tearDown() protected function tearDown()
{ {
$this->event = null; $this->event = null;
$this->eventDispatcher = null; $this->dispatcher = null;
} }
public function testIsPropagationStopped() public function testIsPropagationStopped()

View File

@ -33,7 +33,7 @@ class GenericEventTest extends \PHPUnit_Framework_TestCase
{ {
parent::setUp(); parent::setUp();
$this->subject = new \StdClass(); $this->subject = new \stdClass();
$this->event = new GenericEvent($this->subject, array('name' => 'Event'), 'foo'); $this->event = new GenericEvent($this->subject, array('name' => 'Event'), 'foo');
} }

View File

@ -32,7 +32,7 @@
"minimum-stability": "dev", "minimum-stability": "dev",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "2.3-dev" "dev-master": "2.4-dev"
} }
} }
} }

View File

@ -90,7 +90,7 @@ class AcceptHeaderItem
{ {
$string = $this->value.($this->quality < 1 ? ';q='.$this->quality : ''); $string = $this->value.($this->quality < 1 ? ';q='.$this->quality : '');
if (count($this->attributes) > 0) { if (count($this->attributes) > 0) {
$string .= ';'.implode(';', array_map(function($name, $value) { $string .= ';'.implode(';', array_map(function ($name, $value) {
return sprintf(preg_match('/[,;=]/', $value) ? '%s="%s"' : '%s=%s', $name, $value); return sprintf(preg_match('/[,;=]/', $value) ? '%s="%s"' : '%s=%s', $name, $value);
}, array_keys($this->attributes), $this->attributes)); }, array_keys($this->attributes), $this->attributes));
} }

View File

@ -34,7 +34,7 @@ class BinaryFileResponse extends Response
/** /**
* Constructor. * Constructor.
* *
* @param SplFileInfo|string $file The file to stream * @param \SplFileInfo|string $file The file to stream
* @param integer $status The response status code * @param integer $status The response status code
* @param array $headers An array of response headers * @param array $headers An array of response headers
* @param boolean $public Files are public by default * @param boolean $public Files are public by default
@ -54,7 +54,13 @@ class BinaryFileResponse extends Response
} }
/** /**
* {@inheritdoc} * @param \SplFileInfo|string $file The file to stream
* @param integer $status The response status code
* @param array $headers An array of response headers
* @param boolean $public Files are public by default
* @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
* @param boolean $autoEtag Whether the ETag header should be automatically set
* @param boolean $autoLastModified Whether the Last-Modified header should be automatically set
*/ */
public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
{ {
@ -64,7 +70,7 @@ class BinaryFileResponse extends Response
/** /**
* Sets the file to stream. * Sets the file to stream.
* *
* @param SplFileInfo|string $file The file to stream * @param \SplFileInfo|string $file The file to stream
* @param string $contentDisposition * @param string $contentDisposition
* @param Boolean $autoEtag * @param Boolean $autoEtag
* @param Boolean $autoLastModified * @param Boolean $autoLastModified
@ -210,14 +216,18 @@ class BinaryFileResponse extends Response
$start = (int) $start; $start = (int) $start;
} }
$start = max($start, 0); if ($start <= $end) {
$end = min($end, $fileSize - 1); if ($start < 0 || $end > $fileSize - 1) {
$this->setStatusCode(416);
} elseif ($start !== 0 || $end !== $fileSize - 1) {
$this->maxlen = $end < $fileSize ? $end - $start + 1 : -1; $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
$this->offset = $start; $this->offset = $start;
$this->setStatusCode(206); $this->setStatusCode(206);
$this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize)); $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
$this->headers->set('Content-Length', $end - $start + 1);
}
}
} }
} }

View File

@ -1,6 +1,13 @@
CHANGELOG CHANGELOG
========= =========
2.4.0
-----
* added RequestStack
* added Request::getEncodings()
* added accessors methods to session handlers
2.3.0 2.3.0
----- -----

View File

@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
* ExpressionRequestMatcher uses an expression to match a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionRequestMatcher extends RequestMatcher
{
private $language;
private $expression;
public function setExpression(ExpressionLanguage $language, $expression)
{
$this->language = $language;
$this->expression = $expression;
}
public function matches(Request $request)
{
if (!$this->language) {
throw new \LogicException('Unable to match the request as the expression language is not available.');
}
return $this->language->evaluate($this->expression, array(
'request' => $request,
'method' => $request->getMethod(),
'path' => rawurldecode($request->getPathInfo()),
'host' => $request->getHost(),
'ip' => $request->getClientIp(),
'attributes' => $request->attributes->all(),
)) && parent::matches($request);
}
}

View File

@ -137,7 +137,7 @@ class File extends \SplFileInfo
throw new FileException(sprintf('Unable to write in the "%s" directory', $directory)); throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
} }
$target = $directory.DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name)); $target = rtrim($directory, '/\\').DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name));
return new File($target, false); return new File($target, false);
} }

View File

@ -252,7 +252,7 @@ class UploadedFile extends File
return $target; return $target;
} }
throw new FileException($this->getErrorMessage($this->getError())); throw new FileException($this->getErrorMessage());
} }
/** /**
@ -262,30 +262,37 @@ class UploadedFile extends File
*/ */
public static function getMaxFilesize() public static function getMaxFilesize()
{ {
$max = strtolower(ini_get('upload_max_filesize')); $iniMax = strtolower(ini_get('upload_max_filesize'));
if ('' === $max) { if ('' === $iniMax) {
return PHP_INT_MAX; return PHP_INT_MAX;
} }
if (preg_match('#^\+?(0x?)?(.*?)([kmg]?)$#', $max, $match)) { $max = ltrim($iniMax, '+');
$shifts = array('' => 0, 'k' => 10, 'm' => 20, 'g' => 30); if (0 === strpos($max, '0x')) {
$bases = array('' => 10, '0' => 8, '0x' => 16); $max = intval($max, 16);
} elseif (0 === strpos($max, '0')) {
return intval($match[2], $bases[$match[1]]) << $shifts[$match[3]]; $max = intval($max, 8);
} else {
$max = intval($max);
} }
return 0; switch (substr($iniMax, -1)) {
case 't': $max *= 1024;
case 'g': $max *= 1024;
case 'm': $max *= 1024;
case 'k': $max *= 1024;
}
return $max;
} }
/** /**
* Returns an informative upload error message. * Returns an informative upload error message.
* *
* @param int $code The error code returned by an upload attempt
*
* @return string The error message regarding the specified error code * @return string The error message regarding the specified error code
*/ */
private function getErrorMessage($errorCode) public function getErrorMessage()
{ {
static $errors = array( static $errors = array(
UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d kb).', UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d kb).',
@ -294,9 +301,10 @@ class UploadedFile extends File
UPLOAD_ERR_NO_FILE => 'No file was uploaded.', UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
UPLOAD_ERR_EXTENSION => 'File upload was stopped by a php extension.', UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
); );
$errorCode = $this->error;
$maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? self::getMaxFilesize() / 1024 : 0; $maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? self::getMaxFilesize() / 1024 : 0;
$message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.'; $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.';

View File

@ -20,8 +20,8 @@ namespace Symfony\Component\HttpFoundation;
*/ */
class HeaderBag implements \IteratorAggregate, \Countable class HeaderBag implements \IteratorAggregate, \Countable
{ {
protected $headers; protected $headers = array();
protected $cacheControl; protected $cacheControl = array();
/** /**
* Constructor. * Constructor.
@ -32,8 +32,6 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/ */
public function __construct(array $headers = array()) public function __construct(array $headers = array())
{ {
$this->cacheControl = array();
$this->headers = array();
foreach ($headers as $key => $values) { foreach ($headers as $key => $values) {
$this->set($key, $values); $this->set($key, $values);
} }

View File

@ -24,10 +24,10 @@ class IpUtils
private function __construct() {} private function __construct() {}
/** /**
* Validates an IPv4 or IPv6 address. * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets
* *
* @param string $requestIp * @param string $requestIp IP to check
* @param string|array $ips * @param string|array $ips List of IPs or subnets (can be a string if only a single one)
* *
* @return boolean Whether the IP is valid * @return boolean Whether the IP is valid
*/ */
@ -49,10 +49,11 @@ class IpUtils
} }
/** /**
* Validates an IPv4 address. * Compares two IPv4 addresses.
* In case a subnet is given, it checks if it contains the request IP.
* *
* @param string $requestIp * @param string $requestIp IPv4 address to check
* @param string $ip * @param string $ip IPv4 address or subnet in CIDR notation
* *
* @return boolean Whether the IP is valid * @return boolean Whether the IP is valid
*/ */
@ -73,13 +74,14 @@ class IpUtils
} }
/** /**
* Validates an IPv6 address. * Compares two IPv6 addresses.
* In case a subnet is given, it checks if it contains the request IP.
* *
* @author David Soria Parra <dsp at php dot net> * @author David Soria Parra <dsp at php dot net>
* @see https://github.com/dsp/v6tools * @see https://github.com/dsp/v6tools
* *
* @param string $requestIp * @param string $requestIp IPv6 address to check
* @param string $ip * @param string $ip IPv6 address or subnet in CIDR notation
* *
* @return boolean Whether the IP is valid * @return boolean Whether the IP is valid
* *

View File

@ -55,11 +55,11 @@ class JsonResponse extends Response
/** /**
* Sets the JSONP callback. * Sets the JSONP callback.
* *
* @param string $callback * @param string|null $callback The JSONP callback or null to use none
* *
* @return JsonResponse * @return JsonResponse
* *
* @throws \InvalidArgumentException * @throws \InvalidArgumentException When the callback name is not valid
*/ */
public function setCallback($callback = null) public function setCallback($callback = null)
{ {
@ -85,12 +85,18 @@ class JsonResponse extends Response
* @param mixed $data * @param mixed $data
* *
* @return JsonResponse * @return JsonResponse
*
* @throws \InvalidArgumentException
*/ */
public function setData($data = array()) public function setData($data = array())
{ {
// Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML. // Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
$this->data = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); $this->data = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException($this->transformJsonError());
}
return $this->update(); return $this->update();
} }
@ -116,4 +122,31 @@ class JsonResponse extends Response
return $this->setContent($this->data); return $this->setContent($this->data);
} }
private function transformJsonError()
{
if (function_exists('json_last_error_msg')) {
return json_last_error_msg();
}
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded.';
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch.';
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found.';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON.';
case JSON_ERROR_UTF8:
return 'Malformed UTF-8 characters, possibly incorrectly encoded.';
default:
return 'Unknown error.';
}
}
} }

View File

@ -266,7 +266,7 @@ class ParameterBag implements \IteratorAggregate, \Countable
* *
* @return mixed * @return mixed
*/ */
public function filter($key, $default = null, $deep = false, $filter=FILTER_DEFAULT, $options=array()) public function filter($key, $default = null, $deep = false, $filter = FILTER_DEFAULT, $options = array())
{ {
$value = $this->get($key, $default, $deep); $value = $this->get($key, $default, $deep);

View File

@ -44,5 +44,5 @@ Resources
You can run the unit tests with the following command: You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/HttpFoundation/ $ cd path/to/Symfony/Component/HttpFoundation/
$ composer.phar install --dev $ composer.phar install
$ phpunit $ phpunit

View File

@ -27,7 +27,7 @@ class RedirectResponse extends Response
* *
* @param string $url The URL to redirect to * @param string $url The URL to redirect to
* @param integer $status The status code (302 by default) * @param integer $status The status code (302 by default)
* @param array $headers The headers (Location is always set to the given url) * @param array $headers The headers (Location is always set to the given URL)
* *
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
* *

View File

@ -64,6 +64,8 @@ class Request
protected static $httpMethodParameterOverride = false; protected static $httpMethodParameterOverride = false;
/** /**
* Custom parameters
*
* @var \Symfony\Component\HttpFoundation\ParameterBag * @var \Symfony\Component\HttpFoundation\ParameterBag
* *
* @api * @api
@ -71,6 +73,8 @@ class Request
public $attributes; public $attributes;
/** /**
* Request body parameters ($_POST)
*
* @var \Symfony\Component\HttpFoundation\ParameterBag * @var \Symfony\Component\HttpFoundation\ParameterBag
* *
* @api * @api
@ -78,6 +82,8 @@ class Request
public $request; public $request;
/** /**
* Query string parameters ($_GET)
*
* @var \Symfony\Component\HttpFoundation\ParameterBag * @var \Symfony\Component\HttpFoundation\ParameterBag
* *
* @api * @api
@ -85,6 +91,8 @@ class Request
public $query; public $query;
/** /**
* Server and execution environment parameters ($_SERVER)
*
* @var \Symfony\Component\HttpFoundation\ServerBag * @var \Symfony\Component\HttpFoundation\ServerBag
* *
* @api * @api
@ -92,6 +100,8 @@ class Request
public $server; public $server;
/** /**
* Uploaded files ($_FILES)
*
* @var \Symfony\Component\HttpFoundation\FileBag * @var \Symfony\Component\HttpFoundation\FileBag
* *
* @api * @api
@ -99,6 +109,8 @@ class Request
public $files; public $files;
/** /**
* Cookies ($_COOKIE)
*
* @var \Symfony\Component\HttpFoundation\ParameterBag * @var \Symfony\Component\HttpFoundation\ParameterBag
* *
* @api * @api
@ -106,6 +118,8 @@ class Request
public $cookies; public $cookies;
/** /**
* Headers (taken from the $_SERVER)
*
* @var \Symfony\Component\HttpFoundation\HeaderBag * @var \Symfony\Component\HttpFoundation\HeaderBag
* *
* @api * @api
@ -127,6 +141,11 @@ class Request
*/ */
protected $charsets; protected $charsets;
/**
* @var array
*/
protected $encodings;
/** /**
* @var array * @var array
*/ */
@ -182,6 +201,8 @@ class Request
*/ */
protected static $formats; protected static $formats;
protected static $requestFactory;
/** /**
* Constructor. * Constructor.
* *
@ -228,6 +249,7 @@ class Request
$this->content = $content; $this->content = $content;
$this->languages = null; $this->languages = null;
$this->charsets = null; $this->charsets = null;
$this->encodings = null;
$this->acceptableContentTypes = null; $this->acceptableContentTypes = null;
$this->pathInfo = null; $this->pathInfo = null;
$this->requestUri = null; $this->requestUri = null;
@ -246,7 +268,7 @@ class Request
*/ */
public static function createFromGlobals() public static function createFromGlobals()
{ {
$request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER); $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
&& in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH')) && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
@ -346,16 +368,39 @@ class Request
break; break;
} }
$queryString = '';
if (isset($components['query'])) { if (isset($components['query'])) {
parse_str(html_entity_decode($components['query']), $qs); parse_str(html_entity_decode($components['query']), $qs);
if ($query) {
$query = array_replace($qs, $query); $query = array_replace($qs, $query);
}
$queryString = http_build_query($query, '', '&'); $queryString = http_build_query($query, '', '&');
} else {
$query = $qs;
$queryString = $components['query'];
}
} elseif ($query) {
$queryString = http_build_query($query, '', '&');
}
$server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : ''); $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
$server['QUERY_STRING'] = $queryString; $server['QUERY_STRING'] = $queryString;
return new static($query, $request, array(), $cookies, $files, $server, $content); return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content);
}
/**
* Sets a callable able to create a Request instance.
*
* This is mainly useful when you need to override the Request class
* to keep BC with an existing system. It should not be used for any
* other purpose.
*
* @param callable|null $callable A PHP callable
*/
public static function setFactory($callable)
{
self::$requestFactory = $callable;
} }
/** /**
@ -396,6 +441,7 @@ class Request
} }
$dup->languages = null; $dup->languages = null;
$dup->charsets = null; $dup->charsets = null;
$dup->encodings = null;
$dup->acceptableContentTypes = null; $dup->acceptableContentTypes = null;
$dup->pathInfo = null; $dup->pathInfo = null;
$dup->requestUri = null; $dup->requestUri = null;
@ -404,8 +450,12 @@ class Request
$dup->method = null; $dup->method = null;
$dup->format = null; $dup->format = null;
if (!$dup->get('_format')) { if (!$dup->get('_format') && $this->get('_format')) {
$dup->setRequestFormat($this->getRequestFormat()); $dup->attributes->set('_format', $this->get('_format'));
}
if (!$dup->getRequestFormat(null)) {
$dup->setRequestFormat($format = $this->getRequestFormat(null));
} }
return $dup; return $dup;
@ -467,7 +517,7 @@ class Request
$request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE); $request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE);
$requestOrder = ini_get('request_order') ?: ini_get('variable_order'); $requestOrder = ini_get('request_order') ?: ini_get('variables_order');
$requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp'; $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
$_REQUEST = array(); $_REQUEST = array();
@ -719,9 +769,9 @@ class Request
/** /**
* Returns the client IP addresses. * Returns the client IP addresses.
* *
* The most trusted IP address is first, and the less trusted one last. * In the returned array the most trusted IP address is first, and the
* The "real" client IP address is the last one, but this is also the * least trusted one last. The "real" client IP address is the last one,
* less trusted one. * but this is also the least trusted one. Trusted proxies are stripped.
* *
* Use this method carefully; you should use getClientIp() instead. * Use this method carefully; you should use getClientIp() instead.
* *
@ -742,19 +792,18 @@ class Request
} }
$clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP]))); $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
$clientIps[] = $ip; $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
$trustedProxies = !self::$trustedProxies ? array($ip) : self::$trustedProxies; $ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies
$ip = $clientIps[0];
// Eliminate all IPs from the forwarded IP chain which are trusted proxies
foreach ($clientIps as $key => $clientIp) { foreach ($clientIps as $key => $clientIp) {
if (IpUtils::checkIp($clientIp, $trustedProxies)) { if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
unset($clientIps[$key]); unset($clientIps[$key]);
continue;
} }
} }
// Now the IP chain contains only untrusted proxies and the client IP
return $clientIps ? array_reverse($clientIps) : array($ip); return $clientIps ? array_reverse($clientIps) : array($ip);
} }
@ -846,14 +895,14 @@ class Request
} }
/** /**
* Returns the root url from which this request is executed. * Returns the root URL from which this request is executed.
* *
* The base URL never ends with a /. * The base URL never ends with a /.
* *
* This is similar to getBasePath(), except that it also includes the * This is similar to getBasePath(), except that it also includes the
* script filename (e.g. index.php) if one exists. * script filename (e.g. index.php) if one exists.
* *
* @return string The raw url (i.e. not urldecoded) * @return string The raw URL (i.e. not urldecoded)
* *
* @api * @api
*/ */
@ -905,6 +954,14 @@ class Request
} }
} }
if ($host = $this->headers->get('HOST')) {
if (false !== $pos = strrpos($host, ':')) {
return intval(substr($host, $pos + 1));
}
return 'https' === $this->getScheme() ? 443 : 80;
}
return $this->server->get('SERVER_PORT'); return $this->server->get('SERVER_PORT');
} }
@ -1063,7 +1120,7 @@ class Request
public function isSecure() public function isSecure()
{ {
if (self::$trustedProxies && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) { if (self::$trustedProxies && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) {
return in_array(strtolower($proto), array('https', 'on', '1')); return in_array(strtolower(current(explode(',', $proto))), array('https', 'on', 'ssl', '1'));
} }
return 'on' == strtolower($this->server->get('HTTPS')) || 1 == $this->server->get('HTTPS'); return 'on' == strtolower($this->server->get('HTTPS')) || 1 == $this->server->get('HTTPS');
@ -1105,7 +1162,7 @@ class Request
// as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user) // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
// check that it does not contain forbidden characters (see RFC 952 and RFC 2181) // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
if ($host && !preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host)) { if ($host && !preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host)) {
throw new \UnexpectedValueException('Invalid Host "'.$host.'"'); throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
} }
if (count(self::$trustedHostPatterns) > 0) { if (count(self::$trustedHostPatterns) > 0) {
@ -1123,7 +1180,7 @@ class Request
} }
} }
throw new \UnexpectedValueException('Untrusted Host "'.$host.'"'); throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
} }
return $host; return $host;
@ -1502,6 +1559,20 @@ class Request
return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()); return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
} }
/**
* Gets a list of encodings acceptable by the client browser.
*
* @return array List of encodings in preferable order
*/
public function getEncodings()
{
if (null !== $this->encodings) {
return $this->encodings;
}
return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
}
/** /**
* Gets a list of content types acceptable by the client browser * Gets a list of content types acceptable by the client browser
* *
@ -1558,13 +1629,13 @@ class Request
$requestUri = $this->headers->get('X_REWRITE_URL'); $requestUri = $this->headers->get('X_REWRITE_URL');
$this->headers->remove('X_REWRITE_URL'); $this->headers->remove('X_REWRITE_URL');
} elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') { } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
// IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem) // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
$requestUri = $this->server->get('UNENCODED_URL'); $requestUri = $this->server->get('UNENCODED_URL');
$this->server->remove('UNENCODED_URL'); $this->server->remove('UNENCODED_URL');
$this->server->remove('IIS_WasUrlRewritten'); $this->server->remove('IIS_WasUrlRewritten');
} elseif ($this->server->has('REQUEST_URI')) { } elseif ($this->server->has('REQUEST_URI')) {
$requestUri = $this->server->get('REQUEST_URI'); $requestUri = $this->server->get('REQUEST_URI');
// HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
$schemeAndHttpHost = $this->getSchemeAndHttpHost(); $schemeAndHttpHost = $this->getSchemeAndHttpHost();
if (strpos($requestUri, $schemeAndHttpHost) === 0) { if (strpos($requestUri, $schemeAndHttpHost) === 0) {
$requestUri = substr($requestUri, strlen($schemeAndHttpHost)); $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
@ -1613,7 +1684,7 @@ class Request
$seg = $segs[$index]; $seg = $segs[$index];
$baseUrl = '/'.$seg.$baseUrl; $baseUrl = '/'.$seg.$baseUrl;
++$index; ++$index;
} while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos)); } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
} }
// Does the baseUrl have anything in common with the request_uri? // Does the baseUrl have anything in common with the request_uri?
@ -1630,7 +1701,7 @@ class Request
} }
$truncatedRequestUri = $requestUri; $truncatedRequestUri = $requestUri;
if (($pos = strpos($requestUri, '?')) !== false) { if (false !== $pos = strpos($requestUri, '?')) {
$truncatedRequestUri = substr($requestUri, 0, $pos); $truncatedRequestUri = substr($requestUri, 0, $pos);
} }
@ -1643,7 +1714,7 @@ class Request
// If using mod_rewrite or ISAPI_Rewrite strip the script filename // If using mod_rewrite or ISAPI_Rewrite strip the script filename
// out of baseUrl. $pos !== 0 makes sure it is not matching a value // out of baseUrl. $pos !== 0 makes sure it is not matching a value
// from PATH_INFO or QUERY_STRING // from PATH_INFO or QUERY_STRING
if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) { if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) {
$baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
} }
@ -1696,7 +1767,7 @@ class Request
$requestUri = substr($requestUri, 0, $pos); $requestUri = substr($requestUri, 0, $pos);
} }
if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) { if (null !== $baseUrl && false === $pathInfo = substr($requestUri, strlen($baseUrl))) {
// If substr() returns false then PATH_INFO is set to an empty string // If substr() returns false then PATH_INFO is set to an empty string
return '/'; return '/';
} elseif (null === $baseUrl) { } elseif (null === $baseUrl) {
@ -1765,4 +1836,19 @@ class Request
return false; return false;
} }
private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
if (self::$requestFactory) {
$request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
if (!$request instanceof Request) {
throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
}
return $request;
}
return new static($query, $request, $attributes, $cookies, $files, $server, $content);
}
} }

View File

@ -0,0 +1,103 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
/**
* Request stack that controls the lifecycle of requests.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class RequestStack
{
/**
* @var Request[]
*/
private $requests = array();
/**
* Pushes a Request on the stack.
*
* This method should generally not be called directly as the stack
* management should be taken care of by the application itself.
*/
public function push(Request $request)
{
$this->requests[] = $request;
}
/**
* Pops the current request from the stack.
*
* This operation lets the current request go out of scope.
*
* This method should generally not be called directly as the stack
* management should be taken care of by the application itself.
*
* @return Request|null
*/
public function pop()
{
if (!$this->requests) {
return null;
}
return array_pop($this->requests);
}
/**
* @return Request|null
*/
public function getCurrentRequest()
{
return end($this->requests) ?: null;
}
/**
* Gets the master Request.
*
* Be warned that making your code aware of the master request
* might make it un-compatible with other features of your framework
* like ESI support.
*
* @return Request|null
*/
public function getMasterRequest()
{
if (!$this->requests) {
return null;
}
return $this->requests[0];
}
/**
* Returns the parent request of the current.
*
* Be warned that making your code aware of the parent request
* might make it un-compatible with other features of your framework
* like ESI support.
*
* If current Request is the master request, it returns null.
*
* @return Request|null
*/
public function getParentRequest()
{
$pos = count($this->requests) - 2;
if (!isset($this->requests[$pos])) {
return null;
}
return $this->requests[$pos];
}
}

View File

@ -20,6 +20,67 @@ namespace Symfony\Component\HttpFoundation;
*/ */
class Response class Response
{ {
const HTTP_CONTINUE = 100;
const HTTP_SWITCHING_PROTOCOLS = 101;
const HTTP_PROCESSING = 102; // RFC2518
const HTTP_OK = 200;
const HTTP_CREATED = 201;
const HTTP_ACCEPTED = 202;
const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
const HTTP_NO_CONTENT = 204;
const HTTP_RESET_CONTENT = 205;
const HTTP_PARTIAL_CONTENT = 206;
const HTTP_MULTI_STATUS = 207; // RFC4918
const HTTP_ALREADY_REPORTED = 208; // RFC5842
const HTTP_IM_USED = 226; // RFC3229
const HTTP_MULTIPLE_CHOICES = 300;
const HTTP_MOVED_PERMANENTLY = 301;
const HTTP_FOUND = 302;
const HTTP_SEE_OTHER = 303;
const HTTP_NOT_MODIFIED = 304;
const HTTP_USE_PROXY = 305;
const HTTP_RESERVED = 306;
const HTTP_TEMPORARY_REDIRECT = 307;
const HTTP_PERMANENTLY_REDIRECT = 308; // RFC-reschke-http-status-308-07
const HTTP_BAD_REQUEST = 400;
const HTTP_UNAUTHORIZED = 401;
const HTTP_PAYMENT_REQUIRED = 402;
const HTTP_FORBIDDEN = 403;
const HTTP_NOT_FOUND = 404;
const HTTP_METHOD_NOT_ALLOWED = 405;
const HTTP_NOT_ACCEPTABLE = 406;
const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
const HTTP_REQUEST_TIMEOUT = 408;
const HTTP_CONFLICT = 409;
const HTTP_GONE = 410;
const HTTP_LENGTH_REQUIRED = 411;
const HTTP_PRECONDITION_FAILED = 412;
const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
const HTTP_REQUEST_URI_TOO_LONG = 414;
const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
const HTTP_EXPECTATION_FAILED = 417;
const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
const HTTP_LOCKED = 423; // RFC4918
const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817
const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
const HTTP_INTERNAL_SERVER_ERROR = 500;
const HTTP_NOT_IMPLEMENTED = 501;
const HTTP_BAD_GATEWAY = 502;
const HTTP_SERVICE_UNAVAILABLE = 503;
const HTTP_GATEWAY_TIMEOUT = 504;
const HTTP_VERSION_NOT_SUPPORTED = 505;
const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
const HTTP_LOOP_DETECTED = 508; // RFC5842
const HTTP_NOT_EXTENDED = 510; // RFC2774
const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
/** /**
* @var \Symfony\Component\HttpFoundation\ResponseHeaderBag * @var \Symfony\Component\HttpFoundation\ResponseHeaderBag
*/ */
@ -127,7 +188,7 @@ class Response
/** /**
* Constructor. * Constructor.
* *
* @param string $content The response content * @param mixed $content The response content, see setContent()
* @param integer $status The response status code * @param integer $status The response status code
* @param array $headers An array of response headers * @param array $headers An array of response headers
* *
@ -154,7 +215,7 @@ class Response
* return Response::create($body, 200) * return Response::create($body, 200)
* ->setSharedMaxAge(300); * ->setSharedMaxAge(300);
* *
* @param string $content The response content * @param mixed $content The response content, see setContent()
* @param integer $status The response status code * @param integer $status The response status code
* @param array $headers An array of response headers * @param array $headers An array of response headers
* *
@ -223,7 +284,7 @@ class Response
$charset = $this->charset ?: 'UTF-8'; $charset = $this->charset ?: 'UTF-8';
if (!$headers->has('Content-Type')) { if (!$headers->has('Content-Type')) {
$headers->set('Content-Type', 'text/html; charset='.$charset); $headers->set('Content-Type', 'text/html; charset='.$charset);
} elseif (0 === strpos($headers->get('Content-Type'), 'text/') && false === strpos($headers->get('Content-Type'), 'charset')) { } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
// add the charset // add the charset
$headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset); $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
} }
@ -271,12 +332,12 @@ class Response
} }
// status // status
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)); header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
// headers // headers
foreach ($this->headers->allPreserveCase() as $name => $values) { foreach ($this->headers->allPreserveCase() as $name => $values) {
foreach ($values as $value) { foreach ($values as $value) {
header($name.': '.$value, false); header($name.': '.$value, false, $this->statusCode);
} }
} }
@ -342,9 +403,9 @@ class Response
/** /**
* Sets the response content. * Sets the response content.
* *
* Valid types are strings, numbers, and objects that implement a __toString() method. * Valid types are strings, numbers, null, and objects that implement a __toString() method.
* *
* @param mixed $content * @param mixed $content Content that can be cast to string
* *
* @return Response * @return Response
* *
@ -1181,7 +1242,7 @@ class Response
} }
/** /**
* Check if we need to remove Cache-Control for ssl encrypted downloads when using IE < 9 * Check if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9
* *
* @link http://support.microsoft.com/kb/323308 * @link http://support.microsoft.com/kb/323308
*/ */

Some files were not shown because too many files have changed in this diff Show More