diff --git a/.travis.php b/.github/travis.php similarity index 75% rename from .travis.php rename to .github/travis.php index 7618c272e88ee..1d036d4f4295c 100644 --- a/.travis.php +++ b/.github/travis.php @@ -1,19 +1,24 @@ $_SERVER['argc']) { - echo "Usage: branch dir1 dir2 ... dirN\n"; + echo "Usage: branch version dir1 dir2 ... dirN\n"; exit(1); } +chdir(dirname(__DIR__)); $dirs = $_SERVER['argv']; array_shift($dirs); $branch = array_shift($dirs); +$version = array_shift($dirs); $packages = array(); $flags = PHP_VERSION_ID >= 50400 ? JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE : 0; foreach ($dirs as $dir) { - if (!`git diff --name-only $branch...HEAD -- $dir`) { + if (!system("git diff --name-only $branch...HEAD -- $dir", $exitStatus)) { + if ($exitStatus) { + exit($exitStatus); + } continue; } echo "$dir\n"; @@ -26,15 +31,15 @@ $package->repositories = array(array( 'type' => 'composer', - 'url' => 'file://'.__DIR__.'/', + 'url' => 'file://'.dirname(__DIR__).'/', )); $json = rtrim(json_encode(array('repositories' => $package->repositories), $flags), "\n}").','.substr($json, 1); file_put_contents($dir.'/composer.json', $json); passthru("cd $dir && tar -cf package.tar --exclude='package.tar' *"); - $package->version = $branch.'.x-dev'; + $package->version = $version.'.999'; $package->dist['type'] = 'tar'; - $package->dist['url'] = 'file://'.__DIR__."/$dir/package.tar"; + $package->dist['url'] = 'file://'.dirname(__DIR__)."/$dir/package.tar"; $packages[$package->name][$package->version] = $package; diff --git a/.php_cs b/.php_cs index 290e9bf5fbcba..02d15784e65b1 100644 --- a/.php_cs +++ b/.php_cs @@ -3,6 +3,10 @@ return Symfony\CS\Config\Config::create() ->setUsingLinter(false) ->setUsingCache(true) + ->fixers(array( + 'long_array_syntax', + 'php_unit_construct', + )) ->finder( Symfony\CS\Finder\DefaultFinder::create() ->in(__DIR__) @@ -12,6 +16,9 @@ return Symfony\CS\Config\Config::create() 'src/Symfony/Component/Routing/Tests/Fixtures/dumper', // fixture templates 'src/Symfony/Component/Templating/Tests/Fixtures/templates', + 'src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom', + // generated fixtures + 'src/Symfony/Component/VarDumper/Tests/Fixtures', // resource templates 'src/Symfony/Bundle/FrameworkBundle/Resources/views/Form', )) diff --git a/.travis.yml b/.travis.yml index 778d0e9c04db2..76e38fcb1beb7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,7 @@ env: matrix: include: # Use the newer stack for HHVM as HHVM does not support Precise anymore since a long time and so Precise has an outdated version - - php: hhvm + - php: hhvm-3.12 sudo: required dist: trusty group: edge @@ -64,7 +64,7 @@ before_install: install: - if [[ ! $skip ]]; then COMPONENTS=$(find src/Symfony -mindepth 3 -type f -name phpunit.xml.dist -printf '%h\n'); fi # Create local composer packages for each patched components and reference them in composer.json files when cross-testing components - - if [[ ! $skip && $deps ]]; then php .travis.php $TRAVIS_BRANCH $COMPONENTS; fi + - if [[ ! $skip && $deps ]]; then git fetch origin $TRAVIS_BRANCH && php .github/travis.php FETCH_HEAD $TRAVIS_BRANCH $COMPONENTS; fi # For the master branch when deps=high, the version before master is checked out and tested with the locally patched components - if [[ $deps = high && $TRAVIS_BRANCH = master ]]; then SYMFONY_VERSION=$(git ls-remote --heads | grep -o '/[1-9].*' | tail -n 1 | sed s/.//); else SYMFONY_VERSION=$(cat composer.json | grep '^ *"dev-master". *"[1-9]' | grep -o '[0-9.]*'); fi - if [[ $deps = high && $TRAVIS_BRANCH = master ]]; then git fetch origin $SYMFONY_VERSION; git checkout -m FETCH_HEAD; COMPONENTS=$(find src/Symfony -mindepth 3 -type f -name phpunit.xml.dist -printf '%h\n'); ./phpunit install; fi diff --git a/CHANGELOG-2.7.md b/CHANGELOG-2.7.md index cfe286f2a4caf..235f166764c2d 100644 --- a/CHANGELOG-2.7.md +++ b/CHANGELOG-2.7.md @@ -7,6 +7,32 @@ in 2.7 minor versions. To get the diff for a specific change, go to https://github.com/symfony/symfony/commit/XXX where XXX is the change hash To get the diff between two versions, go to https://github.com/symfony/symfony/compare/v2.7.0...v2.7.1 +* 2.7.14 (2016-06-06) + + * bug #18908 [DependencyInjection] force enabling the external XML entity loaders (xabbuh) + * bug #18893 [DependencyInjection] Skip deep reference check for 'service_container' (RobertMe) + * bug #18812 Catch \Throwable (fprochazka) + * bug #18821 [Form] Removed UTC specification with timestamp (francisbesset) + * bug #18861 Fix for #18843 (inso) + * bug #18907 [Routing] Fix the annotation loader taking a class constant as a beginning of a class name (jakzal, nicolas-grekas) + * bug #18879 [Console] SymfonyStyle: Align multi-line/very-long-line blocks (chalasr) + * bug #18864 [Console][DX] Fixed ambiguous error message when using a duplicate option shortcut (peterrehm) + * bug #18883 Fix js comment in profiler (linnaea) + * bug #18844 [Yaml] fix exception contexts (xabbuh) + * bug #18840 [Yaml] properly handle unindented collections (xabbuh) + * bug #18813 Catch \Throwable (fprochazka) + * bug #18839 People - person singularization (Keeo) + * bug #18828 [Yaml] chomp newlines only at the end of YAML documents (xabbuh) + * bug #18814 Fixed server status command when port has been omitted (peterrehm) + * bug #18799 Use levenshtein level for better Bundle matching (j0k3r) + * bug #18413 [WebProfilerBundle] Fix CORS ajax security issues (romainneutron) + * bug #18507 [BUG] Delete class 'control-group' in bootstrap 3 (Philippe Degeeter) + * bug #18747 [Form] Modified iterator_to_array's 2nd parameter to false in ViolationMapper (issei-m) + * bug #18635 [Console] Prevent fatal error when calling Command::getHelper without helperSet (chalasr) + * bug #18686 [console][table] adjust width of colspanned cell. (aitboudad) + * bug #18761 [Form] Modified iterator_to_array's 2nd parameter to false in ViolationMapper (issei-m) + * bug #18737 [Debug] Fix fatal error handlers on PHP 7 (nicolas-grekas) + * 2.7.13 (2016-05-09) * security #18733 limited the maximum length of a submitted username (fabpot) diff --git a/CHANGELOG-2.8.md b/CHANGELOG-2.8.md index 52ff682833743..27060f7527791 100644 --- a/CHANGELOG-2.8.md +++ b/CHANGELOG-2.8.md @@ -7,6 +7,39 @@ in 2.8 minor versions. To get the diff for a specific change, go to https://github.com/symfony/symfony/commit/XXX where XXX is the change hash To get the diff between two versions, go to https://github.com/symfony/symfony/compare/v2.8.0...v2.8.1 +* 2.8.8 (2016-06-30) + + * bug #19217 [HttpKernel] Inline ValidateRequestListener logic into HttpKernel (nicolas-grekas) + * bug #18688 [HttpFoundation] Warning when request has both Forwarded and X-Forwarded-For (magnusnordlander) + * bug #19173 [Console] Decouple SymfonyStyle from TableCell (ro0NL) + * bug #19189 [Console] Fix formatting of SymfonyStyle::comment() (chalasr) + * bug #19211 [Form] fix post max size translation type extension for >= 2.8 (Tobion) + * bug #17822 [WIP] [Form] fix `empty_data` option in expanded `ChoiceType` (HeahDude) + * bug #19134 Distinguish between first and subsequent progress bar displays (rquadling) + * bug #19061 [FORM] fix post_max_size_message translation (alt. 2) (David Badura) + * bug #19100 [Console] Fixed SymfonyQuestionHelper multi-choice with defaults (sstok) + * bug #18924 [DoctrineBridge] Don't use object IDs in DoctrineChoiceLoader when passing a value closure (webmozart) + * bug #19138 [DomCrawler] No more exception on field name with strange format (guiled, fabpot) + * bug #18935 [Form] Consider a violation even if the form is not submitted (egeloen) + * bug #19127 [Form] Add exception to FormRenderer about non-unique block names (enumag) + * bug #19118 [Process] Fix pipes cleaning on Windows (nicolas-grekas) + * bug #19128 Avoid phpunit 5.4 warnings on getMock (2.7+) (iltar) + * bug #19114 [HttpKernel] Dont close the reponse stream in debug (nicolas-grekas) + * bug #19101 [Session] fix PDO transaction aborted under PostgreSQL (Tobion) + * bug #18501 [HttpFoundation] changed MERGE queries (hjkl) + * bug #19062 [HttpFoundation] Fix UPSERT for PgSql >= 9.5 (nicolas-grekas) + * bug #18548 [Form] minor fixes in DateTime transformers (HeahDude) + * bug #18732 [PropertyAccess][DX] Enhance exception that say that some methods are missing if they don't (nykopol) + * bug #19048 [HttpFoundation] Use UPSERT for sessions stored in PgSql >= 9.5 (nicolas-grekas) + * bug #19038 Fix feature detection for IE (Alsciende) + * bug #18915 [DependencyInjection] force enabling the external XML entity loaders (xabbuh) + * bug #19020 [Form] Fixed collapsed choice attributes (HeahDude) + * bug #19028 [Yaml] properly count skipped comment lines (xabbuh) + * bug #19009 [WebProfilerBundle] Fix invalid CSS style (romainneutron) + * bug #17733 [Yaml] Fix wrong line number when comments are inserted in the middle of a block. (paradajozsef) + * bug #18911 Fixed singular of committee (peterrehm) + * bug #18971 Do not inject web debug toolbar on attachments (peterrehm) + * 2.8.7 (2016-06-06) * bug #18908 [DependencyInjection] force enabling the external XML entity loaders (xabbuh) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 94711183ff113..5fc732e26ff90 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -39,8 +39,8 @@ Symfony is the result of the work of many people who made the code better - Maxime Steinhausser (ogizanagi) - Alexandre Salomé (alexandresalome) - William Durand (couac) - - ornicar - Jules Pietri (heah) + - ornicar - stealth35 ‏ (stealth35) - Alexander Mols (asm89) - Francis Besset (francisbesset) @@ -65,9 +65,9 @@ Symfony is the result of the work of many people who made the code better - Dariusz Górecki (canni) - Arnout Boks (aboks) - Iltar van der Berg (kjarli) + - Charles Sarrazin (csarrazi) - Ener-Getick (energetick) - Douglas Greenshields (shieldo) - - Charles Sarrazin (csarrazi) - Lee McDermott - Brandon Turner - Luis Cordova (cordoval) @@ -187,6 +187,7 @@ Symfony is the result of the work of many people who made the code better - Loïc Faugeron - Jannik Zschiesche (apfelbox) - Marco Pivetta (ocramius) + - Teoh Han Hui (teohhanhui) - julien pauli (jpauli) - Michael Lee (zerustech) - Lorenz Schori @@ -213,6 +214,7 @@ Symfony is the result of the work of many people who made the code better - Pierre-Yves LEBECQ (pylebecq) - Daniel Espendiller - Jakub Kucharovic (jkucharovic) + - Robin Chalas (chalas_r) - Eugene Leonovich (rybakit) - Filippo Tessarotto - Joseph Rouff (rouffj) @@ -275,7 +277,6 @@ Symfony is the result of the work of many people who made the code better - janschoenherr - Thomas Schulz (king2500) - Berny Cantos (xphere81) - - Teoh Han Hui (teohhanhui) - Ricard Clau (ricardclau) - Mark Challoner (markchalloner) - Gregor Harlan (gharlan) @@ -310,7 +311,6 @@ Symfony is the result of the work of many people who made the code better - Philipp Kräutli (pkraeutli) - Kirill chEbba Chebunin (chebba) - Greg Thornton (xdissent) - - Robin Chalas (chalas_r) - Costin Bereveanu (schniper) - Loïc Chardonnet (gnusat) - Marek Kalnik (marekkalnik) @@ -1414,6 +1414,7 @@ Symfony is the result of the work of many people who made the code better - Damon Jones (damon__jones) - David Badura (davidbadura) - Daniel Londero (dlondero) + - Sebastian Landwehr (dword123) - Adel ELHAIBA (eadel) - Damián Nohales (eagleoneraptor) - Elliot Anderson (elliot) diff --git a/UPGRADE-2.8.md b/UPGRADE-2.8.md index 990382602bab0..957f35b505cff 100644 --- a/UPGRADE-2.8.md +++ b/UPGRADE-2.8.md @@ -630,3 +630,31 @@ HttpFoundation ```php $request->query->get('foo')[bar]; ``` + +Routing +------- + + * Deprecated the hardcoded value for the `$referenceType` argument of the `UrlGeneratorInterface::generate` method. + Use the constants defined in the `UrlGeneratorInterface` instead. + + Before: + + ```php + // url generated in controller + $this->generateUrl('blog_show', array('slug' => 'my-blog-post'), true); + + // url generated in @router service + $router->generate('blog_show', array('slug' => 'my-blog-post'), true); + ``` + + After: + + ```php + use Symfony\Component\Routing\Generator\UrlGeneratorInterface; + + // url generated in controller + $this->generateUrl('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL); + + // url generated in @router service + $router->generate('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL); + ``` \ No newline at end of file diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index 08796bd419d29..b8b4a96223469 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -899,6 +899,30 @@ UPGRADE FROM 2.x to 3.0 * The `getMatcherDumperInstance()` and `getGeneratorDumperInstance()` methods in the `Symfony\Component\Routing\Router` have been changed from `public` to `protected`. + * Use the constants defined in the UrlGeneratorInterface for the $referenceType argument of the UrlGeneratorInterface::generate method. + + Before: + + ```php + // url generated in controller + $this->generateUrl('blog_show', array('slug' => 'my-blog-post'), true); + + // url generated in @router service + $router->generate('blog_show', array('slug' => 'my-blog-post'), true); + ``` + + After: + + ```php + use Symfony\Component\Routing\Generator\UrlGeneratorInterface; + + // url generated in controller + $this->generateUrl('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL); + + // url generated in @router service + $router->generate('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL); + ``` + ### Security * The `Resources/` directory was moved to `Core/Resources/` diff --git a/composer.json b/composer.json index ee035f235b3e0..97e4c5e766e47 100644 --- a/composer.json +++ b/composer.json @@ -85,7 +85,7 @@ "doctrine/doctrine-bundle": "~1.2", "monolog/monolog": "~1.11", "ocramius/proxy-manager": "~0.4|~1.0|~2.0", - "egulias/email-validator": "~1.2", + "egulias/email-validator": "~1.2,>=1.2.1", "phpdocumentor/reflection": "^1.0.7" }, "conflict": { diff --git a/phpunit b/phpunit index 3ab3ca1686042..22432a093c267 100755 --- a/phpunit +++ b/phpunit @@ -11,7 +11,7 @@ */ // Please update when phpunit needs to be reinstalled with fresh deps: -// Cache-Id-Version: 2016-03-25 09:45 UTC +// Cache-Id-Version: 2016-06-29 13:45 UTC use Symfony\Component\Process\ProcessUtils; @@ -56,7 +56,7 @@ if (!file_exists("$PHPUNIT_DIR/phpunit-$PHPUNIT_VERSION/phpunit") || md5_file(__ if (5.1 <= $PHPUNIT_VERSION && $PHPUNIT_VERSION < 5.4) { passthru("$COMPOSER require --no-update phpunit/phpunit-mock-objects \"~3.1.0\""); } - passthru("$COMPOSER require --dev --no-update symfony/phpunit-bridge \">=3.1@dev\""); + passthru("$COMPOSER require --dev --no-update symfony/phpunit-bridge \">=3.2@dev\""); passthru("$COMPOSER install --prefer-dist --no-progress --ansi", $exit); if ($exit) { exit($exit); diff --git a/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php b/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php index 5d07cee69b94a..0888f97ca91d8 100644 --- a/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php +++ b/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php @@ -69,9 +69,9 @@ public function dispatchEvent($eventName, EventArgs $eventArgs = null) /** * Gets the listeners of a specific event or all listeners. * - * @param string $event The name of the event. + * @param string $event The name of the event * - * @return array The event listeners for the specified event, or all event listeners. + * @return array The event listeners for the specified event, or all event listeners */ public function getListeners($event = null) { @@ -83,7 +83,7 @@ public function getListeners($event = null) * * @param string $event * - * @return bool TRUE if the specified event has any listeners, FALSE otherwise. + * @return bool TRUE if the specified event has any listeners, FALSE otherwise */ public function hasListeners($event) { @@ -93,8 +93,8 @@ public function hasListeners($event) /** * Adds an event listener that listens on the specified events. * - * @param string|array $events The event(s) to listen on. - * @param object|string $listener The listener object. + * @param string|array $events The event(s) to listen on + * @param object|string $listener The listener object * * @throws \RuntimeException */ diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php index af584579c8a6c..876ab1d5949e0 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php @@ -40,7 +40,7 @@ abstract class AbstractDoctrineExtension extends Extension protected $drivers = array(); /** - * @param array $objectManager A configured object manager. + * @param array $objectManager A configured object manager * @param ContainerBuilder $container A ContainerBuilder instance * * @throws \InvalidArgumentException @@ -300,8 +300,8 @@ protected function detectMetadataDriver($dir, ContainerBuilder $container) /** * Loads a configured object manager metadata, query or result cache driver. * - * @param array $objectManager A configured object manager. - * @param ContainerBuilder $container A ContainerBuilder instance. + * @param array $objectManager A configured object manager + * @param ContainerBuilder $container A ContainerBuilder instance * @param string $cacheName * * @throws \InvalidArgumentException In case of unknown driver type. @@ -314,10 +314,10 @@ protected function loadObjectManagerCacheDriver(array $objectManager, ContainerB /** * Loads a cache driver. * - * @param string $cacheDriverServiceId The cache driver name. - * @param string $objectManagerName The object manager name. - * @param array $cacheDriver The cache driver mapping. - * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container The ContainerBuilder instance. + * @param string $cacheDriverServiceId The cache driver name + * @param string $objectManagerName The object manager name + * @param array $cacheDriver The cache driver mapping + * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container The ContainerBuilder instance * * @return string * @@ -403,12 +403,12 @@ protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheD /** * Returns a modified version of $managerConfigs. * - * The manager called $autoMappedManager will map all bundles that are not mepped by other managers. + * The manager called $autoMappedManager will map all bundles that are not mapped by other managers. * * @param array $managerConfigs * @param array $bundles * - * @return array The modified version of $managerConfigs. + * @return array The modified version of $managerConfigs */ protected function fixManagersAutoMappings(array $managerConfigs, array $bundles) { diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php index fd32b8d4ceb64..5620740a52082 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterMappingsPass.php @@ -106,18 +106,18 @@ abstract class RegisterMappingsPass implements CompilerPassInterface * The $aliasMap parameter can be used to define bundle namespace shortcuts like the * DoctrineBundle provides automatically for objects in the default Entity/Document folder. * - * @param Definition|Reference $driver Driver DI definition or reference. - * @param string[] $namespaces List of namespaces handled by $driver. + * @param Definition|Reference $driver Driver DI definition or reference + * @param string[] $namespaces List of namespaces handled by $driver * @param string[] $managerParameters List of container parameters that could * hold the manager name. - * @param string $driverPattern Pattern for the metadata driver service name. + * @param string $driverPattern Pattern for the metadata driver service name * @param string $enabledParameter Service container parameter that must be * present to enable the mapping. Set to false * to not do any check, optional. - * @param string $configurationPattern Pattern for the Configuration service name. + * @param string $configurationPattern Pattern for the Configuration service name * @param string $registerAliasMethodName Name of Configuration class method to * register alias. - * @param string[] $aliasMap Map of alias to namespace. + * @param string[] $aliasMap Map of alias to namespace * * @since Support for bundle alias was added in Symfony 2.6 */ @@ -219,7 +219,7 @@ private function getConfigurationServiceName(ContainerBuilder $container) * * @param ContainerBuilder $container * - * @return string The name of the active manager. + * @return string The name of the active manager * * @throws ParameterNotFoundException If none of the managerParameters is found in the container. */ diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php index f5dcb7312e65e..9343876ef35b5 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php @@ -110,9 +110,10 @@ public function loadValuesForChoices(array $choices, $value = null) // Optimize performance for single-field identifiers. We already // know that the IDs are used as values + $optimize = null === $value || is_array($value) && $value[0] === $this->idReader; // Attention: This optimization does not check choices for existence - if (!$this->choiceList && $this->idReader->isSingleId()) { + if ($optimize && !$this->choiceList && $this->idReader->isSingleId()) { $values = array(); // Maintain order and indices of the given objects diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php index bd3fa8eb27921..d22a85466f972 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php @@ -109,7 +109,7 @@ class EntityChoiceList extends ObjectChoiceList * @param string $groupPath A property path pointing to the property used * to group the choices. Only allowed if * the choices are given as flat array. - * @param PropertyAccessorInterface $propertyAccessor The reflection graph for reading property paths. + * @param PropertyAccessorInterface $propertyAccessor The reflection graph for reading property paths */ public function __construct(ObjectManager $manager, $class, $labelPath = null, EntityLoaderInterface $entityLoader = null, $entities = null, array $preferredEntities = array(), $groupPath = null, PropertyAccessorInterface $propertyAccessor = null) { @@ -410,7 +410,7 @@ protected function createIndex($entity) * * @param mixed $entity The choice to create a value for * - * @return int|string A unique value without character limitations. + * @return int|string A unique value without character limitations */ protected function createValue($entity) { diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php index 2de34afc889e2..e36043af63cb8 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php @@ -21,7 +21,7 @@ interface EntityLoaderInterface /** * Returns an array of entities that are valid choices in the corresponding choice list. * - * @return array The entities. + * @return array The entities */ public function getEntities(); @@ -31,9 +31,9 @@ public function getEntities(); * @param string $identifier The identifier field of the object. This method * is not applicable for fields with multiple * identifiers. - * @param array $values The values of the identifiers. + * @param array $values The values of the identifiers * - * @return array The entities. + * @return array The entities */ public function getEntitiesByIds($identifier, array $values); } diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php index 6ae98b57f8d42..1f2d1e9e1ed73 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php @@ -105,9 +105,9 @@ public function isIntId() * * This method assumes that the object has a single-column ID. * - * @param object $object The object. + * @param object $object The object * - * @return mixed The ID value. + * @return mixed The ID value */ public function getIdValue($object) { @@ -138,7 +138,7 @@ public function getIdValue($object) * * This method assumes that the object has a single-column ID. * - * @return string The name of the ID field. + * @return string The name of the ID field */ public function getIdField() { diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php index 3c5bd170009bf..632cdbfec0558 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php @@ -43,8 +43,8 @@ class ORMQueryBuilderLoader implements EntityLoaderInterface * deprecated and will not be * supported anymore as of * Symfony 3.0. - * @param ObjectManager $manager Deprecated. - * @param string $class Deprecated. + * @param ObjectManager $manager Deprecated + * @param string $class Deprecated * * @throws UnexpectedTypeException */ diff --git a/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php b/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php index 8f9b2ca7bf04c..e24c1968854be 100644 --- a/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php +++ b/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php @@ -56,9 +56,9 @@ abstract class DoctrineType extends AbstractType * * For backwards compatibility, objects are cast to strings by default. * - * @param object $choice The object. + * @param object $choice The object * - * @return string The string representation of the object. + * @return string The string representation of the object * * @internal This method is public to be usable as callback. It should not * be used in user code. @@ -75,12 +75,12 @@ public static function createChoiceLabel($choice) * a single-column integer ID. In that case, the value of the field is * the ID of the object. That ID is also used as field name. * - * @param object $choice The object. - * @param int|string $key The choice key. + * @param object $choice The object + * @param int|string $key The choice key * @param string $value The choice value. Corresponds to the object's * ID here. * - * @return string The field name. + * @return string The field name * * @internal This method is public to be usable as callback. It should not * be used in user code. diff --git a/src/Symfony/Bridge/Doctrine/HttpFoundation/DbalSessionHandler.php b/src/Symfony/Bridge/Doctrine/HttpFoundation/DbalSessionHandler.php index fd7dcff62c3d3..92c7b6bf40afd 100644 --- a/src/Symfony/Bridge/Doctrine/HttpFoundation/DbalSessionHandler.php +++ b/src/Symfony/Bridge/Doctrine/HttpFoundation/DbalSessionHandler.php @@ -180,7 +180,7 @@ public function write($sessionId, $data) $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); $updateStmt->execute(); - // When MERGE is not supported, like in Postgres, we have to use this approach that can result in + // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in // duplicate key errors when the same session is written simultaneously. We can just catch such an // error and re-execute the update. This is similar to a serializable transaction with retry logic // on serialization failures but without the overhead and without possible false positives due to @@ -224,11 +224,11 @@ private function getMergeSql() { $platform = $this->con->getDatabasePlatform()->getName(); - switch ($platform) { - case 'mysql': + switch (true) { + case 'mysql' === $platform: return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ". "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->timeCol = VALUES($this->timeCol)"; - case 'oracle': + case 'oracle' === $platform: // DUAL is Oracle specific dummy table return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) ". "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ". @@ -239,8 +239,11 @@ private function getMergeSql() return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = :id) ". "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ". "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->timeCol = :time;"; - case 'sqlite': + case 'sqlite' === $platform: return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)"; + case 'postgresql' === $platform && version_compare($this->con->getServerVersion(), '9.5', '>='): + return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ". + "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->timeCol)"; } } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php new file mode 100644 index 0000000000000..4848d88818f8a --- /dev/null +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php @@ -0,0 +1,459 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList; + +use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Common\Persistence\ObjectRepository; +use Doctrine\ORM\Mapping\ClassMetadata; +use Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader; +use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface; +use Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader; +use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface; + +/** + * @author Bernhard Schussek + */ +class DoctrineChoiceLoaderTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var ChoiceListFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $factory; + + /** + * @var ObjectManager|\PHPUnit_Framework_MockObject_MockObject + */ + private $om; + + /** + * @var ObjectRepository|\PHPUnit_Framework_MockObject_MockObject + */ + private $repository; + + /** + * @var string + */ + private $class; + + /** + * @var IdReader|\PHPUnit_Framework_MockObject_MockObject + */ + private $idReader; + + /** + * @var EntityLoaderInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $objectLoader; + + /** + * @var \stdClass + */ + private $obj1; + + /** + * @var \stdClass + */ + private $obj2; + + /** + * @var \stdClass + */ + private $obj3; + + protected function setUp() + { + $this->factory = $this->getMock('Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface'); + $this->om = $this->getMock('Doctrine\Common\Persistence\ObjectManager'); + $this->repository = $this->getMock('Doctrine\Common\Persistence\ObjectRepository'); + $this->class = 'stdClass'; + $this->idReader = $this->getMockBuilder('Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader') + ->disableOriginalConstructor() + ->getMock(); + $this->objectLoader = $this->getMock('Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface'); + $this->obj1 = (object) array('name' => 'A'); + $this->obj2 = (object) array('name' => 'B'); + $this->obj3 = (object) array('name' => 'C'); + + $this->om->expects($this->any()) + ->method('getRepository') + ->with($this->class) + ->willReturn($this->repository); + + $this->om->expects($this->any()) + ->method('getClassMetadata') + ->with($this->class) + ->willReturn(new ClassMetadata($this->class)); + } + + public function testLoadChoiceList() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $choices = array($this->obj1, $this->obj2, $this->obj3); + $choiceList = new ArrayChoiceList(array()); + $value = function () {}; + + $this->repository->expects($this->once()) + ->method('findAll') + ->willReturn($choices); + + $this->factory->expects($this->once()) + ->method('createListFromChoices') + ->with($choices, $value) + ->willReturn($choiceList); + + $this->assertSame($choiceList, $loader->loadChoiceList($value)); + + // no further loads on subsequent calls + + $this->assertSame($choiceList, $loader->loadChoiceList($value)); + } + + public function testLoadChoiceListUsesObjectLoaderIfAvailable() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader, + $this->objectLoader + ); + + $choices = array($this->obj1, $this->obj2, $this->obj3); + $choiceList = new ArrayChoiceList(array()); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->objectLoader->expects($this->once()) + ->method('getEntities') + ->willReturn($choices); + + $this->factory->expects($this->once()) + ->method('createListFromChoices') + ->with($choices) + ->willReturn($choiceList); + + $this->assertSame($choiceList, $loader->loadChoiceList()); + + // no further loads on subsequent calls + + $this->assertSame($choiceList, $loader->loadChoiceList()); + } + + public function testLoadValuesForChoices() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $choices = array($this->obj1, $this->obj2, $this->obj3); + $choiceList = new ArrayChoiceList($choices); + + $this->repository->expects($this->once()) + ->method('findAll') + ->willReturn($choices); + + $this->factory->expects($this->once()) + ->method('createListFromChoices') + ->with($choices) + ->willReturn($choiceList); + + $this->assertSame(array('1', '2'), $loader->loadValuesForChoices(array($this->obj2, $this->obj3))); + + // no further loads on subsequent calls + + $this->assertSame(array('1', '2'), $loader->loadValuesForChoices(array($this->obj2, $this->obj3))); + } + + public function testLoadValuesForChoicesDoesNotLoadIfEmptyChoices() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->factory->expects($this->never()) + ->method('createListFromChoices'); + + $this->assertSame(array(), $loader->loadValuesForChoices(array())); + } + + public function testLoadValuesForChoicesDoesNotLoadIfSingleIntId() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $this->idReader->expects($this->any()) + ->method('isSingleId') + ->willReturn(true); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->factory->expects($this->never()) + ->method('createListFromChoices'); + + $this->idReader->expects($this->any()) + ->method('getIdValue') + ->with($this->obj2) + ->willReturn('2'); + + $this->assertSame(array('2'), $loader->loadValuesForChoices(array($this->obj2))); + } + + public function testLoadValuesForChoicesLoadsIfSingleIntIdAndValueGiven() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $choices = array($this->obj1, $this->obj2, $this->obj3); + $value = function (\stdClass $object) { return $object->name; }; + $choiceList = new ArrayChoiceList($choices, $value); + + $this->idReader->expects($this->any()) + ->method('isSingleId') + ->willReturn(true); + + $this->repository->expects($this->once()) + ->method('findAll') + ->willReturn($choices); + + $this->factory->expects($this->once()) + ->method('createListFromChoices') + ->with($choices, $value) + ->willReturn($choiceList); + + $this->assertSame(array('B'), $loader->loadValuesForChoices( + array($this->obj2), + $value + )); + } + + public function testLoadValuesForChoicesDoesNotLoadIfValueIsIdReader() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $value = array($this->idReader, 'getIdValue'); + + $this->idReader->expects($this->any()) + ->method('isSingleId') + ->willReturn(true); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->factory->expects($this->never()) + ->method('createListFromChoices'); + + $this->idReader->expects($this->any()) + ->method('getIdValue') + ->with($this->obj2) + ->willReturn('2'); + + $this->assertSame(array('2'), $loader->loadValuesForChoices( + array($this->obj2), + $value + )); + } + + public function testLoadChoicesForValues() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $choices = array($this->obj1, $this->obj2, $this->obj3); + $choiceList = new ArrayChoiceList($choices); + + $this->repository->expects($this->once()) + ->method('findAll') + ->willReturn($choices); + + $this->factory->expects($this->once()) + ->method('createListFromChoices') + ->with($choices) + ->willReturn($choiceList); + + $this->assertSame(array($this->obj2, $this->obj3), $loader->loadChoicesForValues(array('1', '2'))); + + // no further loads on subsequent calls + + $this->assertSame(array($this->obj2, $this->obj3), $loader->loadChoicesForValues(array('1', '2'))); + } + + public function testLoadChoicesForValuesDoesNotLoadIfEmptyValues() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->factory->expects($this->never()) + ->method('createListFromChoices'); + + $this->assertSame(array(), $loader->loadChoicesForValues(array())); + } + + public function testLoadChoicesForValuesLoadsOnlyChoicesIfSingleIntId() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader, + $this->objectLoader + ); + + $choices = array($this->obj2, $this->obj3); + + $this->idReader->expects($this->any()) + ->method('isSingleId') + ->willReturn(true); + + $this->idReader->expects($this->any()) + ->method('getIdField') + ->willReturn('idField'); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->factory->expects($this->never()) + ->method('createListFromChoices'); + + $this->objectLoader->expects($this->once()) + ->method('getEntitiesByIds') + ->with('idField', array(4 => '3', 7 => '2')) + ->willReturn($choices); + + $this->idReader->expects($this->any()) + ->method('getIdValue') + ->willReturnMap(array( + array($this->obj2, '2'), + array($this->obj3, '3'), + )); + + $this->assertSame( + array(4 => $this->obj3, 7 => $this->obj2), + $loader->loadChoicesForValues(array(4 => '3', 7 => '2') + )); + } + + public function testLoadChoicesForValuesLoadsAllIfSingleIntIdAndValueGiven() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader + ); + + $choices = array($this->obj1, $this->obj2, $this->obj3); + $value = function (\stdClass $object) { return $object->name; }; + $choiceList = new ArrayChoiceList($choices, $value); + + $this->idReader->expects($this->any()) + ->method('isSingleId') + ->willReturn(true); + + $this->repository->expects($this->once()) + ->method('findAll') + ->willReturn($choices); + + $this->factory->expects($this->once()) + ->method('createListFromChoices') + ->with($choices, $value) + ->willReturn($choiceList); + + $this->assertSame(array($this->obj2), $loader->loadChoicesForValues( + array('B'), + $value + )); + } + + public function testLoadChoicesForValuesLoadsOnlyChoicesIfValueIsIdReader() + { + $loader = new DoctrineChoiceLoader( + $this->factory, + $this->om, + $this->class, + $this->idReader, + $this->objectLoader + ); + + $choices = array($this->obj2, $this->obj3); + $value = array($this->idReader, 'getIdValue'); + + $this->idReader->expects($this->any()) + ->method('isSingleId') + ->willReturn(true); + + $this->idReader->expects($this->any()) + ->method('getIdField') + ->willReturn('idField'); + + $this->repository->expects($this->never()) + ->method('findAll'); + + $this->factory->expects($this->never()) + ->method('createListFromChoices'); + + $this->objectLoader->expects($this->once()) + ->method('getEntitiesByIds') + ->with('idField', array('2')) + ->willReturn($choices); + + $this->idReader->expects($this->any()) + ->method('getIdValue') + ->willReturnMap(array( + array($this->obj2, '2'), + array($this->obj3, '3'), + )); + + $this->assertSame(array($this->obj2), $loader->loadChoicesForValues(array('2'), $value)); + } +} diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php index 469d8fa3d1d5d..2fdccb946daf9 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php @@ -222,8 +222,13 @@ public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder() $field->submit('2'); } - public function testConfigureQueryBuilderWithClosureReturningNull() + public function testConfigureQueryBuilderWithClosureReturningNullUseDefault() { + $entity1 = new SingleIntIdEntity(1, 'Foo'); + $entity2 = new SingleIntIdEntity(2, 'Bar'); + + $this->persist(array($entity1, $entity2)); + $field = $this->factory->createNamed('name', 'Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, @@ -232,7 +237,7 @@ public function testConfigureQueryBuilderWithClosureReturningNull() }, )); - $this->assertEquals(array(), $field->createView()->vars['choices']); + $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']); } public function testSetDataSingleNull() @@ -799,7 +804,11 @@ public function testOverrideChoicesValuesWithCallable() 'em' => 'default', 'class' => self::ITEM_GROUP_CLASS, 'choice_label' => 'name', - 'choice_value' => function (GroupableEntity $entity) { + 'choice_value' => function (GroupableEntity $entity = null) { + if (null === $entity) { + return ''; + } + return $entity->groupName.'/'.$entity->name; }, )); diff --git a/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php b/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php index 592584ffa4af0..0b9ada21b2c50 100644 --- a/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php @@ -168,7 +168,7 @@ protected function getDefaultFormatter() /** * Updates the logging level based on the verbosity setting of the console output. * - * @return bool Whether the handler is enabled and verbosity is not set to quiet. + * @return bool Whether the handler is enabled and verbosity is not set to quiet */ private function updateLevel() { diff --git a/src/Symfony/Bridge/Monolog/composer.json b/src/Symfony/Bridge/Monolog/composer.json index 433e0e103ff4c..e65fb26e7ef74 100644 --- a/src/Symfony/Bridge/Monolog/composer.json +++ b/src/Symfony/Bridge/Monolog/composer.json @@ -17,10 +17,10 @@ ], "require": { "php": ">=5.3.9", - "monolog/monolog": "~1.11" + "monolog/monolog": "~1.11", + "symfony/http-kernel": "~2.4" }, "require-dev": { - "symfony/http-kernel": "~2.4", "symfony/console": "~2.4|~3.0.0", "symfony/event-dispatcher": "~2.2|~3.0.0" }, diff --git a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php index 330798fa6eb89..efb2dadc861d8 100644 --- a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php +++ b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php @@ -32,7 +32,7 @@ class DeprecationErrorHandler * - use a number to define the upper bound of allowed deprecations, * making the test suite fail whenever more notices are trigerred. * - * @param int|string|false $mode The reporting mode. Defaults to not allowing any deprecations. + * @param int|string|false $mode The reporting mode, defaults to not allowing any deprecations */ public static function register($mode = 0) { diff --git a/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php b/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php index 24c17b865fb0e..646a9c2e6f1dd 100644 --- a/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php +++ b/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php @@ -27,7 +27,7 @@ class SymfonyTestsListener extends \PHPUnit_Framework_BaseTestListener private $isSkipped = array(); /** - * @param array $mockedNamespaces List of namespaces, indexed by mocked features (time-sensitive). + * @param array $mockedNamespaces List of namespaces, indexed by mocked features (time-sensitive) */ public function __construct(array $mockedNamespaces = array()) { diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/includes/foo.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/includes/foo.php index 1013a8c572325..16c898a370845 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/includes/foo.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/includes/foo.php @@ -2,9 +2,14 @@ class ProxyManagerBridgeFooClass { - public $foo, $moo; - - public $bar = null, $initialized = false, $configured = false, $called = false, $arguments = array(); + public $foo; + public $moo; + + public $bar = null; + public $initialized = false; + public $configured = false; + public $called = false; + public $arguments = array(); public function __construct($arguments = array()) { diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service.php index 69e1b9b3e7016..fd58c19d818db 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service.php @@ -38,7 +38,7 @@ public function __construct() * * @param bool $lazyLoad whether to try lazy-loading the service with a proxy * - * @return stdClass A stdClass instance. + * @return stdClass A stdClass instance */ public function getFooService($lazyLoad = true) { diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service_with_hints.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service_with_hints.php index 349d899649c92..f57c4c6360ba3 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service_with_hints.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/Fixtures/php/lazy_service_with_hints.php @@ -33,7 +33,7 @@ public function __construct() * * @param bool $lazyLoad whether to try lazy-loading the service with a proxy * - * @return stdClass A stdClass instance. + * @return stdClass A stdClass instance */ public function getFooService($lazyLoad = true) { diff --git a/src/Symfony/Bridge/Twig/Command/LintCommand.php b/src/Symfony/Bridge/Twig/Command/LintCommand.php index 31009a75b9e8a..ec7da4c37c8e0 100644 --- a/src/Symfony/Bridge/Twig/Command/LintCommand.php +++ b/src/Symfony/Bridge/Twig/Command/LintCommand.php @@ -66,18 +66,19 @@ protected function configure() The %command.name% command lints a template and outputs to STDOUT the first encountered syntax error. -You can validate the syntax of a file: +You can validate the syntax of contents passed from STDIN: -php %command.full_name% filename + cat filename | php %command.full_name% -Or of a whole directory: +Or the syntax of a file: + + php %command.full_name% filename -php %command.full_name% dirname -php %command.full_name% dirname --format=json +Or of a whole directory: -You can also pass the template contents from STDIN: + php %command.full_name% dirname + php %command.full_name% dirname --format=json -cat filename | php %command.full_name% EOF ) ; diff --git a/src/Symfony/Bridge/Twig/Extension/FormExtension.php b/src/Symfony/Bridge/Twig/Extension/FormExtension.php index 3f0a423337311..e833e3de2d228 100644 --- a/src/Symfony/Bridge/Twig/Extension/FormExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/FormExtension.php @@ -97,9 +97,9 @@ public function getTests() /** * Renders a CSRF token. * - * @param string $intention The intention of the protected action. + * @param string $intention The intention of the protected action * - * @return string A CSRF token. + * @return string A CSRF token */ public function renderCsrfToken($intention) { @@ -109,9 +109,9 @@ public function renderCsrfToken($intention) /** * Makes a technical name human readable. * - * @param string $text The text to humanize. + * @param string $text The text to humanize * - * @return string The humanized text. + * @return string The humanized text */ public function humanize($text) { @@ -134,10 +134,10 @@ public function humanize($text) * seems to be much more efficient at executing filters than at executing * methods of an object. * - * @param ChoiceView $choice The choice to check. - * @param string|array $selectedValue The selected value to compare. + * @param ChoiceView $choice The choice to check + * @param string|array $selectedValue The selected value to compare * - * @return bool Whether the choice is selected. + * @return bool Whether the choice is selected * * @see ChoiceView::isSelected() */ diff --git a/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php b/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php index f9dfea3571790..5248d5fd370ea 100644 --- a/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php +++ b/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php @@ -70,11 +70,11 @@ public function renderBlock(FormView $view, $resource, $blockName, array $variab * * @see getResourceForBlock() * - * @param string $cacheKey The cache key of the form view. - * @param FormView $view The form view for finding the applying themes. - * @param string $blockName The name of the block to load. + * @param string $cacheKey The cache key of the form view + * @param FormView $view The form view for finding the applying themes + * @param string $blockName The name of the block to load * - * @return bool True if the resource could be loaded, false otherwise. + * @return bool True if the resource could be loaded, false otherwise */ protected function loadResourceForBlockName($cacheKey, FormView $view, $blockName) { @@ -141,7 +141,7 @@ protected function loadResourceForBlockName($cacheKey, FormView $view, $blockNam /** * Loads the resources for all blocks in a theme. * - * @param string $cacheKey The cache key for storing the resource. + * @param string $cacheKey The cache key for storing the resource * @param mixed $theme The theme to load the block from. This parameter * is passed by reference, because it might be necessary * to initialize the theme first. Any changes made to diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php index 758b25c58d6e3..5560748c0b129 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php @@ -31,7 +31,7 @@ protected function listBundles($output) $rows = array(); $bundles = $this->getContainer()->get('kernel')->getBundles(); - usort($bundles, function($bundleA, $bundleB) { + usort($bundles, function ($bundleA, $bundleB) { return strcmp($bundleA->getName(), $bundleB->getName()); }); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml index 8d6dd4bf50750..7e86fb0728a03 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml @@ -192,5 +192,10 @@ + + + + %validator.translation_domain% + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml index b7a77671c58e3..f2123f4a6510f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml @@ -46,5 +46,9 @@ + + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_attributes.html.php new file mode 100644 index 0000000000000..8d2d6d7fd63c3 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_attributes.html.php @@ -0,0 +1,9 @@ +id="escape($id) ?>" name="escape($full_name) ?>" +disabled="disabled" + $v): ?> + +escape($k), $view->escape($k)) ?> + +escape($k), $view->escape($v)) ?> + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php index a0363cc5a47b8..f1c6ad3b56f21 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php @@ -8,6 +8,6 @@ block($form, 'choice_widget_options', array('choices' => $choice)) ?> - + diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php index 76f853643c6bb..5571c74e81d19 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php @@ -21,7 +21,7 @@ class RedirectableUrlMatcher extends BaseMatcher /** * Redirects the user to another URL. * - * @param string $path The path info to redirect to. + * @param string $path The path info to redirect to * @param string $route The route that matched * @param string $scheme The URL scheme (null to keep the current one) * diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php index 22848fcbfa35a..47c434aa476da 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php +++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php @@ -223,9 +223,9 @@ public function rest(FormView $view, array $variables = array()) /** * Renders a block of the template. * - * @param FormView $view The view for determining the used themes. - * @param string $blockName The name of the block to render. - * @param array $variables The variable to pass to the template. + * @param FormView $view The view for determining the used themes + * @param string $blockName The name of the block to render + * @param array $variables The variable to pass to the template * * @return string The HTML markup */ diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_1.txt index 91ed6790f03b7..4be149bffbe07 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_1.txt @@ -1,3 +1,3 @@ - // This service is an alias for the service service_1 + // This service is an alias for the service service_1 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_2.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_2.txt index 1ebffe38ac58a..0dbee6ac67c85 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_2.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/alias_2.txt @@ -1,3 +1,3 @@ - // This service is an alias for the service service_2 + // This service is an alias for the service service_2 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/array_parameter.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/array_parameter.txt index 6ba6c9c6ea714..903717b620cff 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/array_parameter.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/array_parameter.txt @@ -1,5 +1,5 @@ --------------------- ----------------------------------------------------------------- - Parameter Value +  Parameter   Value  --------------------- ----------------------------------------------------------------- twig.form.resources ["bootstrap_3_horizontal_layout.html.twig","bootstrap_3_layo... --------------------- ----------------------------------------------------------------- diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.txt index cc56a5a6c40cd..f03cb62bede8c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.txt @@ -2,7 +2,7 @@ ================================= ------------------- -------------------------------------------------------- - Service ID Class name +  Service ID   Class name  ------------------- -------------------------------------------------------- alias_1 alias for "service_1" alias_2 alias for "service_2" diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.txt index f539a2db7e63b..4434b248fdeb3 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.txt @@ -2,11 +2,11 @@ ============================================= ------------------- -------------------------------------------------------- - Service ID Class name +  Service ID   Class name  ------------------- -------------------------------------------------------- alias_1 alias for "service_1" alias_2 alias for "service_2" definition_1 Full\Qualified\Class1 definition_2 Full\Qualified\Class2 service_container Symfony\Component\DependencyInjection\ContainerBuilder - ------------------- -------------------------------------------------------- \ No newline at end of file + ------------------- -------------------------------------------------------- diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.txt index fd55212ad2bf4..e3f6ccbb02564 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.txt @@ -2,7 +2,7 @@ ==================================================================== -------------- ------- ------- ------- ----------------------- - Service ID attr1 attr2 attr3 Class name +  Service ID   attr1   attr2   attr3   Class name  -------------- ------- ------- ------- ----------------------- definition_2 val1 val2 Full\Qualified\Class2 " val3 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.txt index 7ab7df60e9a3a..cf3f4a21ab078 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.txt @@ -1,5 +1,5 @@ ------------------ ----------------------------- - Option Value +  Option   Value  ------------------ ----------------------------- Service ID - Class Full\Qualified\Class1 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.txt index 8211241055c90..4605072470b87 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.txt @@ -1,5 +1,5 @@ ------------------ ------------------------------------------------------- - Option Value +  Option   Value  ------------------ ------------------------------------------------------- Service ID - Class Full\Qualified\Class2 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_event1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_event1.txt index b8ae6b8c3f9ee..d411b672271cd 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_event1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_event1.txt @@ -2,7 +2,7 @@ ======================================= ------- ------------------- ---------- - Order Callable Priority +  Order   Callable   Priority  ------- ------------------- ---------- #1 global_function() 255 #2 \Closure() -1 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_events.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_events.txt index 2040a428aa221..52155be1cea36 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_events.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/event_dispatcher_1_events.txt @@ -5,7 +5,7 @@ -------------- ------- ------------------- ---------- - Order Callable Priority +  Order   Callable   Priority  ------- ------------------- ---------- #1 global_function() 255 #2 \Closure() -1 @@ -15,7 +15,7 @@ -------------- ------- ----------------------------------------------------------------------------------- ---------- - Order Callable Priority +  Order   Callable   Priority  ------- ----------------------------------------------------------------------------------- ---------- #1 Symfony\Bundle\FrameworkBundle\Tests\Console\Descriptor\CallableClass::__invoke() 0 - ------- ----------------------------------------------------------------------------------- ---------- \ No newline at end of file + ------- ----------------------------------------------------------------------------------- ---------- diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.txt index 6ccc8d9fe6820..fd56bcbea7586 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.txt @@ -1,5 +1,5 @@ ------------------ ----------------------------- - Option Value +  Option   Value  ------------------ ----------------------------- Service ID - Class Full\Qualified\Class1 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.txt index 8211241055c90..4605072470b87 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.txt @@ -1,5 +1,5 @@ ------------------ ------------------------------------------------------- - Option Value +  Option   Value  ------------------ ------------------------------------------------------- Service ID - Class Full\Qualified\Class2 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameter.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameter.txt index 34a6f43dbabaa..53e34624d0628 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameter.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameter.txt @@ -1,5 +1,5 @@ --------------- --------- - Parameter Value +  Parameter   Value  --------------- --------- database_name symfony --------------- --------- \ No newline at end of file diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameters_1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameters_1.txt index 8636c066e5a80..d363cd2e99be4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameters_1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/parameters_1.txt @@ -2,7 +2,7 @@ ============================ ----------- -------------------------- - Parameter Value +  Parameter   Value  ----------- -------------------------- array [12,"Hello world!",true] boolean true diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/route_collection_1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/route_collection_1.txt index 708438a10c098..95e83240ec05a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/route_collection_1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/route_collection_1.txt @@ -1,5 +1,5 @@ --------- ---------- ------------ ----------- --------------- - Name Method Scheme Host Path +  Name   Method   Scheme   Host   Path  --------- ---------- ------------ ----------- --------------- route_1 GET|HEAD http|https localhost /hello/{name} route_2 PUT|POST http|https localhost /name/add diff --git a/src/Symfony/Bundle/FrameworkBundle/composer.json b/src/Symfony/Bundle/FrameworkBundle/composer.json index 6b7853b036b26..c0a73efc6162f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/composer.json +++ b/src/Symfony/Bundle/FrameworkBundle/composer.json @@ -23,8 +23,8 @@ "symfony/config": "~2.8", "symfony/event-dispatcher": "~2.8|~3.0.0", "symfony/finder": "~2.0,>=2.0.5|~3.0.0", - "symfony/http-foundation": "~2.4.9|~2.5,>=2.5.4|~3.0.0", - "symfony/http-kernel": "~2.8", + "symfony/http-foundation": "~2.7", + "symfony/http-kernel": "~2.8.8", "symfony/polyfill-mbstring": "~1.0", "symfony/filesystem": "~2.3|~3.0.0", "symfony/routing": "~2.8|~3.0.0", @@ -38,7 +38,7 @@ }, "require-dev": { "symfony/browser-kit": "~2.4|~3.0.0", - "symfony/console": "~2.8|~3.0.0", + "symfony/console": "~2.8.8|~3.0.8", "symfony/css-selector": "~2.0,>=2.0.5|~3.0.0", "symfony/dom-crawler": "~2.0,>=2.0.5|~3.0.0", "symfony/polyfill-intl-icu": "~1.0", diff --git a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php index 0fff7552e858d..707c6338b9455 100644 --- a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php +++ b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php @@ -150,7 +150,7 @@ public function getInheritedRoles() * Checks if the data contains information about inherited roles. Still the inherited * roles can be an empty array. * - * @return bool true if the profile was contains inherited role information. + * @return bool true if the profile was contains inherited role information */ public function supportsRoleHierarchy() { diff --git a/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php b/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php index 237fda48ec931..47bb19380d285 100644 --- a/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php +++ b/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php @@ -28,7 +28,7 @@ class ExceptionController protected $twig; /** - * @var bool Show error (false) or exception (true) pages by default. + * @var bool Show error (false) or exception (true) pages by default */ protected $debug; diff --git a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php index ee537af4f9889..ab67078dd6ecd 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php +++ b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php @@ -98,6 +98,7 @@ public function onKernelResponse(FilterResponseEvent $event) || $response->isRedirection() || ($response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html')) || 'html' !== $request->getRequestFormat() + || false !== stripos($response->headers->get('Content-Disposition'), 'attachment;') ) { return; } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/time.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/time.html.twig index 1c065ed5fc295..14afbfca9590f 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/time.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/time.html.twig @@ -160,7 +160,7 @@ /** * Query an element with a CSS selector. * - * @param string selector a CSS-selector-compatible query string. + * @param string selector a CSS-selector-compatible query string * * @return DOMElement|null */ @@ -187,7 +187,7 @@ /** * Check whether this event is a child event. * - * @return true if it is. + * @return true if it is */ function isChildEvent(event) { @@ -197,7 +197,7 @@ /** * Check whether this event is categorized in 'section'. * - * @return true if it is. + * @return true if it is */ function isSectionEvent(event) { @@ -217,8 +217,8 @@ * * @param request the request object * @param max - * @param threshold the threshold (lower bound) of the length of the timeline (in milliseconds). - * @param width the width of the canvas. + * @param threshold the threshold (lower bound) of the length of the timeline (in milliseconds) + * @param width the width of the canvas */ this.drawOne = function(request, max, threshold, width) { diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/base_js.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/base_js.html.twig index 03617dfa957b3..cb4fbeed7e2cb 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/base_js.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/base_js.html.twig @@ -211,7 +211,7 @@ var addEventListener; var el = document.createElement('div'); - if (!'addEventListener' in el) { + if (!('addEventListener' in el)) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, callback); }; diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig index 8a6929c4df916..16487d3fcbd36 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig @@ -30,7 +30,7 @@

Route Redirection

This page redirects to:

-
+
{{ router.targetUrl }} {% if router.targetRoute %}(route: "{{ router.targetRoute }}"){% endif %}
diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php index e5d95471ae09f..f5aa3f4ab8531 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php @@ -82,6 +82,21 @@ public function testToolbarIsInjected() $this->assertEquals("\nWDT\n", $response->getContent()); } + /** + * @depends testToolbarIsInjected + */ + public function testToolbarIsNotInjectedOnContentDispositionAttachment() + { + $response = new Response(''); + $response->headers->set('Content-Disposition', 'attachment; filename=test.html'); + $event = new FilterResponseEvent($this->getKernelMock(), $this->getRequestMock(false, 'html'), HttpKernelInterface::MASTER_REQUEST, $response); + + $listener = new WebDebugToolbarListener($this->getTwigMock()); + $listener->onKernelResponse($event); + + $this->assertEquals('', $response->getContent()); + } + /** * @depends testToolbarIsInjected * @dataProvider provideRedirects diff --git a/src/Symfony/Component/BrowserKit/Request.php b/src/Symfony/Component/BrowserKit/Request.php index c79b341bed21f..2e2819b4ca465 100644 --- a/src/Symfony/Component/BrowserKit/Request.php +++ b/src/Symfony/Component/BrowserKit/Request.php @@ -111,7 +111,7 @@ public function getServer() /** * Gets the request raw body data. * - * @return string The request raw body data. + * @return string The request raw body data */ public function getContent() { diff --git a/src/Symfony/Component/ClassLoader/ApcClassLoader.php b/src/Symfony/Component/ClassLoader/ApcClassLoader.php index c21c64e38bfd2..46ee4a8566b1f 100644 --- a/src/Symfony/Component/ClassLoader/ApcClassLoader.php +++ b/src/Symfony/Component/ClassLoader/ApcClassLoader.php @@ -59,8 +59,8 @@ class ApcClassLoader /** * Constructor. * - * @param string $prefix The APC namespace prefix to use. - * @param object $decorated A class loader object that implements the findFile() method. + * @param string $prefix The APC namespace prefix to use + * @param object $decorated A class loader object that implements the findFile() method * * @throws \RuntimeException * @throws \InvalidArgumentException diff --git a/src/Symfony/Component/ClassLoader/WinCacheClassLoader.php b/src/Symfony/Component/ClassLoader/WinCacheClassLoader.php index 8c846e3c266f8..3e077450f1ebc 100644 --- a/src/Symfony/Component/ClassLoader/WinCacheClassLoader.php +++ b/src/Symfony/Component/ClassLoader/WinCacheClassLoader.php @@ -60,8 +60,8 @@ class WinCacheClassLoader /** * Constructor. * - * @param string $prefix The WinCache namespace prefix to use. - * @param object $decorated A class loader object that implements the findFile() method. + * @param string $prefix The WinCache namespace prefix to use + * @param object $decorated A class loader object that implements the findFile() method * * @throws \RuntimeException * @throws \InvalidArgumentException diff --git a/src/Symfony/Component/ClassLoader/XcacheClassLoader.php b/src/Symfony/Component/ClassLoader/XcacheClassLoader.php index 11da39d6f3ec4..aa4dc9d052b9f 100644 --- a/src/Symfony/Component/ClassLoader/XcacheClassLoader.php +++ b/src/Symfony/Component/ClassLoader/XcacheClassLoader.php @@ -60,8 +60,8 @@ class XcacheClassLoader /** * Constructor. * - * @param string $prefix The XCache namespace prefix to use. - * @param object $decorated A class loader object that implements the findFile() method. + * @param string $prefix The XCache namespace prefix to use + * @param object $decorated A class loader object that implements the findFile() method * * @throws \RuntimeException * @throws \InvalidArgumentException diff --git a/src/Symfony/Component/Config/ConfigCacheInterface.php b/src/Symfony/Component/Config/ConfigCacheInterface.php index e367ad187ee6c..7c47ad70a5685 100644 --- a/src/Symfony/Component/Config/ConfigCacheInterface.php +++ b/src/Symfony/Component/Config/ConfigCacheInterface.php @@ -32,7 +32,7 @@ public function getPath(); * * This check should take the metadata passed to the write() method into consideration. * - * @return bool Whether the cache is still fresh. + * @return bool Whether the cache is still fresh */ public function isFresh(); diff --git a/src/Symfony/Component/Config/Definition/ArrayNode.php b/src/Symfony/Component/Config/Definition/ArrayNode.php index f3a983eae369a..8320f4aac315e 100644 --- a/src/Symfony/Component/Config/Definition/ArrayNode.php +++ b/src/Symfony/Component/Config/Definition/ArrayNode.php @@ -349,8 +349,8 @@ protected function remapXml($value) /** * Merges values together. * - * @param mixed $leftSide The left side to merge. - * @param mixed $rightSide The right side to merge. + * @param mixed $leftSide The left side to merge + * @param mixed $rightSide The right side to merge * * @return mixed The merged values * diff --git a/src/Symfony/Component/Config/Definition/BaseNode.php b/src/Symfony/Component/Config/Definition/BaseNode.php index fc3e01291665a..dbf36335b69e3 100644 --- a/src/Symfony/Component/Config/Definition/BaseNode.php +++ b/src/Symfony/Component/Config/Definition/BaseNode.php @@ -184,7 +184,7 @@ public function isRequired() /** * Returns the name of this node. * - * @return string The Node's name. + * @return string The Node's name */ public function getName() { @@ -237,9 +237,9 @@ final public function merge($leftSide, $rightSide) /** * Normalizes a value, applying all normalization closures. * - * @param mixed $value Value to normalize. + * @param mixed $value Value to normalize * - * @return mixed The normalized value. + * @return mixed The normalized value */ final public function normalize($value) { @@ -329,7 +329,7 @@ abstract protected function validateType($value); /** * Normalizes the value. * - * @param mixed $value The value to normalize. + * @param mixed $value The value to normalize * * @return mixed The normalized value */ diff --git a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php index fb34cfa8f71f7..dc1c2fd8db224 100644 --- a/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php +++ b/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php @@ -178,7 +178,7 @@ public function fixXmlConfig($singular, $plural = null) * This method is applicable to prototype nodes only. * * @param string $name The name of the key - * @param bool $removeKeyItem Whether or not the key item should be removed. + * @param bool $removeKeyItem Whether or not the key item should be removed * * @return ArrayNodeDefinition */ diff --git a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php index 931b46792f100..ae1a76663a411 100644 --- a/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php +++ b/src/Symfony/Component/Config/Definition/PrototypedArrayNode.php @@ -278,8 +278,8 @@ protected function normalizeValue($value) /** * Merges values together. * - * @param mixed $leftSide The left side to merge. - * @param mixed $rightSide The right side to merge. + * @param mixed $leftSide The left side to merge + * @param mixed $rightSide The right side to merge * * @return mixed The merged values * diff --git a/src/Symfony/Component/Config/Definition/VariableNode.php b/src/Symfony/Component/Config/Definition/VariableNode.php index e2c0677475933..a9c35284cdcdb 100644 --- a/src/Symfony/Component/Config/Definition/VariableNode.php +++ b/src/Symfony/Component/Config/Definition/VariableNode.php @@ -57,7 +57,7 @@ public function getDefaultValue() /** * Sets if this node is allowed to have an empty value. * - * @param bool $boolean True if this entity will accept empty values. + * @param bool $boolean True if this entity will accept empty values */ public function setAllowEmptyValue($boolean) { diff --git a/src/Symfony/Component/Config/ResourceCheckerInterface.php b/src/Symfony/Component/Config/ResourceCheckerInterface.php index 27a04745a81a4..612d77786446a 100644 --- a/src/Symfony/Component/Config/ResourceCheckerInterface.php +++ b/src/Symfony/Component/Config/ResourceCheckerInterface.php @@ -39,10 +39,10 @@ public function supports(ResourceInterface $metadata); /** * Validates the resource. * - * @param ResourceInterface $resource The resource to be validated. - * @param int $timestamp The timestamp at which the cache associated with this resource was created. + * @param ResourceInterface $resource The resource to be validated + * @param int $timestamp The timestamp at which the cache associated with this resource was created * - * @return bool True if the resource has not changed since the given timestamp, false otherwise. + * @return bool True if the resource has not changed since the given timestamp, false otherwise */ public function isFresh(ResourceInterface $resource, $timestamp); } diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index 603559f0f6c0a..db6e814c6b4cb 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -238,7 +238,7 @@ public function getDefinition() /** * Gets the help message. * - * @return string A help message. + * @return string A help message */ public function getHelp() { diff --git a/src/Symfony/Component/Console/Exception/CommandNotFoundException.php b/src/Symfony/Component/Console/Exception/CommandNotFoundException.php index ce6fefe34abf2..54f1a5b0ce848 100644 --- a/src/Symfony/Component/Console/Exception/CommandNotFoundException.php +++ b/src/Symfony/Component/Console/Exception/CommandNotFoundException.php @@ -21,10 +21,10 @@ class CommandNotFoundException extends \InvalidArgumentException implements Exce private $alternatives; /** - * @param string $message Exception message to throw. - * @param array $alternatives List of similar defined names. - * @param int $code Exception code. - * @param Exception $previous previous exception used for the exception chaining. + * @param string $message Exception message to throw + * @param array $alternatives List of similar defined names + * @param int $code Exception code + * @param Exception $previous previous exception used for the exception chaining */ public function __construct($message, array $alternatives = array(), $code = 0, \Exception $previous = null) { @@ -34,7 +34,7 @@ public function __construct($message, array $alternatives = array(), $code = 0, } /** - * @return array A list of similar defined names. + * @return array A list of similar defined names */ public function getAlternatives() { diff --git a/src/Symfony/Component/Console/Helper/HelperSet.php b/src/Symfony/Component/Console/Helper/HelperSet.php index 27fedcf7b5c1c..896326ee3eca2 100644 --- a/src/Symfony/Component/Console/Helper/HelperSet.php +++ b/src/Symfony/Component/Console/Helper/HelperSet.php @@ -21,13 +21,16 @@ */ class HelperSet implements \IteratorAggregate { + /** + * @var Helper[] + */ private $helpers = array(); private $command; /** * Constructor. * - * @param Helper[] $helpers An array of helper. + * @param Helper[] $helpers An array of helper */ public function __construct(array $helpers = array()) { @@ -110,6 +113,9 @@ public function getCommand() return $this->command; } + /** + * @return Helper[] + */ public function getIterator() { return new \ArrayIterator($this->helpers); diff --git a/src/Symfony/Component/Console/Helper/ProgressBar.php b/src/Symfony/Component/Console/Helper/ProgressBar.php index e7717a528f0e3..89ca85d2f1071 100644 --- a/src/Symfony/Component/Console/Helper/ProgressBar.php +++ b/src/Symfony/Component/Console/Helper/ProgressBar.php @@ -42,8 +42,9 @@ class ProgressBar private $stepWidth; private $percent = 0.0; private $formatLineCount; - private $messages; + private $messages = array(); private $overwrite = true; + private $firstRun = true; private static $formatters; private static $formats; @@ -140,6 +141,16 @@ public static function getFormatDefinition($name) return isset(self::$formats[$name]) ? self::$formats[$name] : null; } + /** + * Associates a text with a named placeholder. + * + * The text is displayed when the progress bar is rendered but only + * when the corresponding placeholder is part of the custom format line + * (by wrapping the name with %). + * + * @param string $message The text to associate with the placeholder + * @param string $name The name of the placeholder + */ public function setMessage($message, $name = 'message') { $this->messages[$name] = $message; @@ -513,20 +524,24 @@ private function setMaxSteps($max) private function overwrite($message) { if ($this->overwrite) { - // Move the cursor to the beginning of the line - $this->output->write("\x0D"); + if (!$this->firstRun) { + // Move the cursor to the beginning of the line + $this->output->write("\x0D"); - // Erase the line - $this->output->write("\x1B[2K"); + // Erase the line + $this->output->write("\x1B[2K"); - // Erase previous lines - if ($this->formatLineCount > 0) { - $this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount)); + // Erase previous lines + if ($this->formatLineCount > 0) { + $this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount)); + } } } elseif ($this->step > 0) { $this->output->writeln(''); } + $this->firstRun = false; + $this->output->write($message); } diff --git a/src/Symfony/Component/Console/Helper/SymfonyQuestionHelper.php b/src/Symfony/Component/Console/Helper/SymfonyQuestionHelper.php index 942278bdf1a98..b17482556ee44 100644 --- a/src/Symfony/Component/Console/Helper/SymfonyQuestionHelper.php +++ b/src/Symfony/Component/Console/Helper/SymfonyQuestionHelper.php @@ -67,6 +67,18 @@ protected function writePrompt(OutputInterface $output, Question $question) break; + case $question instanceof ChoiceQuestion && $question->isMultiSelect(): + $choices = $question->getChoices(); + $default = explode(',', $default); + + foreach ($default as $key => $value) { + $default[$key] = $choices[trim($value)]; + } + + $text = sprintf(' %s [%s]:', $text, implode(', ', $default)); + + break; + case $question instanceof ChoiceQuestion: $choices = $question->getChoices(); $text = sprintf(' %s [%s]:', $text, $choices[$default]); diff --git a/src/Symfony/Component/Console/Helper/TableSeparator.php b/src/Symfony/Component/Console/Helper/TableSeparator.php index 8cbbc6613be36..8cc73e69a25f4 100644 --- a/src/Symfony/Component/Console/Helper/TableSeparator.php +++ b/src/Symfony/Component/Console/Helper/TableSeparator.php @@ -19,8 +19,7 @@ class TableSeparator extends TableCell { /** - * @param string $value - * @param array $options + * @param array $options */ public function __construct(array $options = array()) { diff --git a/src/Symfony/Component/Console/Input/ArgvInput.php b/src/Symfony/Component/Console/Input/ArgvInput.php index 02d4cdb3885b7..0bd6db29e73bb 100644 --- a/src/Symfony/Component/Console/Input/ArgvInput.php +++ b/src/Symfony/Component/Console/Input/ArgvInput.php @@ -46,8 +46,8 @@ class ArgvInput extends Input /** * Constructor. * - * @param array $argv An array of parameters from the CLI (in the argv format) - * @param InputDefinition $definition A InputDefinition instance + * @param array|null $argv An array of parameters from the CLI (in the argv format) + * @param InputDefinition|null $definition A InputDefinition instance */ public function __construct(array $argv = null, InputDefinition $definition = null) { @@ -69,7 +69,7 @@ protected function setTokens(array $tokens) } /** - * Processes command line arguments. + * {@inheritdoc} */ protected function parse() { @@ -93,7 +93,7 @@ protected function parse() /** * Parses a short option. * - * @param string $token The current token. + * @param string $token The current token */ private function parseShortOption($token) { @@ -253,9 +253,7 @@ private function addLongOption($name, $value) } /** - * Returns the first argument from the raw parameters (not parsed). - * - * @return string The value of the first argument or null otherwise + * {@inheritdoc} */ public function getFirstArgument() { @@ -269,14 +267,7 @@ public function getFirstArgument() } /** - * Returns true if the raw parameters (not parsed) contain a value. - * - * This method is to be used to introspect the input parameters - * before they have been validated. It must be used carefully. - * - * @param string|array $values The value(s) to look for in the raw parameters (can be an array) - * - * @return bool true if the value is contained in the raw parameters + * {@inheritdoc} */ public function hasParameterOption($values) { @@ -294,15 +285,7 @@ public function hasParameterOption($values) } /** - * Returns the value of a raw option (not parsed). - * - * This method is to be used to introspect the input parameters - * before they have been validated. It must be used carefully. - * - * @param string|array $values The value(s) to look for in the raw parameters (can be an array) - * @param mixed $default The default value to return if no result is found - * - * @return mixed The option value + * {@inheritdoc} */ public function getParameterOption($values, $default = false) { diff --git a/src/Symfony/Component/Console/Input/ArrayInput.php b/src/Symfony/Component/Console/Input/ArrayInput.php index 8cedbb37ecef6..af4c204bba30a 100644 --- a/src/Symfony/Component/Console/Input/ArrayInput.php +++ b/src/Symfony/Component/Console/Input/ArrayInput.php @@ -30,8 +30,8 @@ class ArrayInput extends Input /** * Constructor. * - * @param array $parameters An array of parameters - * @param InputDefinition $definition A InputDefinition instance + * @param array $parameters An array of parameters + * @param InputDefinition|null $definition A InputDefinition instance */ public function __construct(array $parameters, InputDefinition $definition = null) { @@ -41,9 +41,7 @@ public function __construct(array $parameters, InputDefinition $definition = nul } /** - * Returns the first argument from the raw parameters (not parsed). - * - * @return string The value of the first argument or null otherwise + * {@inheritdoc} */ public function getFirstArgument() { @@ -57,14 +55,7 @@ public function getFirstArgument() } /** - * Returns true if the raw parameters (not parsed) contain a value. - * - * This method is to be used to introspect the input parameters - * before they have been validated. It must be used carefully. - * - * @param string|array $values The values to look for in the raw parameters (can be an array) - * - * @return bool true if the value is contained in the raw parameters + * {@inheritdoc} */ public function hasParameterOption($values) { @@ -84,15 +75,7 @@ public function hasParameterOption($values) } /** - * Returns the value of a raw option (not parsed). - * - * This method is to be used to introspect the input parameters - * before they have been validated. It must be used carefully. - * - * @param string|array $values The value(s) to look for in the raw parameters (can be an array) - * @param mixed $default The default value to return if no result is found - * - * @return mixed The option value + * {@inheritdoc} */ public function getParameterOption($values, $default = false) { @@ -131,7 +114,7 @@ public function __toString() } /** - * Processes command line arguments. + * {@inheritdoc} */ protected function parse() { diff --git a/src/Symfony/Component/Console/Input/Input.php b/src/Symfony/Component/Console/Input/Input.php index 85499fc489d36..817292ed73086 100644 --- a/src/Symfony/Component/Console/Input/Input.php +++ b/src/Symfony/Component/Console/Input/Input.php @@ -38,7 +38,7 @@ abstract class Input implements InputInterface /** * Constructor. * - * @param InputDefinition $definition A InputDefinition instance + * @param InputDefinition|null $definition A InputDefinition instance */ public function __construct(InputDefinition $definition = null) { @@ -51,9 +51,7 @@ public function __construct(InputDefinition $definition = null) } /** - * Binds the current Input instance with the given arguments and options. - * - * @param InputDefinition $definition A InputDefinition instance + * {@inheritdoc} */ public function bind(InputDefinition $definition) { @@ -70,9 +68,7 @@ public function bind(InputDefinition $definition) abstract protected function parse(); /** - * Validates the input. - * - * @throws RuntimeException When not enough arguments are given + * {@inheritdoc} */ public function validate() { @@ -89,9 +85,7 @@ public function validate() } /** - * Checks if the input is interactive. - * - * @return bool Returns true if the input is interactive + * {@inheritdoc} */ public function isInteractive() { @@ -99,9 +93,7 @@ public function isInteractive() } /** - * Sets the input interactivity. - * - * @param bool $interactive If the input should be interactive + * {@inheritdoc} */ public function setInteractive($interactive) { @@ -109,9 +101,7 @@ public function setInteractive($interactive) } /** - * Returns the argument values. - * - * @return array An array of argument values + * {@inheritdoc} */ public function getArguments() { @@ -119,13 +109,7 @@ public function getArguments() } /** - * Returns the argument value for a given argument name. - * - * @param string $name The argument name - * - * @return mixed The argument value - * - * @throws InvalidArgumentException When argument given doesn't exist + * {@inheritdoc} */ public function getArgument($name) { @@ -137,12 +121,7 @@ public function getArgument($name) } /** - * Sets an argument value by name. - * - * @param string $name The argument name - * @param string $value The argument value - * - * @throws InvalidArgumentException When argument given doesn't exist + * {@inheritdoc} */ public function setArgument($name, $value) { @@ -154,11 +133,7 @@ public function setArgument($name, $value) } /** - * Returns true if an InputArgument object exists by name or position. - * - * @param string|int $name The InputArgument name or position - * - * @return bool true if the InputArgument object exists, false otherwise + * {@inheritdoc} */ public function hasArgument($name) { @@ -166,9 +141,7 @@ public function hasArgument($name) } /** - * Returns the options values. - * - * @return array An array of option values + * {@inheritdoc} */ public function getOptions() { @@ -176,13 +149,7 @@ public function getOptions() } /** - * Returns the option value for a given option name. - * - * @param string $name The option name - * - * @return mixed The option value - * - * @throws InvalidArgumentException When option given doesn't exist + * {@inheritdoc} */ public function getOption($name) { @@ -194,12 +161,7 @@ public function getOption($name) } /** - * Sets an option value by name. - * - * @param string $name The option name - * @param string|bool $value The option value - * - * @throws InvalidArgumentException When option given doesn't exist + * {@inheritdoc} */ public function setOption($name, $value) { @@ -211,11 +173,7 @@ public function setOption($name, $value) } /** - * Returns true if an InputOption object exists by name. - * - * @param string $name The InputOption name - * - * @return bool true if the InputOption object exists, false otherwise + * {@inheritdoc} */ public function hasOption($name) { diff --git a/src/Symfony/Component/Console/Input/InputInterface.php b/src/Symfony/Component/Console/Input/InputInterface.php index f83b88560d3e3..4501260970a50 100644 --- a/src/Symfony/Component/Console/Input/InputInterface.php +++ b/src/Symfony/Component/Console/Input/InputInterface.php @@ -11,6 +11,9 @@ namespace Symfony\Component\Console\Input; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\RuntimeException; + /** * InputInterface is the interface implemented by all input classes. * @@ -58,11 +61,9 @@ public function getParameterOption($values, $default = false); public function bind(InputDefinition $definition); /** - * Validates if arguments given are correct. - * - * Throws an exception when not enough arguments are given. + * Validates the input. * - * @throws \RuntimeException + * @throws RuntimeException When not enough arguments are given */ public function validate(); @@ -74,11 +75,13 @@ public function validate(); public function getArguments(); /** - * Gets argument by name. + * Returns the argument value for a given argument name. * - * @param string $name The name of the argument + * @param string $name The argument name * - * @return mixed + * @return mixed The argument value + * + * @throws InvalidArgumentException When argument given doesn't exist */ public function getArgument($name); @@ -109,11 +112,13 @@ public function hasArgument($name); public function getOptions(); /** - * Gets an option by name. + * Returns the option value for a given option name. * - * @param string $name The name of the option + * @param string $name The option name * - * @return mixed + * @return mixed The option value + * + * @throws InvalidArgumentException When option given doesn't exist */ public function getOption($name); diff --git a/src/Symfony/Component/Console/Output/NullOutput.php b/src/Symfony/Component/Console/Output/NullOutput.php index 682f9a4d432f4..218f285bfe51c 100644 --- a/src/Symfony/Component/Console/Output/NullOutput.php +++ b/src/Symfony/Component/Console/Output/NullOutput.php @@ -73,21 +73,33 @@ public function getVerbosity() return self::VERBOSITY_QUIET; } + /** + * {@inheritdoc} + */ public function isQuiet() { return true; } + /** + * {@inheritdoc} + */ public function isVerbose() { return false; } + /** + * {@inheritdoc} + */ public function isVeryVerbose() { return false; } + /** + * {@inheritdoc} + */ public function isDebug() { return false; diff --git a/src/Symfony/Component/Console/Output/Output.php b/src/Symfony/Component/Console/Output/Output.php index 4476ffb5901d0..c12015cc8fee0 100644 --- a/src/Symfony/Component/Console/Output/Output.php +++ b/src/Symfony/Component/Console/Output/Output.php @@ -94,21 +94,33 @@ public function getVerbosity() return $this->verbosity; } + /** + * {@inheritdoc} + */ public function isQuiet() { return self::VERBOSITY_QUIET === $this->verbosity; } + /** + * {@inheritdoc} + */ public function isVerbose() { return self::VERBOSITY_VERBOSE <= $this->verbosity; } + /** + * {@inheritdoc} + */ public function isVeryVerbose() { return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity; } + /** + * {@inheritdoc} + */ public function isDebug() { return self::VERBOSITY_DEBUG <= $this->verbosity; diff --git a/src/Symfony/Component/Console/Question/ChoiceQuestion.php b/src/Symfony/Component/Console/Question/ChoiceQuestion.php index 2c40638dc608e..39c4a852d0833 100644 --- a/src/Symfony/Component/Console/Question/ChoiceQuestion.php +++ b/src/Symfony/Component/Console/Question/ChoiceQuestion.php @@ -68,6 +68,16 @@ public function setMultiselect($multiselect) return $this; } + /** + * Returns whether the choices are multiselect. + * + * @return bool + */ + public function isMultiselect() + { + return $this->multiselect; + } + /** * Gets the prompt for choices. * diff --git a/src/Symfony/Component/Console/Style/SymfonyStyle.php b/src/Symfony/Component/Console/Style/SymfonyStyle.php index 53a7951e016d7..59c5bbf87ed9c 100644 --- a/src/Symfony/Component/Console/Style/SymfonyStyle.php +++ b/src/Symfony/Component/Console/Style/SymfonyStyle.php @@ -18,7 +18,6 @@ use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Helper\SymfonyQuestionHelper; use Symfony\Component\Console\Helper\Table; -use Symfony\Component\Console\Helper\TableCell; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; @@ -66,53 +65,10 @@ public function __construct(InputInterface $input, OutputInterface $output) */ public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false) { - $this->autoPrependBlock(); $messages = is_array($messages) ? array_values($messages) : array($messages); - $indentLength = 0; - $lines = array(); - - if (null !== $type) { - $typePrefix = sprintf('[%s] ', $type); - $indentLength = strlen($typePrefix); - $lineIndentation = str_repeat(' ', $indentLength); - } - - // wrap and add newlines for each element - foreach ($messages as $key => $message) { - $message = OutputFormatter::escape($message); - $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - Helper::strlen($prefix) - $indentLength, PHP_EOL, true))); - // prefix each line with a number of spaces equivalent to the type length - if (null !== $type) { - foreach ($lines as &$line) { - $line = $lineIndentation === substr($line, 0, $indentLength) ? $line : $lineIndentation.$line; - } - } - - if (count($messages) > 1 && $key < count($messages) - 1) { - $lines[] = ''; - } - } - - if (null !== $type) { - $lines[0] = substr_replace($lines[0], $typePrefix, 0, $indentLength); - } - - if ($padding && $this->isDecorated()) { - array_unshift($lines, ''); - $lines[] = ''; - } - - foreach ($lines as &$line) { - $line = sprintf('%s%s', $prefix, $line); - $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line)); - - if ($style) { - $line = sprintf('<%s>%s', $style, $line); - } - } - - $this->writeln($lines); + $this->autoPrependBlock(); + $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, true)); $this->newLine(); } @@ -177,11 +133,10 @@ public function text($message) public function comment($message) { $messages = is_array($message) ? array_values($message) : array($message); - foreach ($messages as &$message) { - $message = $this->getFormatter()->format($message); - } - $this->block($messages, null, null, ' // '); + $this->autoPrependBlock(); + $this->writeln($this->createBlock($messages, null, null, ' // ')); + $this->newLine(); } /** @@ -229,21 +184,13 @@ public function caution($message) */ public function table(array $headers, array $rows) { - array_walk_recursive($headers, function (&$value) { - if ($value instanceof TableCell) { - $value = new TableCell(sprintf('%s', $value), array( - 'colspan' => $value->getColspan(), - 'rowspan' => $value->getRowspan(), - )); - } else { - $value = sprintf('%s', $value); - } - }); + $style = clone Table::getStyleDefinition('symfony-style-guide'); + $style->setCellHeaderFormat('%s'); $table = new Table($this); $table->setHeaders($headers); $table->setRows($rows); - $table->setStyle('symfony-style-guide'); + $table->setStyle($style); $table->render(); $this->newLine(); @@ -437,4 +384,50 @@ private function reduceBuffer($messages) return substr($value, -4); }, array_merge(array($this->bufferedOutput->fetch()), (array) $messages)); } + + private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false) + { + $indentLength = 0; + $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix); + $lines = array(); + + if (null !== $type) { + $type = sprintf('[%s] ', $type); + $indentLength = strlen($type); + $lineIndentation = str_repeat(' ', $indentLength); + } + + // wrap and add newlines for each element + foreach ($messages as $key => $message) { + if ($escape) { + $message = OutputFormatter::escape($message); + } + + $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true))); + + if (count($messages) > 1 && $key < count($messages) - 1) { + $lines[] = ''; + } + } + + foreach ($lines as $i => &$line) { + if (null !== $type) { + $line = 0 === $i ? $type.$line : $lineIndentation.$line; + } + + $line = $prefix.$line; + $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line)); + + if ($style) { + $line = sprintf('<%s>%s', $style, $line); + } + } + + if ($padding && $this->isDecorated()) { + array_unshift($lines, ''); + $lines[] = ''; + } + + return $lines; + } } diff --git a/src/Symfony/Component/Console/Tester/ApplicationTester.php b/src/Symfony/Component/Console/Tester/ApplicationTester.php index da8a19ce50886..90efbab2182a8 100644 --- a/src/Symfony/Component/Console/Tester/ApplicationTester.php +++ b/src/Symfony/Component/Console/Tester/ApplicationTester.php @@ -37,7 +37,7 @@ class ApplicationTester /** * Constructor. * - * @param Application $application An Application instance to test. + * @param Application $application An Application instance to test */ public function __construct(Application $application) { diff --git a/src/Symfony/Component/Console/Tester/CommandTester.php b/src/Symfony/Component/Console/Tester/CommandTester.php index 8d6486e11c764..f95298bc90c79 100644 --- a/src/Symfony/Component/Console/Tester/CommandTester.php +++ b/src/Symfony/Component/Console/Tester/CommandTester.php @@ -32,7 +32,7 @@ class CommandTester /** * Constructor. * - * @param Command $command A Command instance to test. + * @param Command $command A Command instance to test */ public function __construct(Command $command) { diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_11.php b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_11.php index a2781ddbeafa4..678afea5d728e 100644 --- a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_11.php +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_11.php @@ -4,10 +4,9 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tests\Style\SymfonyStyleWithForcedLineLength; -//Ensure that all lines are aligned to the begin of the first one and start with '//' in a very long line comment +// ensure long words are properly wrapped in blocks return function (InputInterface $input, OutputInterface $output) { - $output = new SymfonyStyleWithForcedLineLength($input, $output); - $output->comment( - 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum' - ); + $word = 'Lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophattoperisteralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygon'; + $sfStyle = new SymfonyStyleWithForcedLineLength($input, $output); + $sfStyle->block($word, 'CUSTOM', 'fg=white;bg=blue', ' § ', false); }; diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_12.php b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_12.php new file mode 100644 index 0000000000000..4386e56de20da --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_12.php @@ -0,0 +1,13 @@ +comment( + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum' + ); +}; diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_13.php b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_13.php new file mode 100644 index 0000000000000..fe084365f96c0 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_13.php @@ -0,0 +1,15 @@ +setDecorated(true); + $output = new SymfonyStyle($input, $output); + $output->comment( + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum' + ); +}; diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_14.php b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_14.php new file mode 100644 index 0000000000000..e719f71812ca2 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_14.php @@ -0,0 +1,17 @@ +block( + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum', + null, + null, + '$ ', + true + ); +}; diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_15.php b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_15.php new file mode 100644 index 0000000000000..29e555b047094 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/command/command_15.php @@ -0,0 +1,14 @@ +block( + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum', + 'TEST' + ); +}; diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_11.txt b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_11.txt index 9983af832aa7d..190d784035476 100644 --- a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_11.txt +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_11.txt @@ -1,6 +1,4 @@ - // Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna - // aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. - // Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur - // sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum + § [CUSTOM] Lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophatto + § peristeralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygon diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_12.txt b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_12.txt new file mode 100644 index 0000000000000..9983af832aa7d --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_12.txt @@ -0,0 +1,6 @@ + + // Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna + // aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. + // Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur + // sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum + diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_13.txt b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_13.txt new file mode 100644 index 0000000000000..0f3704b7482ea --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_13.txt @@ -0,0 +1,7 @@ + + // Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et  + // dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea  + // commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla  + // pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim + // id est laborum + diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_14.txt b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_14.txt new file mode 100644 index 0000000000000..1d0d37e7fe31a --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_14.txt @@ -0,0 +1,6 @@ + +$ Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna +$ aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +$ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint +$ occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum + diff --git a/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_15.txt b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_15.txt new file mode 100644 index 0000000000000..66404b8151e41 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/Style/SymfonyStyle/output/output_15.txt @@ -0,0 +1,7 @@ + + [TEST] Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore + magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo + consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla + pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est + laborum + diff --git a/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php b/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php index 261908b542307..db2325b730406 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php @@ -29,7 +29,7 @@ public function testMultipleStart() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0 [>---------------------------]'). + ' 0 [>---------------------------]'. $this->generateOutput(' 1 [->--------------------------]'). $this->generateOutput(' 0 [>---------------------------]'), stream_get_contents($output->getStream()) @@ -44,7 +44,7 @@ public function testAdvance() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0 [>---------------------------]'). + ' 0 [>---------------------------]'. $this->generateOutput(' 1 [->--------------------------]'), stream_get_contents($output->getStream()) ); @@ -58,7 +58,7 @@ public function testAdvanceWithStep() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0 [>---------------------------]'). + ' 0 [>---------------------------]'. $this->generateOutput(' 5 [----->----------------------]'), stream_get_contents($output->getStream()) ); @@ -73,7 +73,7 @@ public function testAdvanceMultipleTimes() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0 [>---------------------------]'). + ' 0 [>---------------------------]'. $this->generateOutput(' 3 [--->------------------------]'). $this->generateOutput(' 5 [----->----------------------]'), stream_get_contents($output->getStream()) @@ -89,7 +89,7 @@ public function testAdvanceOverMax() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 9/10 [=========================>--] 90%'). + ' 9/10 [=========================>--] 90%'. $this->generateOutput(' 10/10 [============================] 100%'). $this->generateOutput(' 11/11 [============================] 100%'), stream_get_contents($output->getStream()) @@ -99,7 +99,7 @@ public function testAdvanceOverMax() public function testFormat() { $expected = - $this->generateOutput(' 0/10 [>---------------------------] 0%'). + ' 0/10 [>---------------------------] 0%'. $this->generateOutput(' 10/10 [============================] 100%'). $this->generateOutput(' 10/10 [============================] 100%') ; @@ -156,7 +156,7 @@ public function testCustomizations() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/10 [/ ] 0%'). + ' 0/10 [/ ] 0%'. $this->generateOutput(' 1/10 [_/ ] 10%'), stream_get_contents($output->getStream()) ); @@ -169,7 +169,7 @@ public function testDisplayWithoutStart() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/50 [>---------------------------] 0%'), + ' 0/50 [>---------------------------] 0%', stream_get_contents($output->getStream()) ); } @@ -193,7 +193,7 @@ public function testFinishWithoutStart() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 50/50 [============================] 100%'), + ' 50/50 [============================] 100%', stream_get_contents($output->getStream()) ); } @@ -208,7 +208,7 @@ public function testPercent() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/50 [>---------------------------] 0%'). + ' 0/50 [>---------------------------] 0%'. $this->generateOutput(' 0/50 [>---------------------------] 0%'). $this->generateOutput(' 1/50 [>---------------------------] 2%'). $this->generateOutput(' 2/50 [=>--------------------------] 4%'), @@ -230,7 +230,7 @@ public function testOverwriteWithShorterLine() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/50 [>---------------------------] 0%'). + ' 0/50 [>---------------------------] 0%'. $this->generateOutput(' 0/50 [>---------------------------] 0%'). $this->generateOutput(' 1/50 [>---------------------------] 2%'). $this->generateOutput(' 2/50 [=>--------------------------]'), @@ -247,7 +247,7 @@ public function testStartWithMax() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/50 [>---------------------------]'). + ' 0/50 [>---------------------------]'. $this->generateOutput(' 1/50 [>---------------------------]'), stream_get_contents($output->getStream()) ); @@ -264,7 +264,7 @@ public function testSetCurrentProgress() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/50 [>---------------------------] 0%'). + ' 0/50 [>---------------------------] 0%'. $this->generateOutput(' 0/50 [>---------------------------] 0%'). $this->generateOutput(' 1/50 [>---------------------------] 2%'). $this->generateOutput(' 15/50 [========>-------------------] 30%'). @@ -336,7 +336,7 @@ public function testMultiByteSupport() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0 [>---------------------------]'). + ' 0 [>---------------------------]'. $this->generateOutput(' 3 [■■■>------------------------]'), stream_get_contents($output->getStream()) ); @@ -351,7 +351,7 @@ public function testClear() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/50 [>---------------------------] 0%'). + ' 0/50 [>---------------------------] 0%'. $this->generateOutput(' 25/50 [==============>-------------] 50%'). $this->generateOutput(''), stream_get_contents($output->getStream()) @@ -368,7 +368,7 @@ public function testPercentNotHundredBeforeComplete() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/200 [>---------------------------] 0%'). + ' 0/200 [>---------------------------] 0%'. $this->generateOutput(' 0/200 [>---------------------------] 0%'). $this->generateOutput(' 199/200 [===========================>] 99%'). $this->generateOutput(' 200/200 [============================] 100%'), @@ -468,9 +468,9 @@ public function testParallelBars() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/2 [>---------------------------] 0%')."\n". - $this->generateOutput(' 0/3 [#---------------------------] 0%')."\n". - rtrim($this->generateOutput(' 0 [>---------------------------]')). + ' 0/2 [>---------------------------] 0%'."\n". + ' 0/3 [#---------------------------] 0%'."\n". + rtrim(' 0 [>---------------------------]'). "\033[2A". $this->generateOutput(' 1/2 [==============>-------------] 50%')."\n". @@ -508,7 +508,7 @@ public function testWithoutMax() rewind($output->getStream()); $this->assertEquals( - rtrim($this->generateOutput(' 0 [>---------------------------]')). + rtrim(' 0 [>---------------------------]'). rtrim($this->generateOutput(' 1 [->--------------------------]')). rtrim($this->generateOutput(' 2 [-->-------------------------]')). rtrim($this->generateOutput(' 3 [--->------------------------]')). @@ -531,7 +531,7 @@ public function testAddingPlaceholderFormatter() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 3 [>---------------------------]'). + ' 3 [>---------------------------]'. $this->generateOutput(' 2 [=========>------------------]'). $this->generateOutput(' 0 [============================]'), stream_get_contents($output->getStream()) @@ -550,7 +550,7 @@ public function testMultilineFormat() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(">---------------------------\nfoobar"). + ">---------------------------\nfoobar". $this->generateOutput("=========>------------------\nfoobar"). "\x0D\x1B[2K\x1B[1A\x1B[2K". $this->generateOutput("============================\nfoobar"), @@ -582,11 +582,11 @@ public function testAnsiColorsAndEmojis() rewind($output->getStream()); $this->assertEquals( - $this->generateOutput( + " \033[44;37m Starting the demo... fingers crossed \033[0m\n". ' 0/15 '.$progress.str_repeat($empty, 26)." 0%\n". " \xf0\x9f\x8f\x81 < 1 sec \033[44;37m 0 B \033[0m" - ). + . $this->generateOutput( " \033[44;37m Looks good to me... \033[0m\n". ' 4/15 '.str_repeat($done, 7).$progress.str_repeat($empty, 19)." 26%\n". @@ -608,7 +608,7 @@ public function testSetFormat() $bar->start(); rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0 [>---------------------------]'), + ' 0 [>---------------------------]', stream_get_contents($output->getStream()) ); @@ -617,7 +617,7 @@ public function testSetFormat() $bar->start(); rewind($output->getStream()); $this->assertEquals( - $this->generateOutput(' 0/10 [>---------------------------] 0%'), + ' 0/10 [>---------------------------] 0%', stream_get_contents($output->getStream()) ); } diff --git a/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php new file mode 100644 index 0000000000000..032e153f068f1 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Helper/SymfonyQuestionHelperTest.php @@ -0,0 +1,109 @@ +setHelperSet($helperSet); + + $heroes = array('Superman', 'Batman', 'Spiderman'); + + $questionHelper->setInputStream($this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n")); + + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '2'); + $question->setMaxAttempts(1); + // first answer is an empty answer, we're supposed to receive the default value + $this->assertEquals('Spiderman', $questionHelper->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question)); + $this->assertOutputContains('What is your favorite superhero? [Spiderman]', $output); + + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes); + $question->setMaxAttempts(1); + $this->assertEquals('Batman', $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); + $this->assertEquals('Batman', $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); + + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes); + $question->setErrorMessage('Input "%s" is not a superhero!'); + $question->setMaxAttempts(2); + $this->assertEquals('Batman', $questionHelper->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question)); + $this->assertOutputContains('Input "Fabien" is not a superhero!', $output); + + try { + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '1'); + $question->setMaxAttempts(1); + $questionHelper->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question); + $this->fail(); + } catch (\InvalidArgumentException $e) { + $this->assertEquals('Value "Fabien" is invalid', $e->getMessage()); + } + + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, null); + $question->setMaxAttempts(1); + $question->setMultiselect(true); + + $this->assertEquals(array('Batman'), $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); + $this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); + $this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); + + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0,1'); + $question->setMaxAttempts(1); + $question->setMultiselect(true); + + $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question)); + $this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output); + + $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, ' 0 , 1 '); + $question->setMaxAttempts(1); + $question->setMultiselect(true); + + $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question)); + $this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output); + } + + protected function getInputStream($input) + { + $stream = fopen('php://memory', 'r+', false); + fwrite($stream, $input); + rewind($stream); + + return $stream; + } + + protected function createOutputInterface() + { + $output = new StreamOutput(fopen('php://memory', 'r+', false)); + $output->setDecorated(false); + + return $output; + } + + protected function createInputInterfaceMock($interactive = true) + { + $mock = $this->getMock('Symfony\Component\Console\Input\InputInterface'); + $mock->expects($this->any()) + ->method('isInteractive') + ->will($this->returnValue($interactive)); + + return $mock; + } + + private function assertOutputContains($expected, StreamOutput $output) + { + rewind($output->getStream()); + $stream = stream_get_contents($output->getStream()); + $this->assertContains($expected, $stream); + } +} diff --git a/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php b/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php index 7e0a24258f3c2..f3d2c0d64ee28 100644 --- a/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php +++ b/src/Symfony/Component/Console/Tests/Input/InputDefinitionTest.php @@ -19,7 +19,10 @@ class InputDefinitionTest extends \PHPUnit_Framework_TestCase { protected static $fixtures; - protected $foo, $bar, $foo1, $foo2; + protected $foo; + protected $bar; + protected $foo1; + protected $foo2; public static function setUpBeforeClass() { diff --git a/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php b/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php index 889a9c82f2dcb..e4ce037bb8f16 100644 --- a/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php +++ b/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php @@ -54,22 +54,6 @@ public function inputCommandToOutputFilesProvider() return array_map(null, glob($baseDir.'/command/command_*.php'), glob($baseDir.'/output/output_*.txt')); } - - public function testLongWordsBlockWrapping() - { - $word = 'Lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophattoperisteralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygovgollhjvhvljfezefeqifzeiqgiqzhrsdgihqzridghqridghqirshdghdghieridgheirhsdgehrsdvhqrsidhqshdgihrsidvqhneriqsdvjzergetsrfhgrstsfhsetsfhesrhdgtesfhbzrtfbrztvetbsdfbrsdfbrn'; - $wordLength = strlen($word); - $maxLineLength = SymfonyStyle::MAX_LINE_LENGTH - 3; - - $this->command->setCode(function (InputInterface $input, OutputInterface $output) use ($word) { - $sfStyle = new SymfonyStyleWithForcedLineLength($input, $output); - $sfStyle->block($word, 'CUSTOM', 'fg=white;bg=blue', ' § ', false); - }); - - $this->tester->execute(array(), array('interactive' => false, 'decorated' => false)); - $expectedCount = (int) ceil($wordLength / ($maxLineLength)) + (int) ($wordLength > $maxLineLength - 5); - $this->assertSame($expectedCount, substr_count($this->tester->getDisplay(true), ' § ')); - } } /** diff --git a/src/Symfony/Component/CssSelector/CssSelector.php b/src/Symfony/Component/CssSelector/CssSelector.php index 6900c6493d9b9..c38c9e77a0a02 100644 --- a/src/Symfony/Component/CssSelector/CssSelector.php +++ b/src/Symfony/Component/CssSelector/CssSelector.php @@ -68,8 +68,8 @@ class CssSelector * Optionally, a prefix can be added to the resulting XPath * expression with the $prefix parameter. * - * @param mixed $cssExpr The CSS expression. - * @param string $prefix An optional prefix for the XPath expression. + * @param mixed $cssExpr The CSS expression + * @param string $prefix An optional prefix for the XPath expression * * @return string */ diff --git a/src/Symfony/Component/CssSelector/CssSelectorConverter.php b/src/Symfony/Component/CssSelector/CssSelectorConverter.php index e31ac1917afba..8d66dbd0e18f2 100644 --- a/src/Symfony/Component/CssSelector/CssSelectorConverter.php +++ b/src/Symfony/Component/CssSelector/CssSelectorConverter.php @@ -29,7 +29,7 @@ class CssSelectorConverter private $translator; /** - * @param bool $html Whether HTML support should be enabled. Disable it for XML documents. + * @param bool $html Whether HTML support should be enabled. Disable it for XML documents */ public function __construct($html = true) { @@ -53,8 +53,8 @@ public function __construct($html = true) * Optionally, a prefix can be added to the resulting XPath * expression with the $prefix parameter. * - * @param string $cssExpr The CSS expression. - * @param string $prefix An optional prefix for the XPath expression. + * @param string $cssExpr The CSS expression + * @param string $prefix An optional prefix for the XPath expression * * @return string */ diff --git a/src/Symfony/Component/Debug/ErrorHandler.php b/src/Symfony/Component/Debug/ErrorHandler.php index 8053760285d73..4439faa3d8e9b 100644 --- a/src/Symfony/Component/Debug/ErrorHandler.php +++ b/src/Symfony/Component/Debug/ErrorHandler.php @@ -380,7 +380,7 @@ private function reRegister($prev) * @param int $line * @param array $context * - * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself. + * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself * * @throws \ErrorException When $this->thrownErrors requests so * diff --git a/src/Symfony/Component/Debug/ExceptionHandler.php b/src/Symfony/Component/Debug/ExceptionHandler.php index c44b4a7b4abbb..e738d8b012e52 100644 --- a/src/Symfony/Component/Debug/ExceptionHandler.php +++ b/src/Symfony/Component/Debug/ExceptionHandler.php @@ -96,7 +96,7 @@ public function setHandler($handler) * * @param string $format The format for links to source files * - * @return string The previous file link format. + * @return string The previous file link format */ public function setFileLinkFormat($format) { diff --git a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php index a5ce693078725..96554d8507577 100644 --- a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php @@ -18,7 +18,7 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase { /** - * @var int Error reporting level before running tests. + * @var int Error reporting level before running tests */ private $errorReporting; diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php index 42b491c7c70e8..681f8afdde744 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php @@ -126,7 +126,7 @@ private function processArguments(array $arguments) /** * Returns a service definition given the full name or an alias. * - * @param string $id A full id or alias for a service definition. + * @param string $id A full id or alias for a service definition * * @return Definition|null The definition related to the supplied id */ diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php index 5065ed1880e87..cd5b61b29052b 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php @@ -229,7 +229,6 @@ private function createAutowiredDefinition(\ReflectionClass $typeHint, $id) $matchingServices = implode(', ', $this->types[$typeHint->name]); throw new RuntimeException(sprintf('Unable to autowire argument of type "%s" for the service "%s". Multiple services exist for this %s (%s).', $typeHint->name, $id, $classOrInterface, $matchingServices)); - } if (!$typeHint->isInstantiable()) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php index e80d3ccbf7b53..5c58656a520c6 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php @@ -139,7 +139,6 @@ private function updateFactoryReference(array $replacements, $factory) $factory[0] = new Reference($replacements[$referenceId], $factory[0]->getInvalidBehavior()); } - return $factory; } } diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php index 4544f478cd7bb..e4c529e49a7e8 100644 --- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php +++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php @@ -354,7 +354,7 @@ public function getScopes($triggerDeprecationError = true) /** * Returns all Scope children. * - * @return array An array of scope children. + * @return array An array of scope children * * @deprecated since version 2.8, to be removed in 3.0. */ @@ -510,7 +510,7 @@ public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INV * parameter, the value will still be 'bar' as defined in the ContainerBuilder * constructor. * - * @param ContainerBuilder $container The ContainerBuilder instance to merge. + * @param ContainerBuilder $container The ContainerBuilder instance to merge * * @throws BadMethodCallException When this ContainerBuilder is frozen */ @@ -1011,7 +1011,7 @@ public function resolveServices($value) * * @param string $name The tag name * - * @return array An array of tags with the tagged service as key, holding a list of attribute arrays. + * @return array An array of tags with the tagged service as key, holding a list of attribute arrays */ public function findTaggedServiceIds($name) { @@ -1067,7 +1067,7 @@ public function getExpressionLanguageProviders() /** * Returns the Service Conditionals. * - * @param mixed $value An array of conditionals to return. + * @param mixed $value An array of conditionals to return * * @return array An array of Service conditionals */ diff --git a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php index 83ee0a0e7d303..c03465ad423f5 100644 --- a/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php +++ b/src/Symfony/Component/DependencyInjection/DefinitionDecorator.php @@ -25,7 +25,7 @@ class DefinitionDecorator extends Definition private $changes = array(); /** - * @param string $parent The id of Definition instance to decorate. + * @param string $parent The id of Definition instance to decorate */ public function __construct($parent) { diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index 9394876731dce..9e8d2381157ff 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -570,22 +570,22 @@ private function addService($id, $definition) if ($definition->isSynthetic()) { $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically'; } elseif ($class = $definition->getClass()) { - $return[] = sprintf('@return %s A %s instance.', 0 === strpos($class, '%') ? 'object' : '\\'.ltrim($class, '\\'), ltrim($class, '\\')); + $return[] = sprintf('@return %s A %s instance', 0 === strpos($class, '%') ? 'object' : '\\'.ltrim($class, '\\'), ltrim($class, '\\')); } elseif ($definition->getFactory()) { $factory = $definition->getFactory(); if (is_string($factory)) { - $return[] = sprintf('@return object An instance returned by %s().', $factory); + $return[] = sprintf('@return object An instance returned by %s()', $factory); } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) { if (is_string($factory[0]) || $factory[0] instanceof Reference) { - $return[] = sprintf('@return object An instance returned by %s::%s().', (string) $factory[0], $factory[1]); + $return[] = sprintf('@return object An instance returned by %s::%s()', (string) $factory[0], $factory[1]); } elseif ($factory[0] instanceof Definition) { - $return[] = sprintf('@return object An instance returned by %s::%s().', $factory[0]->getClass(), $factory[1]); + $return[] = sprintf('@return object An instance returned by %s::%s()', $factory[0]->getClass(), $factory[1]); } } } elseif ($definition->getFactoryClass(false)) { - $return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryClass(false), $definition->getFactoryMethod(false)); + $return[] = sprintf('@return object An instance returned by %s::%s()', $definition->getFactoryClass(false), $definition->getFactoryMethod(false)); } elseif ($definition->getFactoryService(false)) { - $return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryService(false), $definition->getFactoryMethod(false)); + $return[] = sprintf('@return object An instance returned by %s::%s()', $definition->getFactoryService(false), $definition->getFactoryMethod(false)); } $scope = $definition->getScope(false); diff --git a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php index 300a19ffcfdb9..96b0b597053c3 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php @@ -338,7 +338,6 @@ private function processAnonymousServices(\DOMDocument $xml, $file) foreach ($definitions as $id => $def) { list($domElement, $file, $wild) = $def; - if (null !== $definition = $this->parseDefinition($domElement, $file)) { $this->container->setDefinition($id, $definition); } @@ -508,7 +507,9 @@ public function validateSchema(\DOMDocument $dom) EOF ; + $disableEntities = libxml_disable_entity_loader(false); $valid = @$dom->schemaValidateSource($source); + libxml_disable_entity_loader($disableEntities); foreach ($tmpfiles as $tmpfile) { @unlink($tmpfile); diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php index 8e80c47205908..f9f6aabe73282 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php @@ -14,6 +14,7 @@ require_once __DIR__.'/Fixtures/includes/classes.php'; require_once __DIR__.'/Fixtures/includes/ProjectExtension.php'; +use Symfony\Bridge\PhpUnit\ErrorAssert; use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -61,27 +62,13 @@ public function testDefinitions() public function testCreateDeprecatedService() { - $deprecations = array(); - set_error_handler(function ($type, $msg) use (&$deprecations) { - if (E_USER_DEPRECATED !== $type) { - restore_error_handler(); + ErrorAssert::assertDeprecationsAreTriggered('The "deprecated_foo" service is deprecated. You should stop using it, as it will soon be removed.', function () { + $definition = new Definition('stdClass'); + $definition->setDeprecated(true); - return call_user_func_array('PHPUnit_Util_ErrorHandler::handleError', func_get_args()); - } - - $deprecations[] = $msg; + $builder = new ContainerBuilder(); + $builder->createService($definition, 'deprecated_foo'); }); - - $definition = new Definition('stdClass'); - $definition->setDeprecated(true); - - $builder = new ContainerBuilder(); - $builder->createService($definition, 'deprecated_foo'); - - restore_error_handler(); - - $this->assertCount(1, $deprecations); - $this->assertContains('The "deprecated_foo" service is deprecated. You should stop using it, as it will soon be removed.', $deprecations[0]); } public function testRegister() diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php index 8d4fc6004ddd0..8e1ab10f7af49 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php @@ -692,7 +692,9 @@ public function testThatCloningIsNotSupported() class ProjectServiceContainer extends Container { - public $__bar, $__foo_bar, $__foo_baz; + public $__bar; + public $__foo_bar; + public $__foo_baz; public $synchronized; public function __construct() diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/foo.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/foo.php index 55968aff923c4..bcb4e20a94afd 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/foo.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/foo.php @@ -4,9 +4,14 @@ class FooClass { - public $foo, $moo; - - public $bar = null, $initialized = false, $configured = false, $called = false, $arguments = array(); + public $foo; + public $moo; + + public $bar = null; + public $initialized = false; + public $configured = false; + public $called = false; + public $arguments = array(); public function __construct($arguments = array()) { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services10.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services10.php index b9b8d5b38620b..ecf87158a916d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services10.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services10.php @@ -52,7 +52,7 @@ public function compile() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getTestService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services12.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services12.php index a53f3a3e8176f..62d1d5efa59d0 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services12.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services12.php @@ -56,7 +56,7 @@ public function compile() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getTestService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services13.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services13.php index f6038f390367e..048a9dda76563 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services13.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services13.php @@ -50,7 +50,7 @@ public function compile() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getBarService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php index 455600da7d830..985f0a96283d5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php @@ -37,7 +37,7 @@ public function __construct() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getServiceFromAnonymousFactoryService() { @@ -50,7 +50,7 @@ protected function getServiceFromAnonymousFactoryService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getServiceWithMethodCallAndFactoryService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services20.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services20.php index 83f6dc7ed3c24..ec0887ecbcab1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services20.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services20.php @@ -37,7 +37,7 @@ public function __construct() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getDependsOnRequestService() { @@ -54,7 +54,7 @@ protected function getDependsOnRequestService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Request A Request instance. + * @return \Request A Request instance */ protected function getRequestService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services24.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services24.php index fb8dd19fd2b1a..aa02494ca0332 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services24.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services24.php @@ -35,7 +35,7 @@ public function __construct() * * This service is autowired. * - * @return \Foo A Foo instance. + * @return \Foo A Foo instance */ protected function getFooService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php index 675f17ec2a717..e30b809c67a29 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php @@ -58,7 +58,7 @@ public function __construct() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getBarService() { @@ -77,7 +77,7 @@ protected function getBarService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Baz A Baz instance. + * @return \Baz A Baz instance */ protected function getBazService() { @@ -94,7 +94,7 @@ protected function getBazService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getConfiguredServiceService() { @@ -111,7 +111,7 @@ protected function getConfiguredServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getDecoratedService() { @@ -124,7 +124,7 @@ protected function getDecoratedService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getDecoratorServiceService() { @@ -137,7 +137,7 @@ protected function getDecoratorServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getDecoratorServiceWithNameService() { @@ -150,7 +150,7 @@ protected function getDecoratorServiceWithNameService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance * * @deprecated The "deprecated_service" service is deprecated. You should stop using it, as it will soon be removed. */ @@ -167,7 +167,7 @@ protected function getDeprecatedServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar A Bar instance. + * @return \Bar A Bar instance */ protected function getFactoryServiceService() { @@ -180,7 +180,7 @@ protected function getFactoryServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getFooService() { @@ -204,7 +204,7 @@ protected function getFooService() * This service is shared. * This method always returns the same instance of the service. * - * @return object A %baz_class% instance. + * @return object A %baz_class% instance */ protected function getFoo_BazService() { @@ -218,7 +218,7 @@ protected function getFoo_BazService() /** * Gets the 'foo_bar' service. * - * @return object A %foo_class% instance. + * @return object A %foo_class% instance */ protected function getFooBarService() { @@ -233,7 +233,7 @@ protected function getFooBarService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Foo A Foo instance. + * @return \Foo A Foo instance */ protected function getFooWithInlineService() { @@ -250,7 +250,7 @@ protected function getFooWithInlineService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getMethodCall1Service() { @@ -277,7 +277,7 @@ protected function getMethodCall1Service() * This service is shared. * This method always returns the same instance of the service. * - * @return \FooBarBaz A FooBarBaz instance. + * @return \FooBarBaz A FooBarBaz instance */ protected function getNewFactoryServiceService() { @@ -307,7 +307,7 @@ protected function getRequestService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getServiceFromStaticMethodService() { @@ -324,7 +324,7 @@ protected function getServiceFromStaticMethodService() * If you want to be able to request this service from the container directly, * make it public, otherwise you might end up with broken code. * - * @return \ConfClass A ConfClass instance. + * @return \ConfClass A ConfClass instance */ protected function getConfiguratorServiceService() { @@ -345,7 +345,7 @@ protected function getConfiguratorServiceService() * If you want to be able to request this service from the container directly, * make it public, otherwise you might end up with broken code. * - * @return \Bar A Bar instance. + * @return \Bar A Bar instance */ protected function getInlinedService() { @@ -367,7 +367,7 @@ protected function getInlinedService() * If you want to be able to request this service from the container directly, * make it public, otherwise you might end up with broken code. * - * @return \FactoryClass A FactoryClass instance. + * @return \FactoryClass A FactoryClass instance */ protected function getNewFactoryService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.php index c616432bacc53..b774c0db91df5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.php @@ -69,7 +69,7 @@ public function compile() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getBarService() { @@ -88,7 +88,7 @@ protected function getBarService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Baz A Baz instance. + * @return \Baz A Baz instance */ protected function getBazService() { @@ -105,7 +105,7 @@ protected function getBazService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getConfiguredServiceService() { @@ -125,7 +125,7 @@ protected function getConfiguredServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getDecoratorServiceService() { @@ -138,7 +138,7 @@ protected function getDecoratorServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance */ protected function getDecoratorServiceWithNameService() { @@ -151,7 +151,7 @@ protected function getDecoratorServiceWithNameService() * This service is shared. * This method always returns the same instance of the service. * - * @return \stdClass A stdClass instance. + * @return \stdClass A stdClass instance * * @deprecated The "deprecated_service" service is deprecated. You should stop using it, as it will soon be removed. */ @@ -168,7 +168,7 @@ protected function getDeprecatedServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar A Bar instance. + * @return \Bar A Bar instance */ protected function getFactoryServiceService() { @@ -181,7 +181,7 @@ protected function getFactoryServiceService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getFooService() { @@ -205,7 +205,7 @@ protected function getFooService() * This service is shared. * This method always returns the same instance of the service. * - * @return \BazClass A BazClass instance. + * @return \BazClass A BazClass instance */ protected function getFoo_BazService() { @@ -219,7 +219,7 @@ protected function getFoo_BazService() /** * Gets the 'foo_bar' service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getFooBarService() { @@ -232,7 +232,7 @@ protected function getFooBarService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Foo A Foo instance. + * @return \Foo A Foo instance */ protected function getFooWithInlineService() { @@ -254,7 +254,7 @@ protected function getFooWithInlineService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getMethodCall1Service() { @@ -275,7 +275,7 @@ protected function getMethodCall1Service() * This service is shared. * This method always returns the same instance of the service. * - * @return \FooBarBaz A FooBarBaz instance. + * @return \FooBarBaz A FooBarBaz instance */ protected function getNewFactoryServiceService() { @@ -308,7 +308,7 @@ protected function getRequestService() * This service is shared. * This method always returns the same instance of the service. * - * @return \Bar\FooClass A Bar\FooClass instance. + * @return \Bar\FooClass A Bar\FooClass instance */ protected function getServiceFromStaticMethodService() { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php index 5d7b3f0fac1e9..7322298a79a50 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php @@ -84,6 +84,19 @@ public function testParseFile() $this->assertInstanceOf('DOMDocument', $xml, '->parseFileToDOM() returns an SimpleXMLElement object'); } + public function testLoadWithExternalEntitiesDisabled() + { + $disableEntities = libxml_disable_entity_loader(true); + + $containerBuilder = new ContainerBuilder(); + $loader = new XmlFileLoader($containerBuilder, new FileLocator(self::$fixturesPath.'/xml')); + $loader->load('services2.xml'); + + libxml_disable_entity_loader($disableEntities); + + $this->assertTrue(count($containerBuilder->getParameterBag()->all()) > 0, 'Parameters can be read from the config file.'); + } + public function testLoadParameters() { $container = new ContainerBuilder(); diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 69135301d444f..9e8b0cbc038ff 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -320,7 +320,7 @@ public function serialize() * * @param int $position The position * - * @return Crawler A new instance of the Crawler with the selected node, or an empty Crawler if it does not exist. + * @return Crawler A new instance of the Crawler with the selected node, or an empty Crawler if it does not exist */ public function eq($position) { @@ -379,7 +379,7 @@ public function slice($offset = 0, $length = -1) * * @param \Closure $closure An anonymous function * - * @return Crawler A Crawler instance with the selected nodes. + * @return Crawler A Crawler instance with the selected nodes */ public function reduce(\Closure $closure) { diff --git a/src/Symfony/Component/DomCrawler/Form.php b/src/Symfony/Component/DomCrawler/Form.php index c9c3c139b112b..0390e3fc7831a 100644 --- a/src/Symfony/Component/DomCrawler/Form.php +++ b/src/Symfony/Component/DomCrawler/Form.php @@ -85,7 +85,7 @@ public function setValues(array $values) * * The returned array does not include file fields (@see getFiles). * - * @return array An array of field values. + * @return array An array of field values */ public function getValues() { @@ -106,7 +106,7 @@ public function getValues() /** * Gets the file field values. * - * @return array An array of file field values. + * @return array An array of file field values */ public function getFiles() { @@ -135,7 +135,7 @@ public function getFiles() * This method converts fields with the array notation * (like foo[bar] to arrays) like PHP does. * - * @return array An array of field values. + * @return array An array of field values */ public function getPhpValues() { @@ -162,7 +162,7 @@ public function getPhpValues() * For a compound file field foo[bar] it will create foo[bar][name], * instead of foo[name][bar] which would be found in $_FILES. * - * @return array An array of file field values. + * @return array An array of file field values */ public function getPhpFiles() { @@ -246,8 +246,6 @@ public function has($name) * Removes a field from the form. * * @param string $name The field name - * - * @throws \InvalidArgumentException when the name is malformed */ public function remove($name) { diff --git a/src/Symfony/Component/DomCrawler/FormFieldRegistry.php b/src/Symfony/Component/DomCrawler/FormFieldRegistry.php index edb2788910de2..dbd08ff720765 100644 --- a/src/Symfony/Component/DomCrawler/FormFieldRegistry.php +++ b/src/Symfony/Component/DomCrawler/FormFieldRegistry.php @@ -26,8 +26,6 @@ class FormFieldRegistry * Adds a field to the registry. * * @param FormField $field The field - * - * @throws \InvalidArgumentException when the name is malformed */ public function add(FormField $field) { @@ -52,8 +50,6 @@ public function add(FormField $field) * Removes a field and its children from the registry. * * @param string $name The fully qualified name of the base field - * - * @throws \InvalidArgumentException when the name is malformed */ public function remove($name) { @@ -76,7 +72,6 @@ public function remove($name) * * @return mixed The value of the field * - * @throws \InvalidArgumentException when the name is malformed * @throws \InvalidArgumentException if the field does not exist */ public function &get($name) @@ -118,7 +113,6 @@ public function has($name) * @param string $name The fully qualified name of the field * @param mixed $value The value * - * @throws \InvalidArgumentException when the name is malformed * @throws \InvalidArgumentException if the field does not exist */ public function set($name, $value) @@ -199,24 +193,23 @@ private function walk(array $array, $base = '', array &$output = array()) * @param string $name The name of the field * * @return string[] The list of segments - * - * @throws \InvalidArgumentException when the name is malformed */ private function getSegments($name) { if (preg_match('/^(?P[^[]+)(?P(\[.*)|$)/', $name, $m)) { $segments = array($m['base']); while (!empty($m['extra'])) { - if (preg_match('/^\[(?P.*?)\](?P.*)$/', $m['extra'], $m)) { + $extra = $m['extra']; + if (preg_match('/^\[(?P.*?)\](?P.*)$/', $extra, $m)) { $segments[] = $m['segment']; } else { - throw new \InvalidArgumentException(sprintf('Malformed field path "%s"', $name)); + $segments[] = $extra; } } return $segments; } - throw new \InvalidArgumentException(sprintf('Malformed field path "%s"', $name)); + return array($name); } } diff --git a/src/Symfony/Component/DomCrawler/Tests/FormTest.php b/src/Symfony/Component/DomCrawler/Tests/FormTest.php index 5bfbfb98245dc..3035e8d371d96 100644 --- a/src/Symfony/Component/DomCrawler/Tests/FormTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/FormTest.php @@ -345,18 +345,6 @@ public function testGetSetValue() } } - public function testSetValueOnMultiValuedFieldsWithMalformedName() - { - $form = $this->createForm('
'); - - try { - $form['foo[bar'] = 'bar'; - $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the name is malformed.'); - } catch (\InvalidArgumentException $e) { - $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the name is malformed.'); - } - } - public function testDisableValidation() { $form = $this->createForm('
@@ -681,31 +669,19 @@ public function testTypeAttributeIsCaseInsensitive() $this->assertTrue($form->has('example.y'), '->has() returns true if the image input was correctly turned into an x and a y fields'); } - /** - * @expectedException \InvalidArgumentException - */ - public function testFormFieldRegistryAddThrowAnExceptionWhenTheNameIsMalformed() + public function testFormFieldRegistryAcceptAnyNames() { - $registry = new FormFieldRegistry(); - $registry->add($this->getFormFieldMock('[foo]')); - } + $field = $this->getFormFieldMock('[t:dbt%3adate;]data_daterange_enddate_value'); - /** - * @expectedException \InvalidArgumentException - */ - public function testFormFieldRegistryRemoveThrowAnExceptionWhenTheNameIsMalformed() - { $registry = new FormFieldRegistry(); - $registry->remove('[foo]'); - } + $registry->add($field); + $this->assertEquals($field, $registry->get('[t:dbt%3adate;]data_daterange_enddate_value')); + $registry->set('[t:dbt%3adate;]data_daterange_enddate_value', null); - /** - * @expectedException \InvalidArgumentException - */ - public function testFormFieldRegistryGetThrowAnExceptionWhenTheNameIsMalformed() - { - $registry = new FormFieldRegistry(); - $registry->get('[foo]'); + $form = $this->createForm('
'); + $form['[t:dbt%3adate;]data_daterange_enddate_value'] = 'bar'; + + $registry->remove('[t:dbt%3adate;]data_daterange_enddate_value'); } /** @@ -717,15 +693,6 @@ public function testFormFieldRegistryGetThrowAnExceptionWhenTheFieldDoesNotExist $registry->get('foo'); } - /** - * @expectedException \InvalidArgumentException - */ - public function testFormFieldRegistrySetThrowAnExceptionWhenTheNameIsMalformed() - { - $registry = new FormFieldRegistry(); - $registry->set('[foo]', null); - } - /** * @expectedException \InvalidArgumentException */ diff --git a/src/Symfony/Component/EventDispatcher/Event.php b/src/Symfony/Component/EventDispatcher/Event.php index 4a563495e3a22..956f7264528c5 100644 --- a/src/Symfony/Component/EventDispatcher/Event.php +++ b/src/Symfony/Component/EventDispatcher/Event.php @@ -47,7 +47,7 @@ class Event * * @see Event::stopPropagation() * - * @return bool Whether propagation was already stopped for this event. + * @return bool Whether propagation was already stopped for this event */ public function isPropagationStopped() { @@ -109,7 +109,7 @@ public function getName() /** * Sets the event's name property. * - * @param string $name The event name. + * @param string $name The event name * * @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call. */ diff --git a/src/Symfony/Component/EventDispatcher/EventDispatcher.php b/src/Symfony/Component/EventDispatcher/EventDispatcher.php index d4c5cdf58c652..f19ba1d24596f 100644 --- a/src/Symfony/Component/EventDispatcher/EventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/EventDispatcher.php @@ -171,9 +171,9 @@ public function removeSubscriber(EventSubscriberInterface $subscriber) * This method can be overridden to add functionality that is executed * for each listener. * - * @param callable[] $listeners The event listeners. - * @param string $eventName The name of the event to dispatch. - * @param Event $event The event object to pass to the event handlers/listeners. + * @param callable[] $listeners The event listeners + * @param string $eventName The name of the event to dispatch + * @param Event $event The event object to pass to the event handlers/listeners */ protected function doDispatch($listeners, $eventName, Event $event) { @@ -188,7 +188,7 @@ protected function doDispatch($listeners, $eventName, Event $event) /** * Sorts the internal list of listeners for the given event by priority. * - * @param string $eventName The name of the event. + * @param string $eventName The name of the event */ private function sortListeners($eventName) { diff --git a/src/Symfony/Component/EventDispatcher/EventDispatcherInterface.php b/src/Symfony/Component/EventDispatcher/EventDispatcherInterface.php index a9bdd2c8867ac..abe8d2895ebc3 100644 --- a/src/Symfony/Component/EventDispatcher/EventDispatcherInterface.php +++ b/src/Symfony/Component/EventDispatcher/EventDispatcherInterface.php @@ -26,7 +26,7 @@ interface EventDispatcherInterface * @param string $eventName The name of the event to dispatch. The name of * the event is the name of the method that is * invoked on listeners. - * @param Event $event The event to pass to the event handlers/listeners. + * @param Event $event The event to pass to the event handlers/listeners * If not supplied, an empty Event instance is created. * * @return Event @@ -49,7 +49,7 @@ public function addListener($eventName, $listener, $priority = 0); * The subscriber is asked for all the events he is * interested in and added as a listener for these events. * - * @param EventSubscriberInterface $subscriber The subscriber. + * @param EventSubscriberInterface $subscriber The subscriber */ public function addSubscriber(EventSubscriberInterface $subscriber); diff --git a/src/Symfony/Component/EventDispatcher/GenericEvent.php b/src/Symfony/Component/EventDispatcher/GenericEvent.php index 03cbcfe33414e..2b9f40e26ad2b 100644 --- a/src/Symfony/Component/EventDispatcher/GenericEvent.php +++ b/src/Symfony/Component/EventDispatcher/GenericEvent.php @@ -37,8 +37,8 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate /** * Encapsulate an event with $subject and $args. * - * @param mixed $subject The subject of the event, usually an object. - * @param array $arguments Arguments to store in the event. + * @param mixed $subject The subject of the event, usually an object + * @param array $arguments Arguments to store in the event */ public function __construct($subject = null, array $arguments = array()) { @@ -49,7 +49,7 @@ public function __construct($subject = null, array $arguments = array()) /** * Getter for subject property. * - * @return mixed $subject The observer subject. + * @return mixed $subject The observer subject */ public function getSubject() { @@ -59,9 +59,9 @@ public function getSubject() /** * Get argument by key. * - * @param string $key Key. + * @param string $key Key * - * @return mixed Contents of array key. + * @return mixed Contents of array key * * @throws \InvalidArgumentException If key is not found. */ @@ -77,8 +77,8 @@ public function getArgument($key) /** * Add argument to event. * - * @param string $key Argument name. - * @param mixed $value Value. + * @param string $key Argument name + * @param mixed $value Value * * @return GenericEvent */ @@ -102,7 +102,7 @@ public function getArguments() /** * Set args property. * - * @param array $args Arguments. + * @param array $args Arguments * * @return GenericEvent */ @@ -116,7 +116,7 @@ public function setArguments(array $args = array()) /** * Has argument. * - * @param string $key Key of arguments array. + * @param string $key Key of arguments array * * @return bool */ @@ -128,7 +128,7 @@ public function hasArgument($key) /** * ArrayAccess for argument getter. * - * @param string $key Array key. + * @param string $key Array key * * @return mixed * @@ -142,8 +142,8 @@ public function offsetGet($key) /** * ArrayAccess for argument setter. * - * @param string $key Array key to set. - * @param mixed $value Value. + * @param string $key Array key to set + * @param mixed $value Value */ public function offsetSet($key, $value) { @@ -153,7 +153,7 @@ public function offsetSet($key, $value) /** * ArrayAccess for unset argument. * - * @param string $key Array key. + * @param string $key Array key */ public function offsetUnset($key) { @@ -165,7 +165,7 @@ public function offsetUnset($key) /** * ArrayAccess has argument. * - * @param string $key Array key. + * @param string $key Array key * * @return bool */ diff --git a/src/Symfony/Component/EventDispatcher/ImmutableEventDispatcher.php b/src/Symfony/Component/EventDispatcher/ImmutableEventDispatcher.php index 13e8572ed6492..7f2be8d3145d6 100644 --- a/src/Symfony/Component/EventDispatcher/ImmutableEventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/ImmutableEventDispatcher.php @@ -28,7 +28,7 @@ class ImmutableEventDispatcher implements EventDispatcherInterface /** * Creates an unmodifiable proxy for an event dispatcher. * - * @param EventDispatcherInterface $dispatcher The proxied event dispatcher. + * @param EventDispatcherInterface $dispatcher The proxied event dispatcher */ public function __construct(EventDispatcherInterface $dispatcher) { diff --git a/src/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php b/src/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php index 35350587633d0..c11965a4247ee 100644 --- a/src/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php +++ b/src/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php @@ -21,7 +21,7 @@ interface IOExceptionInterface extends ExceptionInterface /** * Returns the associated path for the exception. * - * @return string The path. + * @return string The path */ public function getPath(); } diff --git a/src/Symfony/Component/Filesystem/Filesystem.php b/src/Symfony/Component/Filesystem/Filesystem.php index f7e3b96b462cc..7390783de6e5a 100644 --- a/src/Symfony/Component/Filesystem/Filesystem.php +++ b/src/Symfony/Component/Filesystem/Filesystem.php @@ -283,7 +283,7 @@ public function rename($origin, $target, $overwrite = false) /** * Tells whether a file exists and is readable. * - * @param string $filename Path to the file. + * @param string $filename Path to the file * * @throws IOException When windows path is longer than 258 characters */ @@ -479,11 +479,11 @@ public function isAbsolutePath($file) /** * Creates a temporary file with support for custom stream wrappers. * - * @param string $dir The directory where the temporary filename will be created. - * @param string $prefix The prefix of the generated temporary filename. - * Note: Windows uses only the first three characters of prefix. + * @param string $dir The directory where the temporary filename will be created + * @param string $prefix The prefix of the generated temporary filename + * Note: Windows uses only the first three characters of prefix * - * @return string The new temporary filename (with path), or throw an exception on failure. + * @return string The new temporary filename (with path), or throw an exception on failure */ public function tempnam($dir, $prefix) { @@ -531,8 +531,8 @@ public function tempnam($dir, $prefix) /** * Atomically dumps content into a file. * - * @param string $filename The file to be written to. - * @param string $content The data to write into the file. + * @param string $filename The file to be written to + * @param string $content The data to write into the file * @param null|int $mode The file mode (octal). If null, file permissions are not modified * Deprecated since version 2.3.12, to be removed in 3.0. * @@ -581,7 +581,7 @@ private function toIterator($files) /** * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)). * - * @param string $filename The filename to be parsed. + * @param string $filename The filename to be parsed * * @return array The filename scheme and hierarchical part */ diff --git a/src/Symfony/Component/Finder/Finder.php b/src/Symfony/Component/Finder/Finder.php index 9574f10d7ed8d..7bfe3455a41ea 100644 --- a/src/Symfony/Component/Finder/Finder.php +++ b/src/Symfony/Component/Finder/Finder.php @@ -667,7 +667,7 @@ public function in($dirs) * * This method implements the IteratorAggregate interface. * - * @return \Iterator An iterator + * @return \Iterator|SplFileInfo[] An iterator * * @throws \LogicException if the in() method has not been called */ diff --git a/src/Symfony/Component/Finder/Iterator/PathFilterIterator.php b/src/Symfony/Component/Finder/Iterator/PathFilterIterator.php index e9b3a2a5fe21d..dadfc8ed7f286 100644 --- a/src/Symfony/Component/Finder/Iterator/PathFilterIterator.php +++ b/src/Symfony/Component/Finder/Iterator/PathFilterIterator.php @@ -45,7 +45,7 @@ public function accept() * * Use only / as directory separator (on Windows also). * - * @param string $str Pattern: regexp or dirname. + * @param string $str Pattern: regexp or dirname * * @return string regexp corresponding to a given string or regexp */ diff --git a/src/Symfony/Component/Form/AbstractRendererEngine.php b/src/Symfony/Component/Form/AbstractRendererEngine.php index 8202cbf97b641..ae9938a0f004c 100644 --- a/src/Symfony/Component/Form/AbstractRendererEngine.php +++ b/src/Symfony/Component/Form/AbstractRendererEngine.php @@ -126,11 +126,11 @@ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierar * * @see getResourceForBlock() * - * @param string $cacheKey The cache key of the form view. - * @param FormView $view The form view for finding the applying themes. - * @param string $blockName The name of the block to load. + * @param string $cacheKey The cache key of the form view + * @param FormView $view The form view for finding the applying themes + * @param string $blockName The name of the block to load * - * @return bool True if the resource could be loaded, false otherwise. + * @return bool True if the resource could be loaded, false otherwise */ abstract protected function loadResourceForBlockName($cacheKey, FormView $view, $blockName); @@ -148,7 +148,7 @@ abstract protected function loadResourceForBlockName($cacheKey, FormView $view, * @param int $hierarchyLevel The level in the block hierarchy that * should be loaded. * - * @return bool True if the resource could be loaded, false otherwise. + * @return bool True if the resource could be loaded, false otherwise */ private function loadResourceForBlockNameHierarchy($cacheKey, FormView $view, array $blockNameHierarchy, $hierarchyLevel) { diff --git a/src/Symfony/Component/Form/AbstractType.php b/src/Symfony/Component/Form/AbstractType.php index 1c56677c05c15..ac0add2b8e557 100644 --- a/src/Symfony/Component/Form/AbstractType.php +++ b/src/Symfony/Component/Form/AbstractType.php @@ -56,7 +56,7 @@ public function setDefaultOptions(OptionsResolverInterface $resolver) /** * Configures the options for this type. * - * @param OptionsResolver $resolver The resolver for the options. + * @param OptionsResolver $resolver The resolver for the options */ public function configureOptions(OptionsResolver $resolver) { diff --git a/src/Symfony/Component/Form/AbstractTypeExtension.php b/src/Symfony/Component/Form/AbstractTypeExtension.php index 666f292c9156a..27783a1a4d508 100644 --- a/src/Symfony/Component/Form/AbstractTypeExtension.php +++ b/src/Symfony/Component/Form/AbstractTypeExtension.php @@ -55,7 +55,7 @@ public function setDefaultOptions(OptionsResolverInterface $resolver) /** * Configures the options for this type. * - * @param OptionsResolver $resolver The resolver for the options. + * @param OptionsResolver $resolver The resolver for the options */ public function configureOptions(OptionsResolver $resolver) { diff --git a/src/Symfony/Component/Form/Button.php b/src/Symfony/Component/Form/Button.php index 1fa5ec25a7925..6ceaed278e866 100644 --- a/src/Symfony/Component/Form/Button.php +++ b/src/Symfony/Component/Form/Button.php @@ -39,7 +39,7 @@ class Button implements \IteratorAggregate, FormInterface /** * Creates a new button from a form configuration. * - * @param FormConfigInterface $config The button's configuration. + * @param FormConfigInterface $config The button's configuration */ public function __construct(FormConfigInterface $config) { @@ -51,7 +51,7 @@ public function __construct(FormConfigInterface $config) * * @param mixed $offset * - * @return bool Always returns false. + * @return bool Always returns false */ public function offsetExists($offset) { @@ -152,7 +152,7 @@ public function get($name) * * @param string $name * - * @return bool Always returns false. + * @return bool Always returns false */ public function has($name) { @@ -226,7 +226,7 @@ public function getViewData() /** * Unsupported method. * - * @return array Always returns an empty array. + * @return array Always returns an empty array */ public function getExtraData() { @@ -236,7 +236,7 @@ public function getExtraData() /** * Returns the button's configuration. * - * @return FormConfigInterface The configuration. + * @return FormConfigInterface The configuration */ public function getConfig() { @@ -246,7 +246,7 @@ public function getConfig() /** * Returns whether the button is submitted. * - * @return bool true if the button was submitted. + * @return bool true if the button was submitted */ public function isSubmitted() { @@ -256,7 +256,7 @@ public function isSubmitted() /** * Returns the name by which the button is identified in forms. * - * @return string The name of the button. + * @return string The name of the button */ public function getName() { @@ -285,7 +285,7 @@ public function addError(FormError $error) /** * Unsupported method. * - * @return bool Always returns true. + * @return bool Always returns true */ public function isValid() { @@ -295,7 +295,7 @@ public function isValid() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function isRequired() { @@ -317,7 +317,7 @@ public function isDisabled() /** * Unsupported method. * - * @return bool Always returns true. + * @return bool Always returns true */ public function isEmpty() { @@ -327,7 +327,7 @@ public function isEmpty() /** * Unsupported method. * - * @return bool Always returns true. + * @return bool Always returns true */ public function isSynchronized() { @@ -366,8 +366,8 @@ public function handleRequest($request = null) /** * Submits data to the button. * - * @param null|string $submittedData The data. - * @param bool $clearMissing Not used. + * @param null|string $submittedData The data + * @param bool $clearMissing Not used * * @return Button The button instance * @@ -423,7 +423,7 @@ public function createView(FormView $parent = null) /** * Unsupported method. * - * @return int Always returns 0. + * @return int Always returns 0 */ public function count() { @@ -433,7 +433,7 @@ public function count() /** * Unsupported method. * - * @return \EmptyIterator Always returns an empty iterator. + * @return \EmptyIterator Always returns an empty iterator */ public function getIterator() { diff --git a/src/Symfony/Component/Form/ButtonBuilder.php b/src/Symfony/Component/Form/ButtonBuilder.php index b34b4bb863506..1eaed6a826292 100644 --- a/src/Symfony/Component/Form/ButtonBuilder.php +++ b/src/Symfony/Component/Form/ButtonBuilder.php @@ -55,8 +55,8 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface /** * Creates a new button builder. * - * @param string $name The name of the button. - * @param array $options The button's options. + * @param string $name The name of the button + * @param array $options The button's options * * @throws InvalidArgumentException If the name is empty. */ @@ -135,7 +135,7 @@ public function remove($name) * * @param string $name * - * @return bool Always returns false. + * @return bool Always returns false */ public function has($name) { @@ -145,7 +145,7 @@ public function has($name) /** * Returns the children. * - * @return array Always returns an empty array. + * @return array Always returns an empty array */ public function all() { @@ -285,7 +285,7 @@ public function setDataMapper(DataMapperInterface $dataMapper = null) * * @param bool $disabled Whether the button is disabled * - * @return ButtonBuilder The button builder. + * @return ButtonBuilder The button builder */ public function setDisabled($disabled) { @@ -412,9 +412,9 @@ public function setCompound($compound) /** * Sets the type of the button. * - * @param ResolvedFormTypeInterface $type The type of the button. + * @param ResolvedFormTypeInterface $type The type of the button * - * @return ButtonBuilder The button builder. + * @return ButtonBuilder The button builder */ public function setType(ResolvedFormTypeInterface $type) { @@ -570,7 +570,7 @@ public function getPropertyPath() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getMapped() { @@ -580,7 +580,7 @@ public function getMapped() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getByReference() { @@ -590,7 +590,7 @@ public function getByReference() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false * * @deprecated since version 2.3, to be removed in 3.0. * Use {@link getInheritData()} instead. @@ -605,7 +605,7 @@ public function getVirtual() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getCompound() { @@ -615,7 +615,7 @@ public function getCompound() /** * Returns the form type used to construct the button. * - * @return ResolvedFormTypeInterface The button's type. + * @return ResolvedFormTypeInterface The button's type */ public function getType() { @@ -625,7 +625,7 @@ public function getType() /** * Unsupported method. * - * @return array Always returns an empty array. + * @return array Always returns an empty array */ public function getViewTransformers() { @@ -635,7 +635,7 @@ public function getViewTransformers() /** * Unsupported method. * - * @return array Always returns an empty array. + * @return array Always returns an empty array */ public function getModelTransformers() { @@ -652,7 +652,7 @@ public function getDataMapper() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getRequired() { @@ -662,7 +662,7 @@ public function getRequired() /** * Returns whether the button is disabled. * - * @return bool Whether the button is disabled. + * @return bool Whether the button is disabled */ public function getDisabled() { @@ -672,7 +672,7 @@ public function getDisabled() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getErrorBubbling() { @@ -689,7 +689,7 @@ public function getEmptyData() /** * Returns additional attributes of the button. * - * @return array An array of key-value combinations. + * @return array An array of key-value combinations */ public function getAttributes() { @@ -699,9 +699,9 @@ public function getAttributes() /** * Returns whether the attribute with the given name exists. * - * @param string $name The attribute name. + * @param string $name The attribute name * - * @return bool Whether the attribute exists. + * @return bool Whether the attribute exists */ public function hasAttribute($name) { @@ -711,10 +711,10 @@ public function hasAttribute($name) /** * Returns the value of the given attribute. * - * @param string $name The attribute name. - * @param mixed $default The value returned if the attribute does not exist. + * @param string $name The attribute name + * @param mixed $default The value returned if the attribute does not exist * - * @return mixed The attribute value. + * @return mixed The attribute value */ public function getAttribute($name, $default = null) { @@ -738,7 +738,7 @@ public function getDataClass() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getDataLocked() { @@ -776,7 +776,7 @@ public function getRequestHandler() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getAutoInitialize() { @@ -786,7 +786,7 @@ public function getAutoInitialize() /** * Unsupported method. * - * @return bool Always returns false. + * @return bool Always returns false */ public function getInheritData() { @@ -796,7 +796,7 @@ public function getInheritData() /** * Returns all options passed during the construction of the button. * - * @return array The passed options. + * @return array The passed options */ public function getOptions() { @@ -808,7 +808,7 @@ public function getOptions() * * @param string $name The option name, * - * @return bool Whether the option exists. + * @return bool Whether the option exists */ public function hasOption($name) { @@ -818,10 +818,10 @@ public function hasOption($name) /** * Returns the value of a specific option. * - * @param string $name The option name. - * @param mixed $default The value returned if the option does not exist. + * @param string $name The option name + * @param mixed $default The value returned if the option does not exist * - * @return mixed The option value. + * @return mixed The option value */ public function getOption($name, $default = null) { @@ -831,7 +831,7 @@ public function getOption($name, $default = null) /** * Unsupported method. * - * @return int Always returns 0. + * @return int Always returns 0 */ public function count() { @@ -841,7 +841,7 @@ public function count() /** * Unsupported method. * - * @return \EmptyIterator Always returns an empty iterator. + * @return \EmptyIterator Always returns an empty iterator */ public function getIterator() { diff --git a/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php b/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php index b89d7b324c622..82ebe7421d9e7 100644 --- a/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php +++ b/src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php @@ -218,7 +218,7 @@ protected function flatten(array $choices, $value, &$choicesByValues, &$keysByVa * Checks whether the given choices can be cast to strings without * generating duplicates. * - * @param array $choices The choices. + * @param array $choices The choices * @param array|null $cache The cache for previously checked entries. Internal * * @return bool Returns true if the choices can be cast to strings and diff --git a/src/Symfony/Component/Form/ChoiceList/View/ChoiceGroupView.php b/src/Symfony/Component/Form/ChoiceList/View/ChoiceGroupView.php index 05d753330626f..9e648cc360000 100644 --- a/src/Symfony/Component/Form/ChoiceList/View/ChoiceGroupView.php +++ b/src/Symfony/Component/Form/ChoiceList/View/ChoiceGroupView.php @@ -35,7 +35,7 @@ class ChoiceGroupView implements \IteratorAggregate /** * Creates a new choice group view. * - * @param string $label The label of the group. + * @param string $label The label of the group * @param ChoiceGroupView[]|ChoiceView[] $choices The choice views in the * group. */ @@ -47,6 +47,8 @@ public function __construct($label, array $choices = array()) /** * {@inheritdoc} + * + * @return ChoiceGroupView[]|ChoiceView[] */ public function getIterator() { diff --git a/src/Symfony/Component/Form/ChoiceList/View/ChoiceListView.php b/src/Symfony/Component/Form/ChoiceList/View/ChoiceListView.php index 99308b826f7a5..cea30dd655559 100644 --- a/src/Symfony/Component/Form/ChoiceList/View/ChoiceListView.php +++ b/src/Symfony/Component/Form/ChoiceList/View/ChoiceListView.php @@ -39,7 +39,7 @@ class ChoiceListView /** * Creates a new choice list view. * - * @param ChoiceGroupView[]|ChoiceView[] $choices The choice views. + * @param ChoiceGroupView[]|ChoiceView[] $choices The choice views * @param ChoiceGroupView[]|ChoiceView[] $preferredChoices The preferred * choice views. */ diff --git a/src/Symfony/Component/Form/ChoiceList/View/ChoiceView.php b/src/Symfony/Component/Form/ChoiceList/View/ChoiceView.php index 6e79d413cc019..5078de789aa65 100644 --- a/src/Symfony/Component/Form/ChoiceList/View/ChoiceView.php +++ b/src/Symfony/Component/Form/ChoiceList/View/ChoiceView.php @@ -45,9 +45,9 @@ class ChoiceView /** * Creates a new ChoiceView. * - * @param mixed $data The original choice. - * @param string $value The view representation of the choice. - * @param string $label The label displayed to humans. + * @param mixed $data The original choice + * @param string $value The view representation of the choice + * @param string $label The label displayed to humans */ public function __construct($data, $value, $label) { diff --git a/src/Symfony/Component/Form/ClickableInterface.php b/src/Symfony/Component/Form/ClickableInterface.php index 6e45eff1a7f1a..541ef879d647e 100644 --- a/src/Symfony/Component/Form/ClickableInterface.php +++ b/src/Symfony/Component/Form/ClickableInterface.php @@ -21,7 +21,7 @@ interface ClickableInterface /** * Returns whether this element was clicked. * - * @return bool Whether this element was clicked. + * @return bool Whether this element was clicked */ public function isClicked(); } diff --git a/src/Symfony/Component/Form/DataMapperInterface.php b/src/Symfony/Component/Form/DataMapperInterface.php index 6e0316829152d..779f15383592d 100644 --- a/src/Symfony/Component/Form/DataMapperInterface.php +++ b/src/Symfony/Component/Form/DataMapperInterface.php @@ -19,8 +19,8 @@ interface DataMapperInterface /** * Maps properties of some data to a list of forms. * - * @param mixed $data Structured data. - * @param FormInterface[] $forms A list of {@link FormInterface} instances. + * @param mixed $data Structured data + * @param FormInterface[] $forms A list of {@link FormInterface} instances * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported. */ @@ -29,8 +29,8 @@ public function mapDataToForms($data, $forms); /** * Maps the data of a list of forms into the properties of some data. * - * @param FormInterface[] $forms A list of {@link FormInterface} instances. - * @param mixed $data Structured data. + * @param FormInterface[] $forms A list of {@link FormInterface} instances + * @param mixed $data Structured data * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported. */ diff --git a/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php b/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php index b77f4d4e75495..90e5d774e72e5 100644 --- a/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php +++ b/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php @@ -101,9 +101,9 @@ public function __construct($choices, array $labels, array $preferredChoices = a * * Safe to be called multiple times. The list is cleared on every call. * - * @param array|\Traversable $choices The choices to write into the list. - * @param array $labels The labels belonging to the choices. - * @param array $preferredChoices The choices to display with priority. + * @param array|\Traversable $choices The choices to write into the list + * @param array $labels The labels belonging to the choices + * @param array $preferredChoices The choices to display with priority */ protected function initialize($choices, array $labels, array $preferredChoices) { @@ -264,9 +264,9 @@ public function getIndicesForValues(array $values) * view objects. * @param array $bucketForRemaining The bucket where to store the * non-preferred view objects. - * @param array|\Traversable $choices The list of choices. - * @param array $labels The labels corresponding to the choices. - * @param array $preferredChoices The preferred choices. + * @param array|\Traversable $choices The list of choices + * @param array $labels The labels corresponding to the choices + * @param array $preferredChoices The preferred choices * * @throws InvalidArgumentException If the structures of the choices and labels array do not match. * @throws InvalidConfigurationException If no valid value or index could be created for a choice. @@ -306,14 +306,14 @@ protected function addChoices(array &$bucketForPreferred, array &$bucketForRemai /** * Recursively adds a choice group. * - * @param string $group The name of the group. + * @param string $group The name of the group * @param array $bucketForPreferred The bucket where to store the preferred * view objects. * @param array $bucketForRemaining The bucket where to store the * non-preferred view objects. - * @param array $choices The list of choices in the group. - * @param array $labels The labels corresponding to the choices in the group. - * @param array $preferredChoices The preferred choices. + * @param array $choices The list of choices in the group + * @param array $labels The labels corresponding to the choices in the group + * @param array $preferredChoices The preferred choices * * @throws InvalidConfigurationException If no valid value or index could be created for a choice. */ @@ -348,9 +348,9 @@ protected function addChoiceGroup($group, array &$bucketForPreferred, array &$bu * view objects. * @param array $bucketForRemaining The bucket where to store the * non-preferred view objects. - * @param mixed $choice The choice to add. - * @param string $label The label for the choice. - * @param array $preferredChoices The preferred choices. + * @param mixed $choice The choice to add + * @param string $label The label for the choice + * @param array $preferredChoices The preferred choices * * @throws InvalidConfigurationException If no valid value or index could be created. */ @@ -387,10 +387,10 @@ protected function addChoice(array &$bucketForPreferred, array &$bucketForRemain * Extension point to optimize performance by changing the structure of the * $preferredChoices array. * - * @param mixed $choice The choice to test. - * @param array $preferredChoices An array of preferred choices. + * @param mixed $choice The choice to test + * @param array $preferredChoices An array of preferred choices * - * @return bool Whether the choice is preferred. + * @return bool Whether the choice is preferred */ protected function isPreferred($choice, array $preferredChoices) { @@ -421,7 +421,7 @@ protected function createIndex($choice) * * @param mixed $choice The choice to create a value for * - * @return string A unique string. + * @return string A unique string */ protected function createValue($choice) { @@ -432,9 +432,9 @@ protected function createValue($choice) * Fixes the data type of the given choice value to avoid comparison * problems. * - * @param mixed $value The choice value. + * @param mixed $value The choice value * - * @return string The value as string. + * @return string The value as string */ protected function fixValue($value) { @@ -445,9 +445,9 @@ protected function fixValue($value) * Fixes the data types of the given choice values to avoid comparison * problems. * - * @param array $values The choice values. + * @param array $values The choice values * - * @return array The values as strings. + * @return array The values as strings */ protected function fixValues(array $values) { @@ -462,9 +462,9 @@ protected function fixValues(array $values) * Fixes the data type of the given choice index to avoid comparison * problems. * - * @param mixed $index The choice index. + * @param mixed $index The choice index * - * @return int|string The index as PHP array key. + * @return int|string The index as PHP array key */ protected function fixIndex($index) { @@ -479,9 +479,9 @@ protected function fixIndex($index) * Fixes the data types of the given choice indices to avoid comparison * problems. * - * @param array $indices The choice indices. + * @param array $indices The choice indices * - * @return array The indices as strings. + * @return array The indices as strings */ protected function fixIndices(array $indices) { @@ -510,9 +510,9 @@ protected function fixChoice($choice) /** * Fixes the data type of the given choices to avoid comparison problems. * - * @param array $choices The choices. + * @param array $choices The choices * - * @return array The fixed choices. + * @return array The fixed choices * * @see fixChoice() */ diff --git a/src/Symfony/Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.php b/src/Symfony/Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.php index 65742c45bce50..6460ba81efafa 100644 --- a/src/Symfony/Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.php +++ b/src/Symfony/Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.php @@ -88,7 +88,7 @@ class ObjectChoiceList extends ChoiceList * @param string $valuePath A property path pointing to the property used * for the choice values. If not given, integers * are generated instead. - * @param PropertyAccessorInterface $propertyAccessor The reflection graph for reading property paths. + * @param PropertyAccessorInterface $propertyAccessor The reflection graph for reading property paths */ public function __construct($choices, $labelPath = null, array $preferredChoices = array(), $groupPath = null, $valuePath = null, PropertyAccessorInterface $propertyAccessor = null) { @@ -105,9 +105,9 @@ public function __construct($choices, $labelPath = null, array $preferredChoices * * Safe to be called multiple times. The list is cleared on every call. * - * @param array|\Traversable $choices The choices to write into the list. - * @param array $labels Ignored. - * @param array $preferredChoices The choices to display with priority. + * @param array|\Traversable $choices The choices to write into the list + * @param array $labels Ignored + * @param array $preferredChoices The choices to display with priority * * @throws InvalidArgumentException When passing a hierarchy of choices and using * the "groupPath" option at the same time. @@ -238,7 +238,7 @@ public function getIndicesForChoices(array $choices) * * @param mixed $choice The choice to create a value for * - * @return int|string A unique value without character limitations. + * @return int|string A unique value without character limitations */ protected function createValue($choice) { diff --git a/src/Symfony/Component/Form/Extension/Core/ChoiceList/SimpleChoiceList.php b/src/Symfony/Component/Form/Extension/Core/ChoiceList/SimpleChoiceList.php index 90cc4ac0236e1..537e318f80dbf 100644 --- a/src/Symfony/Component/Form/Extension/Core/ChoiceList/SimpleChoiceList.php +++ b/src/Symfony/Component/Form/Extension/Core/ChoiceList/SimpleChoiceList.php @@ -87,9 +87,9 @@ public function getValuesForChoices(array $choices) * view objects. * @param array $bucketForRemaining The bucket where to store the * non-preferred view objects. - * @param array|\Traversable $choices The list of choices. - * @param array $labels Ignored. - * @param array $preferredChoices The preferred choices. + * @param array|\Traversable $choices The list of choices + * @param array $labels Ignored + * @param array $preferredChoices The preferred choices */ protected function addChoices(array &$bucketForPreferred, array &$bucketForRemaining, $choices, array $labels, array $preferredChoices) { @@ -126,10 +126,10 @@ protected function addChoices(array &$bucketForPreferred, array &$bucketForRemai * Optimized for performance by treating the preferred choices as array * where choices are stored in the keys. * - * @param mixed $choice The choice to test. - * @param array $preferredChoices An array of preferred choices. + * @param mixed $choice The choice to test + * @param array $preferredChoices An array of preferred choices * - * @return bool Whether the choice is preferred. + * @return bool Whether the choice is preferred */ protected function isPreferred($choice, array $preferredChoices) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/BooleanToStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/BooleanToStringTransformer.php index b75b98914dfea..5d3e5eaf051c2 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/BooleanToStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/BooleanToStringTransformer.php @@ -42,9 +42,9 @@ public function __construct($trueValue) /** * Transforms a Boolean into a string. * - * @param bool $value Boolean value. + * @param bool $value Boolean value * - * @return string String value. + * @return string String value * * @throws TransformationFailedException If the given value is not a Boolean. */ @@ -64,9 +64,9 @@ public function transform($value) /** * Transforms a string into a Boolean. * - * @param string $value String value. + * @param string $value String value * - * @return bool Boolean value. + * @return bool Boolean value * * @throws TransformationFailedException If the given value is not a string. */ diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index 07070952f5065..24479fb0163dd 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -53,11 +53,10 @@ public function __construct($inputTimezone = null, $outputTimezone = null, array * * @param \DateTime|\DateTimeInterface $dateTime A DateTime object * - * @return array Localized date. + * @return array Localized date * * @throws TransformationFailedException If the given value is not an - * instance of \DateTime or if the - * output timezone is not supported. + * instance of \DateTime or \DateTimeInterface */ public function transform($dateTime) { @@ -81,11 +80,7 @@ public function transform($dateTime) $dateTime = clone $dateTime; } - try { - $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); - } catch (\Exception $e) { - throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); - } + $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } $result = array_intersect_key(array( @@ -118,8 +113,6 @@ public function transform($dateTime) * * @throws TransformationFailedException If the given value is not an array, * if the value could not be transformed - * or if the input timezone is not - * supported. */ public function reverseTransform($value) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 5418f7feae919..cac50e16c7a0a 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -72,11 +72,11 @@ public function __construct($inputTimezone = null, $outputTimezone = null, $date * * @param \DateTime|\DateTimeInterface $dateTime A DateTime object * - * @return string|array Localized date string/array. + * @return string|array Localized date string/array * * @throws TransformationFailedException If the given value is not an instance - * of \DateTime or if the date could not - * be transformed. + * of \DateTime or \DateTimeInterface or + * if the date could not be transformed. */ public function transform($dateTime) { @@ -105,8 +105,7 @@ public function transform($dateTime) * @return \DateTime Normalized date * * @throws TransformationFailedException if the given value is not a string, - * if the date could not be parsed or - * if the input timezone is not supported + * if the date could not be parsed */ public function reverseTransform($value) { @@ -132,11 +131,7 @@ public function reverseTransform($value) } if ('UTC' !== $this->inputTimezone) { - try { - $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); - } catch (\Exception $e) { - throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); - } + $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); } return $dateTime; diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php index c78d80401a385..25bb1a52c95dc 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php @@ -19,7 +19,14 @@ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer { /** - * {@inheritdoc} + * Transforms a normalized date into a localized date. + * + * @param \DateTime|\DateTimeInterface $dateTime A DateTime object + * + * @return string The formatted date + * + * @throws TransformationFailedException If the given value is not an + * instance of \DateTime or \DateTimeInterface */ public function transform($dateTime) { @@ -32,7 +39,10 @@ public function transform($dateTime) } if ($this->inputTimezone !== $this->outputTimezone) { - $dateTime = clone $dateTime; + if (!$dateTime instanceof \DateTimeImmutable) { + $dateTime = clone $dateTime; + } + $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } @@ -40,7 +50,14 @@ public function transform($dateTime) } /** - * {@inheritdoc} + * Transforms a formatted string following RFC 3339 into a normalized date. + * + * @param string $rfc3339 Formatted string + * + * @return \DateTime Normalized date + * + * @throws TransformationFailedException If the given value is not a string, + * if the value could not be transformed */ public function reverseTransform($rfc3339) { @@ -58,12 +75,8 @@ public function reverseTransform($rfc3339) throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } - if ($this->outputTimezone !== $dateTime->getTimezone()->getName()) { - try { - $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); - } catch (\Exception $e) { - throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); - } + if ($this->inputTimezone !== $dateTime->getTimezone()->getName()) { + $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); } if (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $rfc3339, $matches)) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index 30b73ad83c115..56dee3502787b 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -86,35 +86,30 @@ public function __construct($inputTimezone = null, $outputTimezone = null, $form * Transforms a DateTime object into a date string with the configured format * and timezone. * - * @param \DateTime|\DateTimeInterface $value A DateTime object + * @param \DateTime|\DateTimeInterface $dateTime A DateTime object * * @return string A value as produced by PHP's date() function * - * @throws TransformationFailedException If the given value is not a \DateTime - * instance or if the output timezone - * is not supported. + * @throws TransformationFailedException If the given value is not an + * instance of \DateTime or \DateTimeInterface */ - public function transform($value) + public function transform($dateTime) { - if (null === $value) { + if (null === $dateTime) { return ''; } - if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) { + if (!$dateTime instanceof \DateTime && !$dateTime instanceof \DateTimeInterface) { throw new TransformationFailedException('Expected a \DateTime or \DateTimeInterface.'); } - if (!$value instanceof \DateTimeImmutable) { - $value = clone $value; + if (!$dateTime instanceof \DateTimeImmutable) { + $dateTime = clone $dateTime; } - try { - $value = $value->setTimezone(new \DateTimeZone($this->outputTimezone)); - } catch (\Exception $e) { - throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); - } + $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); - return $value->format($this->generateFormat); + return $dateTime->format($this->generateFormat); } /** @@ -125,8 +120,7 @@ public function transform($value) * @return \DateTime An instance of \DateTime * * @throws TransformationFailedException If the given value is not a string, - * if the date could not be parsed or - * if the input timezone is not supported. + * or could not be transformed */ public function reverseTransform($value) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php index b8f5f381a5a40..7ae30ebbb1c3d 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php @@ -29,20 +29,19 @@ class DateTimeToTimestampTransformer extends BaseDateTimeTransformer * @return int A timestamp * * @throws TransformationFailedException If the given value is not an instance - * of \DateTime or if the output - * timezone is not supported. + * of \DateTime or \DateTimeInterface */ - public function transform($value) + public function transform($dateTime) { - if (null === $value) { + if (null === $dateTime) { return; } - if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) { + if (!$dateTime instanceof \DateTime && !$dateTime instanceof \DateTimeInterface) { throw new TransformationFailedException('Expected a \DateTime or \DateTimeInterface.'); } - return $value->getTimestamp(); + return $dateTime->getTimestamp(); } /** @@ -53,7 +52,7 @@ public function transform($value) * @return \DateTime A \DateTime object * * @throws TransformationFailedException If the given value is not a timestamp - * or if the given timestamp is invalid. + * or if the given timestamp is invalid */ public function reverseTransform($value) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php index eced0cc61d8d3..999e47391b576 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php @@ -22,9 +22,9 @@ class IntegerToLocalizedStringTransformer extends NumberToLocalizedStringTransfo /** * Constructs a transformer. * - * @param int $scale Unused. - * @param bool $grouping Whether thousands should be grouped. - * @param int $roundingMode One of the ROUND_ constants in this class. + * @param int $scale Unused + * @param bool $grouping Whether thousands should be grouped + * @param int $roundingMode One of the ROUND_ constants in this class */ public function __construct($scale = 0, $grouping = false, $roundingMode = self::ROUND_DOWN) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index 2d3efdc35b309..6eeee1280bd75 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -47,7 +47,7 @@ public function __construct($scale = 2, $grouping = true, $roundingMode = self:: * * @param int|float $value Normalized number * - * @return string Localized money string. + * @return string Localized money string * * @throws TransformationFailedException If the given value is not numeric or * if the value can not be transformed. diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 6e336d4ba2dbd..cea67246583f5 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -120,9 +120,9 @@ public function __construct($scale = null, $grouping = false, $roundingMode = se /** * Transforms a number type into localized number. * - * @param int|float $value Number value. + * @param int|float $value Number value * - * @return string Localized value. + * @return string Localized value * * @throws TransformationFailedException If the given value is not numeric * or if the value can not be transformed. @@ -257,9 +257,9 @@ protected function getNumberFormatter() /** * Rounds a number according to the configured scale and rounding mode. * - * @param int|float $number A number. + * @param int|float $number A number * - * @return int|float The rounded number. + * @return int|float The rounded number */ private function round($number) { diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index fff191e543d97..88531feaa222c 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -101,9 +101,9 @@ public function transform($value) /** * Transforms between a percentage value into a normalized format (integer or float). * - * @param string $value Percentage value. + * @param string $value Percentage value * - * @return int|float Normalized value. + * @return int|float Normalized value * * @throws TransformationFailedException If the given value is not a string or * if the value could not be transformed. diff --git a/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php b/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php index 3080ede669cd9..25ebbd35d814f 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php @@ -33,6 +33,7 @@ use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer; +use Symfony\Component\Form\Util\FormUtil; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -90,6 +91,14 @@ public function buildForm(FormBuilderInterface $builder, array $options) $form = $event->getForm(); $data = $event->getData(); + if (null === $data) { + $emptyData = $form->getConfig()->getEmptyData(); + + if (false === FormUtil::isEmpty($emptyData) && array() !== $emptyData) { + $data = is_callable($emptyData) ? call_user_func($emptyData, $form, $data) : $emptyData; + } + } + // Convert the submitted data to a string, if scalar, before // casting it to an array if (!is_array($data)) { @@ -436,9 +445,9 @@ public function getBlockPrefix() /** * Adds the sub fields for an expanded choice field. * - * @param FormBuilderInterface $builder The form builder. - * @param array $choiceViews The choice view objects. - * @param array $options The build options. + * @param FormBuilderInterface $builder The form builder + * @param array $choiceViews The choice view objects + * @param array $options The build options */ private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options) { @@ -507,12 +516,12 @@ private function createChoiceListView(ChoiceListInterface $choiceList, array $op * are lost. Store them in a utility array that is used from the * "choice_label" closure by default. * - * @param array|\Traversable $choices The choice labels indexed by choices. + * @param array|\Traversable $choices The choice labels indexed by choices * @param object $choiceLabels The object that receives the choice labels * indexed by generated keys. - * @param int $nextKey The next generated key. + * @param int $nextKey The next generated key * - * @return array The choices in a normalized array with labels replaced by generated keys. + * @return array The choices in a normalized array with labels replaced by generated keys * * @internal Public only to be accessible from closures on PHP 5.3. Don't * use this method as it may be removed without notice and will be in 3.0. diff --git a/src/Symfony/Component/Form/Extension/Templating/TemplatingRendererEngine.php b/src/Symfony/Component/Form/Extension/Templating/TemplatingRendererEngine.php index a9003e003287d..72b0a4f3dfa3a 100644 --- a/src/Symfony/Component/Form/Extension/Templating/TemplatingRendererEngine.php +++ b/src/Symfony/Component/Form/Extension/Templating/TemplatingRendererEngine.php @@ -48,11 +48,11 @@ public function renderBlock(FormView $view, $resource, $blockName, array $variab * * @see getResourceForBlock() * - * @param string $cacheKey The cache key of the form view. - * @param FormView $view The form view for finding the applying themes. - * @param string $blockName The name of the block to load. + * @param string $cacheKey The cache key of the form view + * @param FormView $view The form view for finding the applying themes + * @param string $blockName The name of the block to load * - * @return bool True if the resource could be loaded, false otherwise. + * @return bool True if the resource could be loaded, false otherwise */ protected function loadResourceForBlockName($cacheKey, FormView $view, $blockName) { @@ -106,11 +106,11 @@ protected function loadResourceForBlockName($cacheKey, FormView $view, $blockNam /** * Tries to load the resource for a block from a theme. * - * @param string $cacheKey The cache key for storing the resource. - * @param string $blockName The name of the block to load a resource for. - * @param mixed $theme The theme to load the block from. + * @param string $cacheKey The cache key for storing the resource + * @param string $blockName The name of the block to load a resource for + * @param mixed $theme The theme to load the block from * - * @return bool True if the resource could be loaded, false otherwise. + * @return bool True if the resource could be loaded, false otherwise */ protected function loadResourceFromTheme($cacheKey, $blockName, $theme) { diff --git a/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php b/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php index d2fb36332d7f7..45cd800b69118 100644 --- a/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php +++ b/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php @@ -153,9 +153,9 @@ public function validate($form, Constraint $constraint) /** * Returns whether the data of a form may be walked. * - * @param FormInterface $form The form to test. + * @param FormInterface $form The form to test * - * @return bool Whether the graph walker may walk the data. + * @return bool Whether the graph walker may walk the data */ private static function allowDataWalking(FormInterface $form) { @@ -185,9 +185,9 @@ private static function allowDataWalking(FormInterface $form) /** * Returns the validation groups of the given form. * - * @param FormInterface $form The form. + * @param FormInterface $form The form * - * @return array The validation groups. + * @return array The validation groups */ private static function getValidationGroups(FormInterface $form) { @@ -222,10 +222,10 @@ private static function getValidationGroups(FormInterface $form) /** * Post-processes the validation groups option for a given form. * - * @param array|callable $groups The validation groups. - * @param FormInterface $form The validated form. + * @param array|callable $groups The validation groups + * @param FormInterface $form The validated form * - * @return array The validation groups. + * @return array The validation groups */ private static function resolveValidationGroups($groups, FormInterface $form) { diff --git a/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php b/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php new file mode 100644 index 0000000000000..d89a326f77a10 --- /dev/null +++ b/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\Validator\Type; + +use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\OptionsResolver\Options; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\Translation\TranslatorInterface; + +/** + * @author Abdellatif Ait boudad + * @author David Badura + */ +class UploadValidatorExtension extends AbstractTypeExtension +{ + private $translator; + private $translationDomain; + + /** + * @param TranslatorInterface $translator The translator for translating error messages + * @param null|string $translationDomain The translation domain for translating + */ + public function __construct(TranslatorInterface $translator, $translationDomain = null) + { + $this->translator = $translator; + $this->translationDomain = $translationDomain; + } + + /** + * {@inheritdoc} + */ + public function configureOptions(OptionsResolver $resolver) + { + $translator = $this->translator; + $translationDomain = $this->translationDomain; + + $resolver->setNormalizer('post_max_size_message', function (Options $options, $errorMessage) use ($translator, $translationDomain) { + return $translator->trans($errorMessage, array(), $translationDomain); + }); + } + + /** + * {@inheritdoc} + */ + public function getExtendedType() + { + return 'Symfony\Component\Form\Extension\Core\Type\FormType'; + } +} diff --git a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/MappingRule.php b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/MappingRule.php index 48b5ceace6e34..dc37a1570752e 100644 --- a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/MappingRule.php +++ b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/MappingRule.php @@ -55,9 +55,9 @@ public function getOrigin() * If the rule matches, the form mapped by the rule is returned. * Otherwise this method returns false. * - * @param string $propertyPath The property path to match against the rule. + * @param string $propertyPath The property path to match against the rule * - * @return null|FormInterface The mapped form or null. + * @return null|FormInterface The mapped form or null */ public function match($propertyPath) { @@ -69,9 +69,9 @@ public function match($propertyPath) /** * Matches a property path against a prefix of the rule path. * - * @param string $propertyPath The property path to match against the rule. + * @param string $propertyPath The property path to match against the rule * - * @return bool Whether the property path is a prefix of the rule or not. + * @return bool Whether the property path is a prefix of the rule or not */ public function isPrefix($propertyPath) { diff --git a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php index 304ec17e1a493..4b64386117f8d 100644 --- a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -141,10 +141,10 @@ public function mapViolation(ConstraintViolation $violation, FormInterface $form * If a matching child is found, it is returned. Otherwise * null is returned. * - * @param FormInterface $form The form to search. - * @param PropertyPathIteratorInterface $it The iterator at its current position. + * @param FormInterface $form The form to search + * @param PropertyPathIteratorInterface $it The iterator at its current position * - * @return null|FormInterface The found match or null. + * @return null|FormInterface The found match or null */ private function matchChild(FormInterface $form, PropertyPathIteratorInterface $it) { @@ -212,10 +212,10 @@ private function matchChild(FormInterface $form, PropertyPathIteratorInterface $ /** * Reconstructs a property path from a violation path and a form tree. * - * @param ViolationPath $violationPath The violation path. - * @param FormInterface $origin The root form of the tree. + * @param ViolationPath $violationPath The violation path + * @param FormInterface $origin The root form of the tree * - * @return RelativePath The reconstructed path. + * @return RelativePath The reconstructed path */ private function reconstructPath(ViolationPath $violationPath, FormInterface $origin) { @@ -275,9 +275,6 @@ private function reconstructPath(ViolationPath $violationPath, FormInterface $or */ private function acceptsErrors(FormInterface $form) { - // Ignore non-submitted forms. This happens, for example, in PATCH - // requests. - // https://github.com/symfony/symfony/pull/10567 - return $form->isSubmitted() && ($this->allowNonSynchronized || $form->isSynchronized()); + return $this->allowNonSynchronized || $form->isSynchronized(); } } diff --git a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapperInterface.php b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapperInterface.php index fb56a2bad2bae..bb7c6b7670aef 100644 --- a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapperInterface.php +++ b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapperInterface.php @@ -23,7 +23,7 @@ interface ViolationMapperInterface * Maps a constraint violation to a form in the form tree under * the given form. * - * @param ConstraintViolation $violation The violation to map. + * @param ConstraintViolation $violation The violation to map * @param FormInterface $form The root form of the tree * to map it to. * @param bool $allowNonSynchronized Whether to allow diff --git a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationPath.php b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationPath.php index c84f98a200ded..1e984e2f4da83 100644 --- a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationPath.php @@ -206,9 +206,9 @@ public function isIndex($index) * In this example, "address" and "office" map to forms, while * "street does not. * - * @param int $index The element index. + * @param int $index The element index * - * @return bool Whether the element maps to a form. + * @return bool Whether the element maps to a form * * @throws OutOfBoundsException If the offset is invalid. */ diff --git a/src/Symfony/Component/Form/Form.php b/src/Symfony/Component/Form/Form.php index 0e0d1b73cce1e..f67375bf33722 100644 --- a/src/Symfony/Component/Form/Form.php +++ b/src/Symfony/Component/Form/Form.php @@ -162,7 +162,7 @@ class Form implements \IteratorAggregate, FormInterface /** * Creates a new form based on the given configuration. * - * @param FormConfigInterface $config The form configuration. + * @param FormConfigInterface $config The form configuration * * @throws LogicException if a data mapper is not provided for a compound form */ @@ -994,8 +994,8 @@ public function offsetGet($name) /** * Adds a child to the form (implements the \ArrayAccess interface). * - * @param string $name Ignored. The name of the child is used. - * @param FormInterface $child The child to be added. + * @param string $name Ignored. The name of the child is used + * @param FormInterface $child The child to be added * * @throws AlreadySubmittedException If the form has already been submitted. * @throws LogicException When trying to add a child to a non-compound form. @@ -1022,7 +1022,7 @@ public function offsetUnset($name) /** * Returns the iterator for this group. * - * @return \Traversable + * @return \Traversable|FormInterface[] */ public function getIterator() { diff --git a/src/Symfony/Component/Form/FormBuilder.php b/src/Symfony/Component/Form/FormBuilder.php index b4dd78c105be3..a9bf67be1f508 100644 --- a/src/Symfony/Component/Form/FormBuilder.php +++ b/src/Symfony/Component/Form/FormBuilder.php @@ -231,6 +231,8 @@ public function getForm() /** * {@inheritdoc} + * + * @return FormBuilderInterface[] */ public function getIterator() { @@ -244,9 +246,9 @@ public function getIterator() /** * Converts an unresolved child into a {@link FormBuilder} instance. * - * @param string $name The name of the unresolved child. + * @param string $name The name of the unresolved child * - * @return FormBuilder The created instance. + * @return FormBuilder The created instance */ private function resolveChild($name) { diff --git a/src/Symfony/Component/Form/FormBuilderInterface.php b/src/Symfony/Component/Form/FormBuilderInterface.php index 998d3ec0d31a0..b72059242ea95 100644 --- a/src/Symfony/Component/Form/FormBuilderInterface.php +++ b/src/Symfony/Component/Form/FormBuilderInterface.php @@ -27,7 +27,7 @@ interface FormBuilderInterface extends \Traversable, \Countable, FormConfigBuild * @param string|FormTypeInterface $type * @param array $options * - * @return FormBuilderInterface The builder object. + * @return FormBuilderInterface The builder object */ public function add($child, $type = null, array $options = array()); @@ -38,7 +38,7 @@ public function add($child, $type = null, array $options = array()); * @param string|FormTypeInterface $type The type of the form or null if name is a property * @param array $options The options * - * @return FormBuilderInterface The created builder. + * @return FormBuilderInterface The created builder */ public function create($name, $type = null, array $options = array()); @@ -58,7 +58,7 @@ public function get($name); * * @param string $name * - * @return FormBuilderInterface The builder object. + * @return FormBuilderInterface The builder object */ public function remove($name); @@ -81,7 +81,7 @@ public function all(); /** * Creates the form. * - * @return Form The form + * @return FormInterface The form */ public function getForm(); } diff --git a/src/Symfony/Component/Form/FormConfigBuilder.php b/src/Symfony/Component/Form/FormConfigBuilder.php index d217cf019365d..2076f016ac2d6 100644 --- a/src/Symfony/Component/Form/FormConfigBuilder.php +++ b/src/Symfony/Component/Form/FormConfigBuilder.php @@ -349,7 +349,7 @@ public function getInheritData() /** * Alias of {@link getInheritData()}. * - * @return FormConfigBuilder The configuration object. + * @return FormConfigBuilder The configuration object * * @deprecated since version 2.3, to be removed in 3.0. * Use {@link getInheritData()} instead. @@ -713,9 +713,9 @@ public function setInheritData($inheritData) /** * Alias of {@link setInheritData()}. * - * @param bool $inheritData Whether the form should inherit its parent's data. + * @param bool $inheritData Whether the form should inherit its parent's data * - * @return FormConfigBuilder The configuration object. + * @return FormConfigBuilder The configuration object * * @deprecated since version 2.3, to be removed in 3.0. * Use {@link setInheritData()} instead. @@ -882,7 +882,7 @@ public function getFormConfig() /** * Validates whether the given variable is a valid form name. * - * @param string|int $name The tested form name. + * @param string|int $name The tested form name * * @throws UnexpectedTypeException If the name is not a string or an integer. * @throws InvalidArgumentException If the name contains invalid characters. @@ -911,9 +911,9 @@ public static function validateName($name) * * contains only letters, digits, numbers, underscores ("_"), * hyphens ("-") and colons (":") * - * @param string $name The tested form name. + * @param string $name The tested form name * - * @return bool Whether the name is valid. + * @return bool Whether the name is valid */ public static function isValidName($name) { diff --git a/src/Symfony/Component/Form/FormConfigBuilderInterface.php b/src/Symfony/Component/Form/FormConfigBuilderInterface.php index ad8bf69328a12..72d747c2421bb 100644 --- a/src/Symfony/Component/Form/FormConfigBuilderInterface.php +++ b/src/Symfony/Component/Form/FormConfigBuilderInterface.php @@ -22,22 +22,22 @@ interface FormConfigBuilderInterface extends FormConfigInterface /** * Adds an event listener to an event on this form. * - * @param string $eventName The name of the event to listen to. - * @param callable $listener The listener to execute. + * @param string $eventName The name of the event to listen to + * @param callable $listener The listener to execute * @param int $priority The priority of the listener. Listeners * with a higher priority are called before * listeners with a lower priority. * - * @return self The configuration object. + * @return self The configuration object */ public function addEventListener($eventName, $listener, $priority = 0); /** * Adds an event subscriber for events on this form. * - * @param EventSubscriberInterface $subscriber The subscriber to attach. + * @param EventSubscriberInterface $subscriber The subscriber to attach * - * @return self The configuration object. + * @return self The configuration object */ public function addEventSubscriber(EventSubscriberInterface $subscriber); @@ -52,14 +52,14 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber); * @param DataTransformerInterface $viewTransformer * @param bool $forcePrepend if set to true, prepend instead of appending * - * @return self The configuration object. + * @return self The configuration object */ public function addViewTransformer(DataTransformerInterface $viewTransformer, $forcePrepend = false); /** * Clears the view transformers. * - * @return self The configuration object. + * @return self The configuration object */ public function resetViewTransformers(); @@ -74,14 +74,14 @@ public function resetViewTransformers(); * @param DataTransformerInterface $modelTransformer * @param bool $forceAppend if set to true, append instead of prepending * - * @return self The configuration object. + * @return self The configuration object */ public function addModelTransformer(DataTransformerInterface $modelTransformer, $forceAppend = false); /** * Clears the normalization transformers. * - * @return self The configuration object. + * @return self The configuration object */ public function resetModelTransformers(); @@ -91,16 +91,16 @@ public function resetModelTransformers(); * @param string $name The name of the attribute * @param mixed $value The value of the attribute * - * @return self The configuration object. + * @return self The configuration object */ public function setAttribute($name, $value); /** * Sets the attributes. * - * @param array $attributes The attributes. + * @param array $attributes The attributes * - * @return self The configuration object. + * @return self The configuration object */ public function setAttributes(array $attributes); @@ -109,7 +109,7 @@ public function setAttributes(array $attributes); * * @param DataMapperInterface $dataMapper * - * @return self The configuration object. + * @return self The configuration object */ public function setDataMapper(DataMapperInterface $dataMapper = null); @@ -118,16 +118,16 @@ public function setDataMapper(DataMapperInterface $dataMapper = null); * * @param bool $disabled Whether the form is disabled * - * @return self The configuration object. + * @return self The configuration object */ public function setDisabled($disabled); /** * Sets the data used for the client data when no value is submitted. * - * @param mixed $emptyData The empty data. + * @param mixed $emptyData The empty data * - * @return self The configuration object. + * @return self The configuration object */ public function setEmptyData($emptyData); @@ -136,7 +136,7 @@ public function setEmptyData($emptyData); * * @param bool $errorBubbling * - * @return self The configuration object. + * @return self The configuration object */ public function setErrorBubbling($errorBubbling); @@ -145,7 +145,7 @@ public function setErrorBubbling($errorBubbling); * * @param bool $required * - * @return self The configuration object. + * @return self The configuration object */ public function setRequired($required); @@ -156,7 +156,7 @@ public function setRequired($required); * The property path or null if the path should be set * automatically based on the form's name. * - * @return self The configuration object. + * @return self The configuration object */ public function setPropertyPath($propertyPath); @@ -164,9 +164,9 @@ public function setPropertyPath($propertyPath); * Sets whether the form should be mapped to an element of its * parent's data. * - * @param bool $mapped Whether the form should be mapped. + * @param bool $mapped Whether the form should be mapped * - * @return self The configuration object. + * @return self The configuration object */ public function setMapped($mapped); @@ -176,25 +176,25 @@ public function setMapped($mapped); * @param bool $byReference Whether the data should be * modified by reference. * - * @return self The configuration object. + * @return self The configuration object */ public function setByReference($byReference); /** * Sets whether the form should read and write the data of its parent. * - * @param bool $inheritData Whether the form should inherit its parent's data. + * @param bool $inheritData Whether the form should inherit its parent's data * - * @return self The configuration object. + * @return self The configuration object */ public function setInheritData($inheritData); /** * Sets whether the form should be compound. * - * @param bool $compound Whether the form should be compound. + * @param bool $compound Whether the form should be compound * - * @return self The configuration object. + * @return self The configuration object * * @see FormConfigInterface::getCompound() */ @@ -203,18 +203,18 @@ public function setCompound($compound); /** * Set the types. * - * @param ResolvedFormTypeInterface $type The type of the form. + * @param ResolvedFormTypeInterface $type The type of the form * - * @return self The configuration object. + * @return self The configuration object */ public function setType(ResolvedFormTypeInterface $type); /** * Sets the initial data of the form. * - * @param mixed $data The data of the form in application format. + * @param mixed $data The data of the form in application format * - * @return self The configuration object. + * @return self The configuration object */ public function setData($data); @@ -225,34 +225,34 @@ public function setData($data); * this configuration. The data can only be modified then by * submitting the form. * - * @param bool $locked Whether to lock the default data. + * @param bool $locked Whether to lock the default data * - * @return self The configuration object. + * @return self The configuration object */ public function setDataLocked($locked); /** * Sets the form factory used for creating new forms. * - * @param FormFactoryInterface $formFactory The form factory. + * @param FormFactoryInterface $formFactory The form factory */ public function setFormFactory(FormFactoryInterface $formFactory); /** * Sets the target URL of the form. * - * @param string $action The target URL of the form. + * @param string $action The target URL of the form * - * @return self The configuration object. + * @return self The configuration object */ public function setAction($action); /** * Sets the HTTP method used by the form. * - * @param string $method The HTTP method of the form. + * @param string $method The HTTP method of the form * - * @return self The configuration object. + * @return self The configuration object */ public function setMethod($method); @@ -261,7 +261,7 @@ public function setMethod($method); * * @param RequestHandlerInterface $requestHandler * - * @return self The configuration object. + * @return self The configuration object */ public function setRequestHandler(RequestHandlerInterface $requestHandler); @@ -275,7 +275,7 @@ public function setRequestHandler(RequestHandlerInterface $requestHandler); * In the second case, you need to call * {@link FormInterface::initialize()} manually. * - * @return self The configuration object. + * @return self The configuration object */ public function setAutoInitialize($initialize); diff --git a/src/Symfony/Component/Form/FormConfigInterface.php b/src/Symfony/Component/Form/FormConfigInterface.php index 179905850f749..c2f97901d25c3 100644 --- a/src/Symfony/Component/Form/FormConfigInterface.php +++ b/src/Symfony/Component/Form/FormConfigInterface.php @@ -24,21 +24,21 @@ interface FormConfigInterface /** * Returns the event dispatcher used to dispatch form events. * - * @return EventDispatcherInterface The dispatcher. + * @return EventDispatcherInterface The dispatcher */ public function getEventDispatcher(); /** * Returns the name of the form used as HTTP parameter. * - * @return string The form name. + * @return string The form name */ public function getName(); /** * Returns the property path that the form should be mapped to. * - * @return null|PropertyPathInterface The property path. + * @return null|PropertyPathInterface The property path */ public function getPropertyPath(); @@ -46,21 +46,21 @@ public function getPropertyPath(); * Returns whether the form should be mapped to an element of its * parent's data. * - * @return bool Whether the form is mapped. + * @return bool Whether the form is mapped */ public function getMapped(); /** * Returns whether the form's data should be modified by reference. * - * @return bool Whether to modify the form's data by reference. + * @return bool Whether to modify the form's data by reference */ public function getByReference(); /** * Returns whether the form should read and write the data of its parent. * - * @return bool Whether the form should inherit its parent's data. + * @return bool Whether the form should inherit its parent's data */ public function getInheritData(); @@ -71,103 +71,103 @@ public function getInheritData(); * children. A form can be compound and have no children at all, like * for example an empty collection form. * - * @return bool Whether the form is compound. + * @return bool Whether the form is compound */ public function getCompound(); /** * Returns the form types used to construct the form. * - * @return ResolvedFormTypeInterface The form's type. + * @return ResolvedFormTypeInterface The form's type */ public function getType(); /** * Returns the view transformers of the form. * - * @return DataTransformerInterface[] An array of {@link DataTransformerInterface} instances. + * @return DataTransformerInterface[] An array of {@link DataTransformerInterface} instances */ public function getViewTransformers(); /** * Returns the model transformers of the form. * - * @return DataTransformerInterface[] An array of {@link DataTransformerInterface} instances. + * @return DataTransformerInterface[] An array of {@link DataTransformerInterface} instances */ public function getModelTransformers(); /** * Returns the data mapper of the form. * - * @return DataMapperInterface The data mapper. + * @return DataMapperInterface The data mapper */ public function getDataMapper(); /** * Returns whether the form is required. * - * @return bool Whether the form is required. + * @return bool Whether the form is required */ public function getRequired(); /** * Returns whether the form is disabled. * - * @return bool Whether the form is disabled. + * @return bool Whether the form is disabled */ public function getDisabled(); /** * Returns whether errors attached to the form will bubble to its parent. * - * @return bool Whether errors will bubble up. + * @return bool Whether errors will bubble up */ public function getErrorBubbling(); /** * Returns the data that should be returned when the form is empty. * - * @return mixed The data returned if the form is empty. + * @return mixed The data returned if the form is empty */ public function getEmptyData(); /** * Returns additional attributes of the form. * - * @return array An array of key-value combinations. + * @return array An array of key-value combinations */ public function getAttributes(); /** * Returns whether the attribute with the given name exists. * - * @param string $name The attribute name. + * @param string $name The attribute name * - * @return bool Whether the attribute exists. + * @return bool Whether the attribute exists */ public function hasAttribute($name); /** * Returns the value of the given attribute. * - * @param string $name The attribute name. - * @param mixed $default The value returned if the attribute does not exist. + * @param string $name The attribute name + * @param mixed $default The value returned if the attribute does not exist * - * @return mixed The attribute value. + * @return mixed The attribute value */ public function getAttribute($name, $default = null); /** * Returns the initial data of the form. * - * @return mixed The initial form data. + * @return mixed The initial form data */ public function getData(); /** * Returns the class of the form data or null if the data is scalar or an array. * - * @return string The data class or null. + * @return string The data class or null */ public function getDataClass(); @@ -178,35 +178,35 @@ public function getDataClass(); * this configuration. The data can only be modified then by * submitting the form. * - * @return bool Whether the data is locked. + * @return bool Whether the data is locked */ public function getDataLocked(); /** * Returns the form factory used for creating new forms. * - * @return FormFactoryInterface The form factory. + * @return FormFactoryInterface The form factory */ public function getFormFactory(); /** * Returns the target URL of the form. * - * @return string The target URL of the form. + * @return string The target URL of the form */ public function getAction(); /** * Returns the HTTP method used by the form. * - * @return string The HTTP method of the form. + * @return string The HTTP method of the form */ public function getMethod(); /** * Returns the request handler used by the form. * - * @return RequestHandlerInterface The request handler. + * @return RequestHandlerInterface The request handler */ public function getRequestHandler(); @@ -221,7 +221,7 @@ public function getAutoInitialize(); /** * Returns all options passed during the construction of the form. * - * @return array The passed options. + * @return array The passed options */ public function getOptions(); @@ -230,17 +230,17 @@ public function getOptions(); * * @param string $name The option name, * - * @return bool Whether the option exists. + * @return bool Whether the option exists */ public function hasOption($name); /** * Returns the value of a specific option. * - * @param string $name The option name. - * @param mixed $default The value returned if the option does not exist. + * @param string $name The option name + * @param mixed $default The value returned if the option does not exist * - * @return mixed The option value. + * @return mixed The option value */ public function getOption($name, $default = null); } diff --git a/src/Symfony/Component/Form/FormErrorIterator.php b/src/Symfony/Component/Form/FormErrorIterator.php index 7ee2df26b4bf7..113de435d5ede 100644 --- a/src/Symfony/Component/Form/FormErrorIterator.php +++ b/src/Symfony/Component/Form/FormErrorIterator.php @@ -99,7 +99,7 @@ public function __toString() /** * Returns the iterated form. * - * @return FormInterface The form whose errors are iterated by this object. + * @return FormInterface The form whose errors are iterated by this object */ public function getForm() { @@ -128,7 +128,7 @@ public function next() /** * Returns the current position of the iterator. * - * @return int The 0-indexed position. + * @return int The 0-indexed position */ public function key() { @@ -138,7 +138,7 @@ public function key() /** * Returns whether the iterator's position is valid. * - * @return bool Whether the iterator is valid. + * @return bool Whether the iterator is valid */ public function valid() { diff --git a/src/Symfony/Component/Form/FormFactory.php b/src/Symfony/Component/Form/FormFactory.php index 048705f1422fb..f0a399b95c037 100644 --- a/src/Symfony/Component/Form/FormFactory.php +++ b/src/Symfony/Component/Form/FormFactory.php @@ -163,9 +163,9 @@ public function createBuilderForProperty($class, $property, $data = null, array * Wraps a type into a ResolvedFormTypeInterface implementation and connects * it with its parent type. * - * @param FormTypeInterface $type The type to resolve. + * @param FormTypeInterface $type The type to resolve * - * @return ResolvedFormTypeInterface The resolved type. + * @return ResolvedFormTypeInterface The resolved type */ private function resolveType(FormTypeInterface $type) { diff --git a/src/Symfony/Component/Form/FormFactoryBuilderInterface.php b/src/Symfony/Component/Form/FormFactoryBuilderInterface.php index e32f1ce7666ef..d89e2f9f9a2bf 100644 --- a/src/Symfony/Component/Form/FormFactoryBuilderInterface.php +++ b/src/Symfony/Component/Form/FormFactoryBuilderInterface.php @@ -23,86 +23,86 @@ interface FormFactoryBuilderInterface * * @param ResolvedFormTypeFactoryInterface $resolvedTypeFactory * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory); /** * Adds an extension to be loaded by the factory. * - * @param FormExtensionInterface $extension The extension. + * @param FormExtensionInterface $extension The extension * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addExtension(FormExtensionInterface $extension); /** * Adds a list of extensions to be loaded by the factory. * - * @param FormExtensionInterface[] $extensions The extensions. + * @param FormExtensionInterface[] $extensions The extensions * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addExtensions(array $extensions); /** * Adds a form type to the factory. * - * @param FormTypeInterface $type The form type. + * @param FormTypeInterface $type The form type * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addType(FormTypeInterface $type); /** * Adds a list of form types to the factory. * - * @param FormTypeInterface[] $types The form types. + * @param FormTypeInterface[] $types The form types * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addTypes(array $types); /** * Adds a form type extension to the factory. * - * @param FormTypeExtensionInterface $typeExtension The form type extension. + * @param FormTypeExtensionInterface $typeExtension The form type extension * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addTypeExtension(FormTypeExtensionInterface $typeExtension); /** * Adds a list of form type extensions to the factory. * - * @param FormTypeExtensionInterface[] $typeExtensions The form type extensions. + * @param FormTypeExtensionInterface[] $typeExtensions The form type extensions * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addTypeExtensions(array $typeExtensions); /** * Adds a type guesser to the factory. * - * @param FormTypeGuesserInterface $typeGuesser The type guesser. + * @param FormTypeGuesserInterface $typeGuesser The type guesser * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser); /** * Adds a list of type guessers to the factory. * - * @param FormTypeGuesserInterface[] $typeGuessers The type guessers. + * @param FormTypeGuesserInterface[] $typeGuessers The type guessers * - * @return FormFactoryBuilderInterface The builder. + * @return FormFactoryBuilderInterface The builder */ public function addTypeGuessers(array $typeGuessers); /** * Builds and returns the factory. * - * @return FormFactoryInterface The form factory. + * @return FormFactoryInterface The form factory */ public function getFormFactory(); } diff --git a/src/Symfony/Component/Form/FormInterface.php b/src/Symfony/Component/Form/FormInterface.php index b2131e1da4ec3..13b03f5118c1c 100644 --- a/src/Symfony/Component/Form/FormInterface.php +++ b/src/Symfony/Component/Form/FormInterface.php @@ -23,7 +23,7 @@ interface FormInterface extends \ArrayAccess, \Traversable, \Countable /** * Sets the parent form. * - * @param FormInterface|null $parent The parent form or null if it's the root. + * @param FormInterface|null $parent The parent form or null if it's the root * * @return FormInterface The form instance * @@ -36,16 +36,16 @@ public function setParent(FormInterface $parent = null); /** * Returns the parent form. * - * @return FormInterface|null The parent form or null if there is none. + * @return FormInterface|null The parent form or null if there is none */ public function getParent(); /** * Adds or replaces a child to the form. * - * @param FormInterface|string|int $child The FormInterface instance or the name of the child. - * @param string|null $type The child's type, if a name was passed. - * @param array $options The child's options, if a name was passed. + * @param FormInterface|string|int $child The FormInterface instance or the name of the child + * @param string|null $type The child's type, if a name was passed + * @param array $options The child's options, if a name was passed * * @return FormInterface The form instance * @@ -132,7 +132,7 @@ public function getData(); /** * Returns the normalized data of the field. * - * @return mixed When the field is not submitted, the default data is returned. + * @return mixed When the field is not submitted, the default data is returned * When the field is submitted, the normalized submitted data is * returned if the field is valid, null otherwise. */ @@ -155,7 +155,7 @@ public function getExtraData(); /** * Returns the form's configuration. * - * @return FormConfigInterface The configuration. + * @return FormConfigInterface The configuration */ public function getConfig(); @@ -169,14 +169,14 @@ public function isSubmitted(); /** * Returns the name by which the form is identified in forms. * - * @return string The name of the form. + * @return string The name of the form */ public function getName(); /** * Returns the property path that the form is mapped to. * - * @return \Symfony\Component\PropertyAccess\PropertyPathInterface The property path. + * @return \Symfony\Component\PropertyAccess\PropertyPathInterface The property path */ public function getPropertyPath(); @@ -251,7 +251,7 @@ public function getTransformationFailure(); * * Should be called on the root form after constructing the tree. * - * @return FormInterface The form instance. + * @return FormInterface The form instance */ public function initialize(); @@ -263,16 +263,16 @@ public function initialize(); * {@link RequestHandlerInterface} instance, which determines whether to * submit the form or not. * - * @param mixed $request The request to handle. + * @param mixed $request The request to handle * - * @return FormInterface The form instance. + * @return FormInterface The form instance */ public function handleRequest($request = null); /** * Submits data to the form, transforms and validates it. * - * @param null|string|array $submittedData The submitted data. + * @param null|string|array $submittedData The submitted data * @param bool $clearMissing Whether to set fields to NULL * when they are missing in the * submitted data. diff --git a/src/Symfony/Component/Form/FormRegistry.php b/src/Symfony/Component/Form/FormRegistry.php index a8995afe89f01..3e04283e96796 100644 --- a/src/Symfony/Component/Form/FormRegistry.php +++ b/src/Symfony/Component/Form/FormRegistry.php @@ -53,7 +53,7 @@ class FormRegistry implements FormRegistryInterface * Constructor. * * @param FormExtensionInterface[] $extensions An array of FormExtensionInterface - * @param ResolvedFormTypeFactoryInterface $resolvedTypeFactory The factory for resolved form types. + * @param ResolvedFormTypeFactoryInterface $resolvedTypeFactory The factory for resolved form types * * @throws UnexpectedTypeException if any extension does not implement FormExtensionInterface */ @@ -107,9 +107,9 @@ public function getType($name) * Wraps a type into a ResolvedFormTypeInterface implementation and connects * it with its parent type. * - * @param FormTypeInterface $type The type to resolve. + * @param FormTypeInterface $type The type to resolve * - * @return ResolvedFormTypeInterface The resolved type. + * @return ResolvedFormTypeInterface The resolved type */ private function resolveAndAddType(FormTypeInterface $type) { diff --git a/src/Symfony/Component/Form/FormRenderer.php b/src/Symfony/Component/Form/FormRenderer.php index b286ffdf41b24..15a8d08430cfe 100644 --- a/src/Symfony/Component/Form/FormRenderer.php +++ b/src/Symfony/Component/Form/FormRenderer.php @@ -253,10 +253,11 @@ public function searchAndRenderBlock(FormView $view, $blockNameSuffix, array $va // Escape if no resource exists for this block if (!$resource) { - throw new LogicException(sprintf( - 'Unable to render the form as none of the following blocks exist: "%s".', - implode('", "', array_reverse($blockNameHierarchy)) - )); + if (count($blockNameHierarchy) !== count(array_unique($blockNameHierarchy))) { + throw new LogicException(sprintf('Unable to render the form because the block names array contains duplicates: "%s".', implode('", "', array_reverse($blockNameHierarchy)))); + } + + throw new LogicException(sprintf('Unable to render the form as none of the following blocks exist: "%s".', implode('", "', array_reverse($blockNameHierarchy)))); } // Merge the passed with the existing attributes diff --git a/src/Symfony/Component/Form/FormRendererEngineInterface.php b/src/Symfony/Component/Form/FormRendererEngineInterface.php index b49ec9cc8ab4e..c3667b1dbb5fb 100644 --- a/src/Symfony/Component/Form/FormRendererEngineInterface.php +++ b/src/Symfony/Component/Form/FormRendererEngineInterface.php @@ -21,7 +21,7 @@ interface FormRendererEngineInterface /** * Sets the theme(s) to be used for rendering a view and its children. * - * @param FormView $view The view to assign the theme(s) to. + * @param FormView $view The view to assign the theme(s) to * @param mixed $themes The theme(s). The type of these themes * is open to the implementation. */ @@ -36,13 +36,13 @@ public function setTheme(FormView $view, $themes); * The type of the resource is decided by the implementation. The resource * is later passed to {@link renderBlock()} by the rendering algorithm. * - * @param FormView $view The view for determining the used themes. + * @param FormView $view The view for determining the used themes * First the themes attached directly to the * view with {@link setTheme()} are considered, * then the ones of its parent etc. - * @param string $blockName The name of the block to render. + * @param string $blockName The name of the block to render * - * @return mixed The renderer resource or false, if none was found. + * @return mixed The renderer resource or false, if none was found */ public function getResourceForBlockName(FormView $view, $blockName); @@ -70,7 +70,7 @@ public function getResourceForBlockName(FormView $view, $blockName); * The type of the resource is decided by the implementation. The resource * is later passed to {@link renderBlock()} by the rendering algorithm. * - * @param FormView $view The view for determining the used themes. + * @param FormView $view The view for determining the used themes * First the themes attached directly to * the view with {@link setTheme()} are * considered, then the ones of its parent etc. @@ -80,7 +80,7 @@ public function getResourceForBlockName(FormView $view, $blockName); * looking. Level 0 indicates the root block, i.e. * the first element of $blockNameHierarchy. * - * @return mixed The renderer resource or false, if none was found. + * @return mixed The renderer resource or false, if none was found */ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNameHierarchy, $hierarchyLevel); @@ -110,7 +110,7 @@ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNam * The type of the resource is decided by the implementation. The resource * is later passed to {@link renderBlock()} by the rendering algorithm. * - * @param FormView $view The view for determining the used themes. + * @param FormView $view The view for determining the used themes * First the themes attached directly to * the view with {@link setTheme()} are * considered, then the ones of its parent etc. @@ -120,7 +120,7 @@ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNam * looking. Level 0 indicates the root block, i.e. * the first element of $blockNameHierarchy. * - * @return int|bool The hierarchy level or false, if no resource was found. + * @return int|bool The hierarchy level or false, if no resource was found */ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierarchy, $hierarchyLevel); @@ -131,12 +131,12 @@ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierar * or {@link getResourceForBlockHierarchy()}. The type of the resource is * decided by the implementation. * - * @param FormView $view The view to render. - * @param mixed $resource The renderer resource. - * @param string $blockName The name of the block to render. - * @param array $variables The variables to pass to the template. + * @param FormView $view The view to render + * @param mixed $resource The renderer resource + * @param string $blockName The name of the block to render + * @param array $variables The variables to pass to the template * - * @return string The HTML markup. + * @return string The HTML markup */ public function renderBlock(FormView $view, $resource, $blockName, array $variables = array()); } diff --git a/src/Symfony/Component/Form/FormRendererInterface.php b/src/Symfony/Component/Form/FormRendererInterface.php index 6dc9e86c37ccb..f0f51e4f59251 100644 --- a/src/Symfony/Component/Form/FormRendererInterface.php +++ b/src/Symfony/Component/Form/FormRendererInterface.php @@ -21,14 +21,14 @@ interface FormRendererInterface /** * Returns the engine used by this renderer. * - * @return FormRendererEngineInterface The renderer engine. + * @return FormRendererEngineInterface The renderer engine */ public function getEngine(); /** * Sets the theme(s) to be used for rendering a view and its children. * - * @param FormView $view The view to assign the theme(s) to. + * @param FormView $view The view to assign the theme(s) to * @param mixed $themes The theme(s). The type of these themes * is open to the implementation. */ @@ -37,9 +37,9 @@ public function setTheme(FormView $view, $themes); /** * Renders a named block of the form theme. * - * @param FormView $view The view for which to render the block. - * @param string $blockName The name of the block. - * @param array $variables The variables to pass to the template. + * @param FormView $view The view for which to render the block + * @param string $blockName The name of the block + * @param array $variables The variables to pass to the template * * @return string The HTML markup */ @@ -55,9 +55,9 @@ public function renderBlock(FormView $view, $blockName, array $variables = array * If this method is called recursively, the block search is continued * where a block was found before. * - * @param FormView $view The view for which to render the block. - * @param string $blockNameSuffix The suffix of the block name. - * @param array $variables The variables to pass to the template. + * @param FormView $view The view for which to render the block + * @param string $blockNameSuffix The suffix of the block name + * @param array $variables The variables to pass to the template * * @return string The HTML markup */ @@ -95,9 +95,9 @@ public function renderCsrfToken($tokenId); * of the resulting string is capitalized, while all other letters are * turned to lowercase. * - * @param string $text The text to humanize. + * @param string $text The text to humanize * - * @return string The humanized text. + * @return string The humanized text */ public function humanize($text); } diff --git a/src/Symfony/Component/Form/FormTypeExtensionInterface.php b/src/Symfony/Component/Form/FormTypeExtensionInterface.php index a8fd086dc8f34..095813d211efd 100644 --- a/src/Symfony/Component/Form/FormTypeExtensionInterface.php +++ b/src/Symfony/Component/Form/FormTypeExtensionInterface.php @@ -62,7 +62,7 @@ public function finishView(FormView $view, FormInterface $form, array $options); /** * Overrides the default options from the extended type. * - * @param OptionsResolverInterface $resolver The resolver for the options. + * @param OptionsResolverInterface $resolver The resolver for the options * * @deprecated since version 2.7, to be removed in 3.0. * Use the method configureOptions instead. This method will be diff --git a/src/Symfony/Component/Form/FormTypeInterface.php b/src/Symfony/Component/Form/FormTypeInterface.php index 83d2181b925a8..0ad9cae7b7e4a 100644 --- a/src/Symfony/Component/Form/FormTypeInterface.php +++ b/src/Symfony/Component/Form/FormTypeInterface.php @@ -71,7 +71,7 @@ public function finishView(FormView $view, FormInterface $form, array $options); /** * Sets the default options for this type. * - * @param OptionsResolverInterface $resolver The resolver for the options. + * @param OptionsResolverInterface $resolver The resolver for the options * * @deprecated since version 2.7, to be renamed in 3.0. * Use the method configureOptions instead. This method will be @@ -90,8 +90,7 @@ public function setDefaultOptions(OptionsResolverInterface $resolver); * Symfony 2.8 and will be unsupported as of Symfony 3.0. Return the * fully-qualified class name of the parent type instead. * - * @return string|null|FormTypeInterface The name of the parent type if any, - * null otherwise. + * @return string|null|FormTypeInterface The name of the parent type if any, null otherwise */ public function getParent(); diff --git a/src/Symfony/Component/Form/FormView.php b/src/Symfony/Component/Form/FormView.php index ac50dc336fffa..4992833e4bda3 100644 --- a/src/Symfony/Component/Form/FormView.php +++ b/src/Symfony/Component/Form/FormView.php @@ -61,7 +61,7 @@ public function __construct(FormView $parent = null) /** * Returns whether the view was already rendered. * - * @return bool Whether this view's widget is rendered. + * @return bool Whether this view's widget is rendered */ public function isRendered() { @@ -87,7 +87,7 @@ public function isRendered() /** * Marks the view as rendered. * - * @return FormView The view object. + * @return FormView The view object */ public function setRendered() { @@ -143,7 +143,7 @@ public function offsetUnset($name) /** * Returns an iterator to iterate over children (implements \IteratorAggregate). * - * @return \ArrayIterator The iterator + * @return \ArrayIterator|FormView[] The iterator */ public function getIterator() { diff --git a/src/Symfony/Component/Form/Forms.php b/src/Symfony/Component/Form/Forms.php index 8ee5c0f23a26a..2a47513f61a25 100644 --- a/src/Symfony/Component/Form/Forms.php +++ b/src/Symfony/Component/Form/Forms.php @@ -104,7 +104,7 @@ final class Forms /** * Creates a form factory with the default configuration. * - * @return FormFactoryInterface The form factory. + * @return FormFactoryInterface The form factory */ public static function createFormFactory() { @@ -114,7 +114,7 @@ public static function createFormFactory() /** * Creates a form factory builder with the default configuration. * - * @return FormFactoryBuilderInterface The form factory builder. + * @return FormFactoryBuilderInterface The form factory builder */ public static function createFormFactoryBuilder() { diff --git a/src/Symfony/Component/Form/NativeRequestHandler.php b/src/Symfony/Component/Form/NativeRequestHandler.php index c9a76858ddf23..36a7d7cff292d 100644 --- a/src/Symfony/Component/Form/NativeRequestHandler.php +++ b/src/Symfony/Component/Form/NativeRequestHandler.php @@ -132,7 +132,7 @@ public function handleRequest(FormInterface $form, $request = null) /** * Returns the method used to submit the request to the server. * - * @return string The request method. + * @return string The request method */ private static function getRequestMethod() { @@ -200,9 +200,9 @@ private static function fixPhpFilesArray($data) /** * Sets empty uploaded files to NULL in the given uploaded files array. * - * @param mixed $data The file upload data. + * @param mixed $data The file upload data * - * @return array|null Returns the stripped upload data. + * @return array|null Returns the stripped upload data */ private static function stripEmptyFiles($data) { diff --git a/src/Symfony/Component/Form/RequestHandlerInterface.php b/src/Symfony/Component/Form/RequestHandlerInterface.php index d0a58e69734c1..598a7bb17438c 100644 --- a/src/Symfony/Component/Form/RequestHandlerInterface.php +++ b/src/Symfony/Component/Form/RequestHandlerInterface.php @@ -21,8 +21,8 @@ interface RequestHandlerInterface /** * Submits a form if it was submitted. * - * @param FormInterface $form The form to submit. - * @param mixed $request The current request. + * @param FormInterface $form The form to submit + * @param mixed $request The current request */ public function handleRequest(FormInterface $form, $request = null); } diff --git a/src/Symfony/Component/Form/ResolvedFormType.php b/src/Symfony/Component/Form/ResolvedFormType.php index d637d223a4631..b86d32a2cf477 100644 --- a/src/Symfony/Component/Form/ResolvedFormType.php +++ b/src/Symfony/Component/Form/ResolvedFormType.php @@ -175,8 +175,8 @@ public function createView(FormInterface $form, FormView $parent = null) /** * Configures a form builder for the type hierarchy. * - * @param FormBuilderInterface $builder The builder to configure. - * @param array $options The options used for the configuration. + * @param FormBuilderInterface $builder The builder to configure + * @param array $options The options used for the configuration */ public function buildForm(FormBuilderInterface $builder, array $options) { @@ -196,9 +196,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) * * This method is called before the children of the view are built. * - * @param FormView $view The form view to configure. - * @param FormInterface $form The form corresponding to the view. - * @param array $options The options used for the configuration. + * @param FormView $view The form view to configure + * @param FormInterface $form The form corresponding to the view + * @param array $options The options used for the configuration */ public function buildView(FormView $view, FormInterface $form, array $options) { @@ -218,9 +218,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) * * This method is called after the children of the view have been built. * - * @param FormView $view The form view to configure. - * @param FormInterface $form The form corresponding to the view. - * @param array $options The options used for the configuration. + * @param FormView $view The form view to configure + * @param FormInterface $form The form corresponding to the view + * @param array $options The options used for the configuration */ public function finishView(FormView $view, FormInterface $form, array $options) { @@ -239,7 +239,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) /** * Returns the configured options resolver used for this type. * - * @return \Symfony\Component\OptionsResolver\OptionsResolverInterface The options resolver. + * @return \Symfony\Component\OptionsResolver\OptionsResolverInterface The options resolver */ public function getOptionsResolver() { @@ -293,12 +293,12 @@ public function getOptionsResolver() * * Override this method if you want to customize the builder class. * - * @param string $name The name of the builder. - * @param string $dataClass The data class. - * @param FormFactoryInterface $factory The current form factory. - * @param array $options The builder options. + * @param string $name The name of the builder + * @param string $dataClass The data class + * @param FormFactoryInterface $factory The current form factory + * @param array $options The builder options * - * @return FormBuilderInterface The new builder instance. + * @return FormBuilderInterface The new builder instance */ protected function newBuilder($name, $dataClass, FormFactoryInterface $factory, array $options) { @@ -318,9 +318,9 @@ protected function newBuilder($name, $dataClass, FormFactoryInterface $factory, * * Override this method if you want to customize the view class. * - * @param FormView|null $parent The parent view, if available. + * @param FormView|null $parent The parent view, if available * - * @return FormView A new view instance. + * @return FormView A new view instance */ protected function newView(FormView $parent = null) { diff --git a/src/Symfony/Component/Form/ResolvedFormTypeInterface.php b/src/Symfony/Component/Form/ResolvedFormTypeInterface.php index e6a61c753b571..1601ef62c2ce6 100644 --- a/src/Symfony/Component/Form/ResolvedFormTypeInterface.php +++ b/src/Symfony/Component/Form/ResolvedFormTypeInterface.php @@ -23,57 +23,57 @@ interface ResolvedFormTypeInterface /** * Returns the name of the type. * - * @return string The type name. + * @return string The type name */ public function getName(); /** * Returns the parent type. * - * @return ResolvedFormTypeInterface|null The parent type or null. + * @return ResolvedFormTypeInterface|null The parent type or null */ public function getParent(); /** * Returns the wrapped form type. * - * @return FormTypeInterface The wrapped form type. + * @return FormTypeInterface The wrapped form type */ public function getInnerType(); /** * Returns the extensions of the wrapped form type. * - * @return FormTypeExtensionInterface[] An array of {@link FormTypeExtensionInterface} instances. + * @return FormTypeExtensionInterface[] An array of {@link FormTypeExtensionInterface} instances */ public function getTypeExtensions(); /** * Creates a new form builder for this type. * - * @param FormFactoryInterface $factory The form factory. - * @param string $name The name for the builder. - * @param array $options The builder options. + * @param FormFactoryInterface $factory The form factory + * @param string $name The name for the builder + * @param array $options The builder options * - * @return FormBuilderInterface The created form builder. + * @return FormBuilderInterface The created form builder */ public function createBuilder(FormFactoryInterface $factory, $name, array $options = array()); /** * Creates a new form view for a form of this type. * - * @param FormInterface $form The form to create a view for. - * @param FormView $parent The parent view or null. + * @param FormInterface $form The form to create a view for + * @param FormView $parent The parent view or null * - * @return FormView The created form view. + * @return FormView The created form view */ public function createView(FormInterface $form, FormView $parent = null); /** * Configures a form builder for the type hierarchy. * - * @param FormBuilderInterface $builder The builder to configure. - * @param array $options The options used for the configuration. + * @param FormBuilderInterface $builder The builder to configure + * @param array $options The options used for the configuration */ public function buildForm(FormBuilderInterface $builder, array $options); @@ -82,9 +82,9 @@ public function buildForm(FormBuilderInterface $builder, array $options); * * It is called before the children of the view are built. * - * @param FormView $view The form view to configure. - * @param FormInterface $form The form corresponding to the view. - * @param array $options The options used for the configuration. + * @param FormView $view The form view to configure + * @param FormInterface $form The form corresponding to the view + * @param array $options The options used for the configuration */ public function buildView(FormView $view, FormInterface $form, array $options); @@ -93,16 +93,16 @@ public function buildView(FormView $view, FormInterface $form, array $options); * * It is called after the children of the view have been built. * - * @param FormView $view The form view to configure. - * @param FormInterface $form The form corresponding to the view. - * @param array $options The options used for the configuration. + * @param FormView $view The form view to configure + * @param FormInterface $form The form corresponding to the view + * @param array $options The options used for the configuration */ public function finishView(FormView $view, FormInterface $form, array $options); /** * Returns the configured options resolver used for this type. * - * @return OptionsResolverInterface The options resolver. + * @return OptionsResolverInterface The options resolver */ public function getOptionsResolver(); } diff --git a/src/Symfony/Component/Form/SubmitButton.php b/src/Symfony/Component/Form/SubmitButton.php index e95cdeeff7b73..53ff7bc311cb1 100644 --- a/src/Symfony/Component/Form/SubmitButton.php +++ b/src/Symfony/Component/Form/SubmitButton.php @@ -34,8 +34,8 @@ public function isClicked() /** * Submits data to the button. * - * @param null|string $submittedData The data. - * @param bool $clearMissing Not used. + * @param null|string $submittedData The data + * @param bool $clearMissing Not used * * @return SubmitButton The button instance * diff --git a/src/Symfony/Component/Form/Test/TypeTestCase.php b/src/Symfony/Component/Form/Test/TypeTestCase.php index 87797757ff3de..a1e360de11915 100644 --- a/src/Symfony/Component/Form/Test/TypeTestCase.php +++ b/src/Symfony/Component/Form/Test/TypeTestCase.php @@ -30,7 +30,7 @@ protected function setUp() { parent::setUp(); - $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); + $this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock(); $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory); } diff --git a/src/Symfony/Component/Form/Tests/AbstractBootstrap3LayoutTest.php b/src/Symfony/Component/Form/Tests/AbstractBootstrap3LayoutTest.php index bc235a5c4218e..9522a47e5124b 100644 --- a/src/Symfony/Component/Form/Tests/AbstractBootstrap3LayoutTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractBootstrap3LayoutTest.php @@ -232,6 +232,68 @@ public function testSingleChoice() ); } + public function testSingleChoiceAttributesWithMainAttributes() + { + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', array( + 'choices' => array('Choice&A' => '&a', 'Choice&B' => '&b'), + 'choices_as_values' => true, + 'multiple' => false, + 'expanded' => false, + 'attr' => array('class' => 'bar&baz'), + )); + + $this->assertWidgetMatchesXpath($form->createView(), array('attr' => array('class' => 'bar&baz')), +'/select + [@name="name"] + [@class="bar&baz form-control"] + [not(@required)] + [ + ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] + /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] + ] + [count(./option)=2] +' + ); + } + + public function testSingleExpandedChoiceAttributesWithMainAttributes() + { + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', array( + 'choices' => array('Choice&A' => '&a', 'Choice&B' => '&b'), + 'choices_as_values' => true, + 'multiple' => false, + 'expanded' => true, + 'attr' => array('class' => 'bar&baz'), + )); + + $this->assertWidgetMatchesXpath($form->createView(), array('attr' => array('class' => 'bar&baz')), +'/div + [@class="bar&baz"] + [ + ./div + [@class="radio"] + [ + ./label + [.=" [trans]Choice&A[/trans]"] + [ + ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] + ] + ] + /following-sibling::div + [@class="radio"] + [ + ./label + [.=" [trans]Choice&B[/trans]"] + [ + ./input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] + ] + ] + /following-sibling::input[@type="hidden"][@id="name__token"] + ] +' + ); + } + public function testSelectWithSizeBiggerThanOneCanBeRequired() { $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array( diff --git a/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php b/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php index 953555724af2f..7eeaf53decd09 100644 --- a/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractLayoutTest.php @@ -641,6 +641,55 @@ public function testSingleChoiceAttributes() ); } + public function testSingleChoiceAttributesWithMainAttributes() + { + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', array( + 'choices' => array('Choice&A' => '&a', 'Choice&B' => '&b'), + 'choices_as_values' => true, + 'multiple' => false, + 'expanded' => false, + 'attr' => array('class' => 'bar&baz'), + )); + + $this->assertWidgetMatchesXpath($form->createView(), array('attr' => array('class' => 'bar&baz')), +'/select + [@name="name"] + [@class="bar&baz"] + [not(@required)] + [ + ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] + /following-sibling::option[@value="&b"][not(@class)][not(@selected)][.="[trans]Choice&B[/trans]"] + ] + [count(./option)=2] +' + ); + } + + public function testSingleExpandedChoiceAttributesWithMainAttributes() + { + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', array( + 'choices' => array('Choice&A' => '&a', 'Choice&B' => '&b'), + 'choices_as_values' => true, + 'multiple' => false, + 'expanded' => true, + 'attr' => array('class' => 'bar&baz'), + )); + + $this->assertWidgetMatchesXpath($form->createView(), array('attr' => array('class' => 'bar&baz')), +'/div + [@class="bar&baz"] + [ + ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] + /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] + /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] + /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] + /following-sibling::input[@type="hidden"][@id="name__token"] + ] + [count(./input)=3] +' + ); + } + public function testSingleChoiceWithPreferred() { $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', array( diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php index d6fe4edd31f0b..5eb01a2ccb63a 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php @@ -68,7 +68,7 @@ public function testReverseTransform() $this->assertSame($out, $this->transformer->reverseTransform($in)); // values are expected to be valid choices and stay the same - $inWithNull = array('0','1','2','3'); + $inWithNull = array('0', '1', '2', '3'); $out[] = null; $this->assertSame($out, $this->transformerWithNull->reverseTransform($inWithNull)); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php index 02f64e37e87d3..a031926f1b792 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -683,6 +683,66 @@ public function testSubmitSingleNonExpandedObjectChoices() $this->assertTrue($form->isSynchronized()); } + public function testSubmitSingleChoiceWithEmptyData() + { + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array( + 'multiple' => false, + 'expanded' => false, + 'choices' => array('test'), + 'choices_as_values' => true, + 'empty_data' => 'test', + )); + + $form->submit(null); + + $this->assertSame('test', $form->getData()); + } + + public function testSubmitMultipleChoiceWithEmptyData() + { + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array( + 'multiple' => true, + 'expanded' => false, + 'choices' => array('test'), + 'choices_as_values' => true, + 'empty_data' => array('test'), + )); + + $form->submit(null); + + $this->assertSame(array('test'), $form->getData()); + } + + public function testSubmitSingleChoiceExpandedWithEmptyData() + { + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array( + 'multiple' => false, + 'expanded' => true, + 'choices' => array('test'), + 'choices_as_values' => true, + 'empty_data' => 'test', + )); + + $form->submit(null); + + $this->assertSame('test', $form->getData()); + } + + public function testSubmitMultipleChoiceExpandedWithEmptyData() + { + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array( + 'multiple' => true, + 'expanded' => true, + 'choices' => array('test'), + 'choices_as_values' => true, + 'empty_data' => array('test'), + )); + + $form->submit(null); + + $this->assertSame(array('test'), $form->getData()); + } + /** * @group legacy */ diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php new file mode 100644 index 0000000000000..95a11a78c71ce --- /dev/null +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\Extension\Validator\Type; + +use Symfony\Component\Form\Extension\Validator\Type\UploadValidatorExtension; +use Symfony\Component\OptionsResolver\OptionsResolver; + +class UploadValidatorExtensionTest extends TypeTestCase +{ + public function testPostMaxSizeTranslation() + { + $translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface'); + + $translator->expects($this->any()) + ->method('trans') + ->with($this->equalTo('old max {{ max }}!')) + ->willReturn('translated max {{ max }}!'); + + $extension = new UploadValidatorExtension($translator); + + $resolver = new OptionsResolver(); + $resolver->setDefault('post_max_size_message', 'old max {{ max }}!'); + + $extension->configureOptions($resolver); + $options = $resolver->resolve(); + + $this->assertEquals('translated max {{ max }}!', $options['post_max_size_message']); + } +} diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php index 74da4aee1c281..9aa75adaeda22 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php @@ -212,7 +212,7 @@ public function testAbortDotRuleMappingIfNotSynchronized() $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one'); } - public function testAbortMappingIfNotSubmitted() + public function testMappingIfNotSubmitted() { $violation = $this->getConstraintViolation('children[address].data.street'); $parent = $this->getForm('parent'); @@ -230,12 +230,12 @@ public function testAbortMappingIfNotSubmitted() $this->mapper->mapViolation($violation, $parent); - $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one'); - $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one'); - $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one'); + $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error'); + $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error'); + $this->assertCount(1, $grandChild->getErrors(), $grandChild->getName().' should have one error'); } - public function testAbortDotRuleMappingIfNotSubmitted() + public function testDotRuleMappingIfNotSubmitted() { $violation = $this->getConstraintViolation('data.address'); $parent = $this->getForm('parent'); @@ -255,9 +255,9 @@ public function testAbortDotRuleMappingIfNotSubmitted() $this->mapper->mapViolation($violation, $parent); - $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one'); - $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one'); - $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one'); + $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error'); + $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error'); + $this->assertCount(1, $grandChild->getErrors(), $grandChild->getName().' should have an error'); } public function provideDefaultTests() diff --git a/src/Symfony/Component/Form/Util/OrderedHashMap.php b/src/Symfony/Component/Form/Util/OrderedHashMap.php index 2ba53e26101d4..3aaa7d0451f1f 100644 --- a/src/Symfony/Component/Form/Util/OrderedHashMap.php +++ b/src/Symfony/Component/Form/Util/OrderedHashMap.php @@ -92,7 +92,7 @@ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable /** * Creates a new map. * - * @param array $elements The elements to insert initially. + * @param array $elements The elements to insert initially * * @since 2.2.6 */ diff --git a/src/Symfony/Component/Form/Util/ServerParams.php b/src/Symfony/Component/Form/Util/ServerParams.php index d5367d9163c06..c4da49db842fd 100644 --- a/src/Symfony/Component/Form/Util/ServerParams.php +++ b/src/Symfony/Component/Form/Util/ServerParams.php @@ -70,7 +70,7 @@ public function getNormalizedIniPostMaxSize() /** * Returns the content length of the request. * - * @return mixed The request content length. + * @return mixed The request content length */ public function getContentLength() { diff --git a/src/Symfony/Component/HttpFoundation/Exception/ConflictingHeadersException.php b/src/Symfony/Component/HttpFoundation/Exception/ConflictingHeadersException.php new file mode 100644 index 0000000000000..fa5f1c7873270 --- /dev/null +++ b/src/Symfony/Component/HttpFoundation/Exception/ConflictingHeadersException.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Exception; + +/** + * The HTTP request contains headers with conflicting information. + * + * This exception should trigger an HTTP 400 response in your application code. + * + * @author Magnus Nordlander + */ +class ConflictingHeadersException extends \RuntimeException +{ +} diff --git a/src/Symfony/Component/HttpFoundation/File/File.php b/src/Symfony/Component/HttpFoundation/File/File.php index f1b28b4b7d524..4736b45c34839 100644 --- a/src/Symfony/Component/HttpFoundation/File/File.php +++ b/src/Symfony/Component/HttpFoundation/File/File.php @@ -68,7 +68,7 @@ public function guessExtension() * mime_content_type() and the system binary "file" (in this order), depending on * which of those are available. * - * @return string|null The guessed mime type (i.e. "application/pdf") + * @return string|null The guessed mime type (e.g. "application/pdf") * * @see MimeTypeGuesser */ diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeExtensionGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeExtensionGuesser.php index 75eeefbf5d780..17fd344b8437c 100644 --- a/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeExtensionGuesser.php +++ b/src/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeExtensionGuesser.php @@ -661,6 +661,7 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'image/gif' => 'gif', 'image/ief' => 'ief', 'image/jpeg' => 'jpeg', + 'image/pjpeg' => 'jpeg', 'image/ktx' => 'ktx', 'image/png' => 'png', 'image/prs.btif' => 'btif', diff --git a/src/Symfony/Component/HttpFoundation/File/UploadedFile.php b/src/Symfony/Component/HttpFoundation/File/UploadedFile.php index ace70db905340..10837726cde5c 100644 --- a/src/Symfony/Component/HttpFoundation/File/UploadedFile.php +++ b/src/Symfony/Component/HttpFoundation/File/UploadedFile.php @@ -194,7 +194,7 @@ public function getError() /** * Returns whether the file was uploaded successfully. * - * @return bool True if the file has been uploaded with HTTP and no error occurred. + * @return bool True if the file has been uploaded with HTTP and no error occurred */ public function isValid() { diff --git a/src/Symfony/Component/HttpFoundation/IpUtils.php b/src/Symfony/Component/HttpFoundation/IpUtils.php index f2cf356e5c3a1..82461d015960f 100644 --- a/src/Symfony/Component/HttpFoundation/IpUtils.php +++ b/src/Symfony/Component/HttpFoundation/IpUtils.php @@ -57,7 +57,7 @@ public static function checkIp($requestIp, $ips) * @param string $requestIp IPv4 address to check * @param string $ip IPv4 address or subnet in CIDR notation * - * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet. + * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet */ public static function checkIp4($requestIp, $ip) { diff --git a/src/Symfony/Component/HttpFoundation/ParameterBag.php b/src/Symfony/Component/HttpFoundation/ParameterBag.php index 9400c1b7e4c61..ef13494ee00b1 100644 --- a/src/Symfony/Component/HttpFoundation/ParameterBag.php +++ b/src/Symfony/Component/HttpFoundation/ParameterBag.php @@ -248,11 +248,11 @@ public function getBoolean($key, $default = false, $deep = false) /** * Filter key. * - * @param string $key Key. - * @param mixed $default Default = null. - * @param int $filter FILTER_* constant. - * @param mixed $options Filter options. - * @param bool $deep Default = false. + * @param string $key Key + * @param mixed $default Default = null + * @param int $filter FILTER_* constant + * @param mixed $options Filter options + * @param bool $deep Default = false * * @see http://php.net/manual/en/function.filter-var.php * diff --git a/src/Symfony/Component/HttpFoundation/RedirectResponse.php b/src/Symfony/Component/HttpFoundation/RedirectResponse.php index 18d5794c0bf34..8d2608336afad 100644 --- a/src/Symfony/Component/HttpFoundation/RedirectResponse.php +++ b/src/Symfony/Component/HttpFoundation/RedirectResponse.php @@ -66,7 +66,7 @@ public function getTargetUrl() * * @param string $url The URL to redirect to * - * @return RedirectResponse The current response. + * @return RedirectResponse The current response * * @throws \InvalidArgumentException */ diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index d7f95e3c4bd54..16a9375e91b2e 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpFoundation; +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; use Symfony\Component\HttpFoundation\Session\SessionInterface; /** @@ -553,7 +554,7 @@ public static function setTrustedProxies(array $proxies) /** * Gets the list of trusted proxies. * - * @return array An array of trusted proxies. + * @return array An array of trusted proxies */ public static function getTrustedProxies() { @@ -579,7 +580,7 @@ public static function setTrustedHosts(array $hostPatterns) /** * Gets the list of trusted host patterns. * - * @return array An array of trusted host patterns. + * @return array An array of trusted host patterns */ public static function getTrustedHosts() { @@ -811,41 +812,34 @@ public function getClientIps() return array($ip); } - if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { + $hasTrustedForwardedHeader = self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED]); + $hasTrustedClientIpHeader = self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP]); + + if ($hasTrustedForwardedHeader) { $forwardedHeader = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); preg_match_all('{(for)=("?\[?)([a-z0-9\.:_\-/]*)}', $forwardedHeader, $matches); - $clientIps = $matches[3]; - } elseif (self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) { - $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP]))); - } + $forwardedClientIps = $matches[3]; - $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from - $firstTrustedIp = null; - - foreach ($clientIps as $key => $clientIp) { - // Remove port (unfortunately, it does happen) - if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) { - $clientIps[$key] = $clientIp = $match[1]; - } + $forwardedClientIps = $this->normalizeAndFilterClientIps($forwardedClientIps, $ip); + $clientIps = $forwardedClientIps; + } - if (!filter_var($clientIp, FILTER_VALIDATE_IP)) { - unset($clientIps[$key]); + if ($hasTrustedClientIpHeader) { + $xForwardedForClientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP]))); - continue; - } + $xForwardedForClientIps = $this->normalizeAndFilterClientIps($xForwardedForClientIps, $ip); + $clientIps = $xForwardedForClientIps; + } - if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { - unset($clientIps[$key]); + if ($hasTrustedForwardedHeader && $hasTrustedClientIpHeader && $forwardedClientIps !== $xForwardedForClientIps) { + throw new ConflictingHeadersException('The request has both a trusted Forwarded header and a trusted Client IP header, conflicting with each other with regards to the originating IP addresses of the request. This is the result of a misconfiguration. You should either configure your proxy only to send one of these headers, or configure Symfony to distrust one of them.'); + } - // Fallback to this when the client IP falls into the range of trusted proxies - if (null === $firstTrustedIp) { - $firstTrustedIp = $clientIp; - } - } + if (!$hasTrustedForwardedHeader && !$hasTrustedClientIpHeader) { + return $this->normalizeAndFilterClientIps(array(), $ip); } - // Now the IP chain contains only untrusted proxies and the client IP - return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp); + return $clientIps; } /** @@ -1402,7 +1396,7 @@ public function getRequestFormat($default = 'html') /** * Sets the request format. * - * @param string $format The request format. + * @param string $format The request format */ public function setRequestFormat($format) { @@ -1466,7 +1460,7 @@ public function getLocale() /** * Checks if the request method is of specified type. * - * @param string $method Uppercase request method (GET, POST etc). + * @param string $method Uppercase request method (GET, POST etc) * * @return bool */ @@ -1490,7 +1484,7 @@ public function isMethodSafe() * * @param bool $asResource If true, a resource will be returned * - * @return string|resource The request body content or a resource to read the body stream. + * @return string|resource The request body content or a resource to read the body stream * * @throws \LogicException */ @@ -1936,4 +1930,35 @@ private function isFromTrustedProxy() { return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies); } + + private function normalizeAndFilterClientIps(array $clientIps, $ip) + { + $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from + $firstTrustedIp = null; + + foreach ($clientIps as $key => $clientIp) { + // Remove port (unfortunately, it does happen) + if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) { + $clientIps[$key] = $clientIp = $match[1]; + } + + if (!filter_var($clientIp, FILTER_VALIDATE_IP)) { + unset($clientIps[$key]); + + continue; + } + + if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { + unset($clientIps[$key]); + + // Fallback to this when the client IP falls into the range of trusted proxies + if (null === $firstTrustedIp) { + $firstTrustedIp = $clientIp; + } + } + } + + // Now the IP chain contains only untrusted proxies and the client IP + return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp); + } } diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php index b2c12ef381202..bc3ab23de2f2e 100644 --- a/src/Symfony/Component/HttpFoundation/Response.php +++ b/src/Symfony/Component/HttpFoundation/Response.php @@ -258,7 +258,7 @@ public function __clone() * * @param Request $request A Request instance * - * @return Response The current response. + * @return Response The current response */ public function prepare(Request $request) { @@ -373,12 +373,6 @@ public function send() $this->sendHeaders(); $this->sendContent(); - if (function_exists('fastcgi_finish_request')) { - fastcgi_finish_request(); - } elseif ('cli' !== PHP_SAPI) { - static::closeOutputBuffers(0, true); - } - return $this; } diff --git a/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php b/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php index 1d26e86b9b17b..3223691eb6fe4 100644 --- a/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php +++ b/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php @@ -230,7 +230,7 @@ public function clearCookie($name, $path = '/', $domain = null, $secure = false, * is semantically equivalent to $filename. If the filename is already ASCII, * it can be omitted, or just copied from $filename * - * @return string A string suitable for use as a Content-Disposition field-value. + * @return string A string suitable for use as a Content-Disposition field-value * * @throws \InvalidArgumentException * diff --git a/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php b/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php index 68cecf63d5ced..d797a6f23886e 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php @@ -29,8 +29,8 @@ class NamespacedAttributeBag extends AttributeBag /** * Constructor. * - * @param string $storageKey Session storage key. - * @param string $namespaceCharacter Namespace character to use in keys. + * @param string $storageKey Session storage key + * @param string $namespaceCharacter Namespace character to use in keys */ public function __construct($storageKey = '_sf2_attributes', $namespaceCharacter = '/') { diff --git a/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php b/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php index b9de5ceb3818d..ddd603fdd1efb 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Flash/AutoExpireFlashBag.php @@ -37,7 +37,7 @@ class AutoExpireFlashBag implements FlashBagInterface /** * Constructor. * - * @param string $storageKey The key used to store flashes in the session. + * @param string $storageKey The key used to store flashes in the session */ public function __construct($storageKey = '_sf2_flashes') { diff --git a/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php b/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php index 0da77150944a2..1516de7fe92ef 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBag.php @@ -39,7 +39,7 @@ class FlashBag implements FlashBagInterface, \IteratorAggregate /** * Constructor. * - * @param string $storageKey The key used to store flashes in the session. + * @param string $storageKey The key used to store flashes in the session */ public function __construct($storageKey = '_sf2_flashes') { diff --git a/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBagInterface.php b/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBagInterface.php index be79d9d752a46..80e97f17cdff3 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBagInterface.php +++ b/src/Symfony/Component/HttpFoundation/Session/Flash/FlashBagInterface.php @@ -39,8 +39,8 @@ public function set($type, $message); /** * Gets flash messages for a given type. * - * @param string $type Message category type. - * @param array $default Default value if $type does not exist. + * @param string $type Message category type + * @param array $default Default value if $type does not exist * * @return array */ @@ -57,7 +57,7 @@ public function peekAll(); * Gets and clears flash from the stack. * * @param string $type - * @param array $default Default value if $type does not exist. + * @param array $default Default value if $type does not exist * * @return array */ diff --git a/src/Symfony/Component/HttpFoundation/Session/Session.php b/src/Symfony/Component/HttpFoundation/Session/Session.php index b743fe1b19aed..cdd97375b9054 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Session.php +++ b/src/Symfony/Component/HttpFoundation/Session/Session.php @@ -46,7 +46,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable /** * Constructor. * - * @param SessionStorageInterface $storage A SessionStorageInterface instance. + * @param SessionStorageInterface $storage A SessionStorageInterface instance * @param AttributeBagInterface $attributes An AttributeBagInterface instance, (defaults null for default AttributeBag) * @param FlashBagInterface $flashes A FlashBagInterface instance (defaults null for default FlashBag) */ diff --git a/src/Symfony/Component/HttpFoundation/Session/SessionBagInterface.php b/src/Symfony/Component/HttpFoundation/Session/SessionBagInterface.php index 182a47d96a0da..aca18aacbf89f 100644 --- a/src/Symfony/Component/HttpFoundation/Session/SessionBagInterface.php +++ b/src/Symfony/Component/HttpFoundation/Session/SessionBagInterface.php @@ -42,7 +42,7 @@ public function getStorageKey(); /** * Clears out data from bag. * - * @return mixed Whatever data was contained. + * @return mixed Whatever data was contained */ public function clear(); } diff --git a/src/Symfony/Component/HttpFoundation/Session/SessionInterface.php b/src/Symfony/Component/HttpFoundation/Session/SessionInterface.php index e2b658413dbc9..d3fcd2eec4e73 100644 --- a/src/Symfony/Component/HttpFoundation/Session/SessionInterface.php +++ b/src/Symfony/Component/HttpFoundation/Session/SessionInterface.php @@ -23,7 +23,7 @@ interface SessionInterface /** * Starts the session storage. * - * @return bool True if session started. + * @return bool True if session started * * @throws \RuntimeException If session fails to start. */ @@ -32,7 +32,7 @@ public function start(); /** * Returns the session ID. * - * @return string The session ID. + * @return string The session ID */ public function getId(); @@ -46,7 +46,7 @@ public function setId($id); /** * Returns the session name. * - * @return mixed The session name. + * @return mixed The session name */ public function getName(); @@ -68,7 +68,7 @@ public function setName($name); * to expire with browser session. Time is in seconds, and is * not a Unix timestamp. * - * @return bool True if session invalidated, false if error. + * @return bool True if session invalidated, false if error */ public function invalidate($lifetime = null); @@ -76,13 +76,13 @@ public function invalidate($lifetime = null); * Migrates the current session to a new session id while maintaining all * session attributes. * - * @param bool $destroy Whether to delete the old session or leave it to garbage collection. + * @param bool $destroy Whether to delete the old session or leave it to garbage collection * @param int $lifetime Sets the cookie lifetime for the session cookie. A null value * will leave the system settings unchanged, 0 sets the cookie * to expire with browser session. Time is in seconds, and is * not a Unix timestamp. * - * @return bool True if session migrated, false if error. + * @return bool True if session migrated, false if error */ public function migrate($destroy = false, $lifetime = null); @@ -108,7 +108,7 @@ public function has($name); * Returns an attribute. * * @param string $name The attribute name - * @param mixed $default The default value if not found. + * @param mixed $default The default value if not found * * @return mixed */ diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcacheSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcacheSessionHandler.php index f6f99eda48c1b..a386bdd184e43 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcacheSessionHandler.php @@ -19,7 +19,7 @@ class MemcacheSessionHandler implements \SessionHandlerInterface { /** - * @var \Memcache Memcache driver. + * @var \Memcache Memcache driver */ private $memcache; @@ -29,7 +29,7 @@ class MemcacheSessionHandler implements \SessionHandlerInterface private $ttl; /** - * @var string Key prefix for shared environments. + * @var string Key prefix for shared environments */ private $prefix; diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php index d87bef852f9a3..76b08e2db944c 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php @@ -24,7 +24,7 @@ class MemcachedSessionHandler implements \SessionHandlerInterface { /** - * @var \Memcached Memcached driver. + * @var \Memcached Memcached driver */ private $memcached; @@ -34,7 +34,7 @@ class MemcachedSessionHandler implements \SessionHandlerInterface private $ttl; /** - * @var string Key prefix for shared environments. + * @var string Key prefix for shared environments */ private $prefix; diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php index c00835d7977dd..1be0a39837333 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/NativeFileSessionHandler.php @@ -23,7 +23,7 @@ class NativeFileSessionHandler extends NativeSessionHandler /** * Constructor. * - * @param string $savePath Path of directory to save session files. + * @param string $savePath Path of directory to save session files * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path * diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php index 48e81ee0f1d30..8909a5f401fdc 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php @@ -325,14 +325,8 @@ public function write($sessionId, $data) try { // We use a single MERGE SQL query when supported by the database. - $mergeSql = $this->getMergeSql(); - - if (null !== $mergeSql) { - $mergeStmt = $this->pdo->prepare($mergeSql); - $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); - $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); - $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime); + if (null !== $mergeStmt) { $mergeStmt->execute(); return true; @@ -347,7 +341,7 @@ public function write($sessionId, $data) $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); $updateStmt->execute(); - // When MERGE is not supported, like in Postgres, we have to use this approach that can result in + // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior). // We can just catch such an error and re-execute the update. This is similar to a serializable // transaction with retry logic on serialization failures but without the overhead and without possible @@ -510,54 +504,51 @@ private function doRead($sessionId) $selectSql = $this->getSelectSql(); $selectStmt = $this->pdo->prepare($selectSql); $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $selectStmt->execute(); - $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); + do { + $selectStmt->execute(); + $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); - if ($sessionRows) { - if ($sessionRows[0][1] + $sessionRows[0][2] < time()) { - $this->sessionExpired = true; + if ($sessionRows) { + if ($sessionRows[0][1] + $sessionRows[0][2] < time()) { + $this->sessionExpired = true; - return ''; - } + return ''; + } - return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; - } + return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; + } - if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { - // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block - // until other connections to the session are committed. - try { - $insertStmt = $this->pdo->prepare( - "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)" - ); - $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB); - $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT); - $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); - $insertStmt->execute(); - } catch (\PDOException $e) { - // Catch duplicate key error because other connection created the session already. - // It would only not be the case when the other connection destroyed the session. - if (0 === strpos($e->getCode(), '23')) { - // Retrieve finished session data written by concurrent connection. SELECT - // FOR UPDATE is necessary to avoid deadlock of connection that starts reading - // before we write (transform intention to real lock). - $selectStmt->execute(); - $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); - - if ($sessionRows) { - return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; + if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { + // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block + // until other connections to the session are committed. + try { + $insertStmt = $this->pdo->prepare( + "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)" + ); + $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB); + $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT); + $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $insertStmt->execute(); + } catch (\PDOException $e) { + // Catch duplicate key error because other connection created the session already. + // It would only not be the case when the other connection destroyed the session. + if (0 === strpos($e->getCode(), '23')) { + // Retrieve finished session data written by concurrent connection by restarting the loop. + // We have to start a new transaction as a failed query will mark the current transaction as + // aborted in PostgreSQL and disallow further queries within it. + $this->rollback(); + $this->beginTransaction(); + continue; } - return ''; + throw $e; } - - throw $e; } - } - return ''; + return ''; + } while (true); } /** @@ -653,29 +644,64 @@ private function getSelectSql() } /** - * Returns a merge/upsert (i.e. insert or update) SQL query when supported by the database for writing session data. + * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data. * - * @return string|null The SQL string or null when not supported + * @param string $sessionId Session ID + * @param string $data Encoded session data + * @param int $maxlifetime session.gc_maxlifetime + * + * @return \PDOStatement|null The merge statement or null when not supported */ - private function getMergeSql() + private function getMergeStatement($sessionId, $data, $maxlifetime) { - switch ($this->driver) { - case 'mysql': - return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". + $mergeSql = null; + switch (true) { + case 'mysql' === $this->driver: + $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)"; - case 'oci': + break; + case 'oci' === $this->driver: // DUAL is Oracle specific dummy table - return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) ". - "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". - "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time"; + $mergeSql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ". + "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". + "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?"; + break; case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): // MERGE is only available since SQL Server 2008 and must be terminated by semicolon // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx - return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = :id) ". - "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". - "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time;"; - case 'sqlite': - return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"; + $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ". + "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". + "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;"; + break; + case 'sqlite' === $this->driver: + $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"; + break; + case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='): + $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". + "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; + break; + } + + if (null !== $mergeSql) { + $mergeStmt = $this->pdo->prepare($mergeSql); + + if ('sqlsrv' === $this->driver || 'oci' === $this->driver) { + $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB); + $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT); + $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB); + $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT); + } else { + $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); + } + + return $mergeStmt; } } diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/MetadataBag.php b/src/Symfony/Component/HttpFoundation/Session/Storage/MetadataBag.php index ec7b26799a5fc..322dd560f8087 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/MetadataBag.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/MetadataBag.php @@ -56,7 +56,7 @@ class MetadataBag implements SessionBagInterface /** * Constructor. * - * @param string $storageKey The key used to store bag in the session. + * @param string $storageKey The key used to store bag in the session * @param int $updateThreshold The time to wait between two UPDATED updates */ public function __construct($storageKey = '_sf2_meta', $updateThreshold = 0) diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php index bc1373755ad55..c26cc1334d6aa 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/MockArraySessionStorage.php @@ -66,7 +66,7 @@ class MockArraySessionStorage implements SessionStorageInterface * Constructor. * * @param string $name Session name - * @param MetadataBag $metaBag MetadataBag instance. + * @param MetadataBag $metaBag MetadataBag instance */ public function __construct($name = 'MOCKSESSID', MetadataBag $metaBag = null) { diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php index 00807cfcb7290..71f9e555121fa 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php @@ -32,9 +32,9 @@ class MockFileSessionStorage extends MockArraySessionStorage /** * Constructor. * - * @param string $savePath Path of directory to save session files. - * @param string $name Session name. - * @param MetadataBag $metaBag MetadataBag instance. + * @param string $savePath Path of directory to save session files + * @param string $name Session name + * @param MetadataBag $metaBag MetadataBag instance */ public function __construct($savePath = null, $name = 'MOCKSESSID', MetadataBag $metaBag = null) { diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php index bfd182d463c16..274b0df6b9e39 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php @@ -92,9 +92,9 @@ class NativeSessionStorage implements SessionStorageInterface * upload_progress.min-freq, "1" * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset=" * - * @param array $options Session configuration options. + * @param array $options Session configuration options * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler - * @param MetadataBag $metaBag MetadataBag. + * @param MetadataBag $metaBag MetadataBag */ public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { @@ -319,7 +319,7 @@ public function isStarted() * For convenience we omit 'session.' from the beginning of the keys. * Explicitly ignores other ini keys. * - * @param array $options Session ini directives array(key => value). + * @param array $options Session ini directives array(key => value) * * @see http://php.net/session.configuration */ diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/NativeProxy.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/NativeProxy.php index 5bb2c712e32ae..0db34aa28d385 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/NativeProxy.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/NativeProxy.php @@ -32,7 +32,7 @@ public function __construct() /** * Returns true if this handler wraps an internal PHP session save handler using \SessionHandler. * - * @return bool False. + * @return bool False */ public function isWrapper() { diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/SessionStorageInterface.php b/src/Symfony/Component/HttpFoundation/Session/Storage/SessionStorageInterface.php index 206f18e77f8d9..34f6c4633f477 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/SessionStorageInterface.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/SessionStorageInterface.php @@ -24,7 +24,7 @@ interface SessionStorageInterface /** * Starts the session. * - * @return bool True if started. + * @return bool True if started * * @throws \RuntimeException If something goes wrong starting the session. */ @@ -33,14 +33,14 @@ public function start(); /** * Checks if the session is started. * - * @return bool True if started, false otherwise. + * @return bool True if started, false otherwise */ public function isStarted(); /** * Returns the session ID. * - * @return string The session ID or empty. + * @return string The session ID or empty */ public function getId(); @@ -54,7 +54,7 @@ public function setId($id); /** * Returns the session name. * - * @return mixed The session name. + * @return mixed The session name */ public function getName(); diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php index 89c4eb2d4272c..1edc48c1b62db 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php @@ -923,6 +923,74 @@ public function testGetClientIpsProvider() ); } + /** + * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException + * @dataProvider testGetClientIpsWithConflictingHeadersProvider + */ + public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor) + { + $request = new Request(); + + $server = array( + 'REMOTE_ADDR' => '88.88.88.88', + 'HTTP_FORWARDED' => $httpForwarded, + 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, + ); + + Request::setTrustedProxies(array('88.88.88.88')); + + $request->initialize(array(), array(), array(), array(), array(), $server); + + $request->getClientIps(); + } + + public function testGetClientIpsWithConflictingHeadersProvider() + { + // $httpForwarded $httpXForwardedFor + return array( + array('for=87.65.43.21', '192.0.2.60'), + array('for=87.65.43.21, for=192.0.2.60', '192.0.2.60'), + array('for=192.0.2.60', '192.0.2.60,87.65.43.21'), + array('for="::face", for=192.0.2.60', '192.0.2.60,192.0.2.43'), + array('for=87.65.43.21, for=192.0.2.60', '192.0.2.60,87.65.43.21'), + ); + } + + /** + * @dataProvider testGetClientIpsWithAgreeingHeadersProvider + */ + public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwardedFor) + { + $request = new Request(); + + $server = array( + 'REMOTE_ADDR' => '88.88.88.88', + 'HTTP_FORWARDED' => $httpForwarded, + 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, + ); + + Request::setTrustedProxies(array('88.88.88.88')); + + $request->initialize(array(), array(), array(), array(), array(), $server); + + $request->getClientIps(); + + Request::setTrustedProxies(array()); + } + + public function testGetClientIpsWithAgreeingHeadersProvider() + { + // $httpForwarded $httpXForwardedFor + return array( + array('for="192.0.2.60"', '192.0.2.60'), + array('for=192.0.2.60, for=87.65.43.21', '192.0.2.60,87.65.43.21'), + array('for="[::face]", for=192.0.2.60', '::face,192.0.2.60'), + array('for="192.0.2.60:80"', '192.0.2.60'), + array('for=192.0.2.60;proto=http;by=203.0.113.43', '192.0.2.60'), + array('for="[2001:db8:cafe::17]:4711"', '2001:db8:cafe::17'), + ); + } + public function testGetContentWorksTwiceInDefaultMode() { $req = new Request(); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 9612320976944..1f88d00d8fe13 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -362,4 +362,8 @@ public function prepare($statement, $driverOptions = array()) public function beginTransaction() { } + + public function rollBack() + { + } } diff --git a/src/Symfony/Component/HttpKernel/CacheClearer/CacheClearerInterface.php b/src/Symfony/Component/HttpKernel/CacheClearer/CacheClearerInterface.php index d4a2db37644ca..675c584234ef3 100644 --- a/src/Symfony/Component/HttpKernel/CacheClearer/CacheClearerInterface.php +++ b/src/Symfony/Component/HttpKernel/CacheClearer/CacheClearerInterface.php @@ -21,7 +21,7 @@ interface CacheClearerInterface /** * Clears any caches necessary. * - * @param string $cacheDir The cache directory. + * @param string $cacheDir The cache directory */ public function clear($cacheDir); } diff --git a/src/Symfony/Component/HttpKernel/CacheClearer/ChainCacheClearer.php b/src/Symfony/Component/HttpKernel/CacheClearer/ChainCacheClearer.php index 81c43b60268ba..c749c7c0a4e47 100644 --- a/src/Symfony/Component/HttpKernel/CacheClearer/ChainCacheClearer.php +++ b/src/Symfony/Component/HttpKernel/CacheClearer/ChainCacheClearer.php @@ -26,7 +26,7 @@ class ChainCacheClearer implements CacheClearerInterface /** * Constructs a new instance of ChainCacheClearer. * - * @param array $clearers The initial clearers. + * @param array $clearers The initial clearers */ public function __construct(array $clearers = array()) { diff --git a/src/Symfony/Component/HttpKernel/EventListener/DumpListener.php b/src/Symfony/Component/HttpKernel/EventListener/DumpListener.php index bccde8eb959fb..2f302f450fcf1 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/DumpListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/DumpListener.php @@ -28,8 +28,8 @@ class DumpListener implements EventSubscriberInterface private $dumper; /** - * @param ClonerInterface $cloner Cloner service. - * @param DataDumperInterface $dumper Dumper service. + * @param ClonerInterface $cloner Cloner service + * @param DataDumperInterface $dumper Dumper service */ public function __construct(ClonerInterface $cloner, DataDumperInterface $dumper) { diff --git a/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php b/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php index 1a90f1ebe7720..1c50ef4acad51 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php @@ -96,10 +96,10 @@ protected function logException(\Exception $exception, $message) /** * Clones the request for the exception. * - * @param \Exception $exception The thrown exception. - * @param Request $request The original request. + * @param \Exception $exception The thrown exception + * @param Request $request The original request * - * @return Request $request The cloned request. + * @return Request $request The cloned request */ protected function duplicateRequest(\Exception $exception, Request $request) { diff --git a/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php b/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php new file mode 100644 index 0000000000000..00096ccf9e4f2 --- /dev/null +++ b/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Validates that the headers and other information indicating the + * client IP address of a request are consistent. + * + * @author Magnus Nordlander + */ +class ValidateRequestListener implements EventSubscriberInterface +{ + /** + * Performs the validation. + * + * @param GetResponseEvent $event + */ + public function onKernelRequest(GetResponseEvent $event) + { + if (!$event->isMasterRequest()) { + return; + } + $request = $event->getRequest(); + + if ($request::getTrustedProxies()) { + // This will throw an exception if the headers are inconsistent. + $request->getClientIps(); + } + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents() + { + return array( + KernelEvents::REQUEST => array( + array('onKernelRequest', 256), + ), + ); + } +} diff --git a/src/Symfony/Component/HttpKernel/HttpCache/Esi.php b/src/Symfony/Component/HttpKernel/HttpCache/Esi.php index bc344c633f2f8..457793953d1f1 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/Esi.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/Esi.php @@ -37,7 +37,7 @@ class Esi implements SurrogateInterface /** * Constructor. * - * @param array $contentTypes An array of content-type that should be parsed for ESI information. + * @param array $contentTypes An array of content-type that should be parsed for ESI information * (default: text/html, text/xml, application/xhtml+xml, and application/xml) */ public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) diff --git a/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php b/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php index 43311b6dc8038..5f7ee10a5bf60 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/Ssi.php @@ -31,7 +31,7 @@ class Ssi implements SurrogateInterface /** * Constructor. * - * @param array $contentTypes An array of content-type that should be parsed for SSI information. + * @param array $contentTypes An array of content-type that should be parsed for SSI information * (default: text/html, text/xml, application/xhtml+xml, and application/xml) */ public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) diff --git a/src/Symfony/Component/HttpKernel/HttpKernel.php b/src/Symfony/Component/HttpKernel/HttpKernel.php index 1600b2ce591dd..4e628a1409beb 100644 --- a/src/Symfony/Component/HttpKernel/HttpKernel.php +++ b/src/Symfony/Component/HttpKernel/HttpKernel.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpKernel; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\Event\FilterControllerEvent; @@ -21,6 +22,7 @@ use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpKernel\Event\PostResponseEvent; +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; @@ -61,6 +63,9 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ try { return $this->handleRaw($request, $type); } catch (\Exception $e) { + if ($e instanceof ConflictingHeadersException) { + $e = new BadRequestHttpException('The request headers contain conflicting information regarding the origin of this request.', $e); + } if (false === $catch) { $this->finishRequest($request, $type); diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index dc5832ed2d505..2032b56120a58 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -59,11 +59,11 @@ abstract class Kernel implements KernelInterface, TerminableInterface protected $startTime; protected $loadClassCache; - const VERSION = '2.8.7'; - const VERSION_ID = 20807; + const VERSION = '2.8.8'; + const VERSION_ID = 20808; const MAJOR_VERSION = 2; const MINOR_VERSION = 8; - const RELEASE_VERSION = 7; + const RELEASE_VERSION = 8; const EXTRA_VERSION = ''; const END_OF_MAINTENANCE = '11/2018'; @@ -150,6 +150,14 @@ public function terminate(Request $request, Response $response) } if ($this->getHttpKernel() instanceof TerminableInterface) { + if (!$this->debug) { + if (function_exists('fastcgi_finish_request')) { + fastcgi_finish_request(); + } elseif ('cli' !== PHP_SAPI) { + Response::closeOutputBuffers(0, true); + } + } + $this->getHttpKernel()->terminate($request, $response); } } diff --git a/src/Symfony/Component/HttpKernel/KernelInterface.php b/src/Symfony/Component/HttpKernel/KernelInterface.php index ee5d27336fc40..37ac3af515a6a 100644 --- a/src/Symfony/Component/HttpKernel/KernelInterface.php +++ b/src/Symfony/Component/HttpKernel/KernelInterface.php @@ -27,7 +27,7 @@ interface KernelInterface extends HttpKernelInterface, \Serializable /** * Returns an array of bundles to register. * - * @return BundleInterface[] An array of bundle instances. + * @return BundleInterface[] An array of bundle instances */ public function registerBundles(); diff --git a/src/Symfony/Component/HttpKernel/Profiler/Profiler.php b/src/Symfony/Component/HttpKernel/Profiler/Profiler.php index 378bf5dac3e8a..18e24c34f3f0c 100644 --- a/src/Symfony/Component/HttpKernel/Profiler/Profiler.php +++ b/src/Symfony/Component/HttpKernel/Profiler/Profiler.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpKernel\Profiler; +use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; @@ -208,9 +209,13 @@ public function collect(Request $request, Response $response, \Exception $except $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6)); $profile->setTime(time()); $profile->setUrl($request->getUri()); - $profile->setIp($request->getClientIp()); $profile->setMethod($request->getMethod()); $profile->setStatusCode($response->getStatusCode()); + try { + $profile->setIp($request->getClientIp()); + } catch (ConflictingHeadersException $e) { + $profile->setIp('Unknown'); + } $response->headers->set('X-Debug-Token', $profile->getToken()); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php new file mode 100644 index 0000000000000..842a3869cba79 --- /dev/null +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/ValidateRequestListenerTest.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Tests\EventListener; + +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener; +use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\KernelEvents; + +class ValidateRequestListenerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @expectedException Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException + */ + public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps() + { + $dispatcher = new EventDispatcher(); + $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); + + $request = new Request(); + $request->setTrustedProxies(array('1.1.1.1')); + $request->server->set('REMOTE_ADDR', '1.1.1.1'); + $request->headers->set('FORWARDED', '2.2.2.2'); + $request->headers->set('X_FORWARDED_FOR', '3.3.3.3'); + + $dispatcher->addListener(KernelEvents::REQUEST, array(new ValidateRequestListener(), 'onKernelRequest')); + $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); + + $dispatcher->dispatch(KernelEvents::REQUEST, $event); + } +} diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php index 97e68f66f979a..372c2a3c1b1ae 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php @@ -271,6 +271,27 @@ public function testVerifyRequestStackPushPopDuringHandle() $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST); } + /** + * @expectedException Symfony\Component\HttpKernel\Exception\BadRequestHttpException + */ + public function testInconsistentClientIpsOnMasterRequests() + { + $dispatcher = new EventDispatcher(); + $dispatcher->addListener(KernelEvents::REQUEST, function ($event) { + $event->getRequest()->getClientIp(); + }); + + $kernel = new HttpKernel($dispatcher, $this->getResolver()); + + $request = new Request(); + $request->setTrustedProxies(array('1.1.1.1')); + $request->server->set('REMOTE_ADDR', '1.1.1.1'); + $request->headers->set('FORWARDED', '2.2.2.2'); + $request->headers->set('X_FORWARDED_FOR', '3.3.3.3'); + + $kernel->handle($request, $kernel::MASTER_REQUEST, false); + } + protected function getResolver($controller = null) { if (null === $controller) { diff --git a/src/Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.php b/src/Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.php index 694dc1e5ba3f4..91222c165b86e 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.php +++ b/src/Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.php @@ -137,7 +137,7 @@ public function get($key) * @param string $key * @param string $value * - * @return int Size of the value after the append. + * @return int Size of the value after the append */ public function append($key, $value) { diff --git a/src/Symfony/Component/HttpKernel/composer.json b/src/Symfony/Component/HttpKernel/composer.json index d0e92d57a666e..3ad45f979f3ad 100644 --- a/src/Symfony/Component/HttpKernel/composer.json +++ b/src/Symfony/Component/HttpKernel/composer.json @@ -18,7 +18,7 @@ "require": { "php": ">=5.3.9", "symfony/event-dispatcher": "~2.6,>=2.6.7|~3.0.0", - "symfony/http-foundation": "~2.5,>=2.5.4|~3.0.0", + "symfony/http-foundation": "~2.7.15|~2.8.8|~3.0.8", "symfony/debug": "~2.6,>=2.6.2", "psr/log": "~1.0" }, diff --git a/src/Symfony/Component/Intl/Collator/Collator.php b/src/Symfony/Component/Intl/Collator/Collator.php index 7482aaa26f311..95f2ac23f59ad 100644 --- a/src/Symfony/Component/Intl/Collator/Collator.php +++ b/src/Symfony/Component/Intl/Collator/Collator.php @@ -72,7 +72,7 @@ class Collator /** * Constructor. * - * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en"). + * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en") * * @throws MethodArgumentValueNotImplementedException When $locale different than "en" or null is passed */ @@ -86,7 +86,7 @@ public function __construct($locale) /** * Static constructor. * - * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en"). + * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en") * * @return Collator * diff --git a/src/Symfony/Component/Intl/Data/Bundle/Compiler/GenrbCompiler.php b/src/Symfony/Component/Intl/Data/Bundle/Compiler/GenrbCompiler.php index cf8ee1a74b5ba..9a91888cf57cf 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Compiler/GenrbCompiler.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Compiler/GenrbCompiler.php @@ -23,14 +23,14 @@ class GenrbCompiler implements BundleCompilerInterface { /** - * @var string The path to the "genrb" executable. + * @var string The path to the "genrb" executable */ private $genrb; /** * Creates a new compiler based on the "genrb" executable. * - * @param string $genrb Optional. The path to the "genrb" executable. + * @param string $genrb Optional. The path to the "genrb" executable * @param string $envVars Optional. Environment variables to be loaded when * running "genrb". * diff --git a/src/Symfony/Component/Intl/Data/Bundle/Reader/BufferedBundleReader.php b/src/Symfony/Component/Intl/Data/Bundle/Reader/BufferedBundleReader.php index fede9cdb4a51d..ff04294683e32 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Reader/BufferedBundleReader.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Reader/BufferedBundleReader.php @@ -30,7 +30,7 @@ class BufferedBundleReader implements BundleReaderInterface /** * Buffers a given reader. * - * @param BundleReaderInterface $reader The reader to buffer. + * @param BundleReaderInterface $reader The reader to buffer * @param int $bufferSize The number of entries to store * in the buffer. */ diff --git a/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReader.php b/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReader.php index 5f991bfe288e8..3cf969bab8134 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReader.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReader.php @@ -43,7 +43,7 @@ class BundleEntryReader implements BundleEntryReaderInterface /** * Creates an entry reader based on the given resource bundle reader. * - * @param BundleReaderInterface $reader A resource bundle reader to use. + * @param BundleReaderInterface $reader A resource bundle reader to use */ public function __construct(BundleReaderInterface $reader) { diff --git a/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReaderInterface.php b/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReaderInterface.php index 8a4ecd8e6309c..e999440190aca 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReaderInterface.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleEntryReaderInterface.php @@ -37,9 +37,9 @@ interface BundleEntryReaderInterface extends BundleReaderInterface * * $reader->readEntry('...', 'en', array('TopLevel', 'NestedLevel', 'Entry')); * - * @param string $path The path to the resource bundle. - * @param string $locale The locale to read. - * @param string[] $indices The indices to read from the bundle. + * @param string $path The path to the resource bundle + * @param string $locale The locale to read + * @param string[] $indices The indices to read from the bundle * @param bool $fallback Whether to merge the value with the value from * the fallback locale (e.g. "en" for "en_GB"). * Only applicable if the result is multivalued diff --git a/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleReaderInterface.php b/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleReaderInterface.php index 7257b0df7ac60..8d3da825f77eb 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleReaderInterface.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Reader/BundleReaderInterface.php @@ -23,8 +23,8 @@ interface BundleReaderInterface /** * Reads a resource bundle. * - * @param string $path The path to the resource bundle. - * @param string $locale The locale to read. + * @param string $path The path to the resource bundle + * @param string $locale The locale to read * * @return mixed Returns an array or {@link \ArrayAccess} instance for * complex data, a scalar value otherwise. diff --git a/src/Symfony/Component/Intl/Data/Bundle/Writer/BundleWriterInterface.php b/src/Symfony/Component/Intl/Data/Bundle/Writer/BundleWriterInterface.php index e85376dc64bfe..ea9a66da6973e 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Writer/BundleWriterInterface.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Writer/BundleWriterInterface.php @@ -23,9 +23,9 @@ interface BundleWriterInterface /** * Writes data to a resource bundle. * - * @param string $path The path to the resource bundle. - * @param string $locale The locale to (over-)write. - * @param mixed $data The data to write. + * @param string $path The path to the resource bundle + * @param string $locale The locale to (over-)write + * @param mixed $data The data to write */ public function write($path, $locale, $data); } diff --git a/src/Symfony/Component/Intl/Data/Bundle/Writer/TextBundleWriter.php b/src/Symfony/Component/Intl/Data/Bundle/Writer/TextBundleWriter.php index aa078db5cd156..3b7d94f10a247 100644 --- a/src/Symfony/Component/Intl/Data/Bundle/Writer/TextBundleWriter.php +++ b/src/Symfony/Component/Intl/Data/Bundle/Writer/TextBundleWriter.php @@ -43,9 +43,9 @@ public function write($path, $locale, $data, $fallback = true) /** * Writes a "resourceBundle" node. * - * @param resource $file The file handle to write to. - * @param string $bundleName The name of the bundle. - * @param mixed $value The value of the node. + * @param resource $file The file handle to write to + * @param string $bundleName The name of the bundle + * @param mixed $value The value of the node * @param bool $fallback Whether the resource bundle should be merged * with the fallback locale. * @@ -63,9 +63,9 @@ private function writeResourceBundle($file, $bundleName, $value, $fallback) /** * Writes a "resource" node. * - * @param resource $file The file handle to write to. - * @param mixed $value The value of the node. - * @param int $indentation The number of levels to indent. + * @param resource $file The file handle to write to + * @param mixed $value The value of the node + * @param int $indentation The number of levels to indent * @param bool $requireBraces Whether to require braces to be printed * around the value. * @@ -118,8 +118,8 @@ private function writeResource($file, $value, $indentation, $requireBraces = tru /** * Writes an "integer" node. * - * @param resource $file The file handle to write to. - * @param int $value The value of the node. + * @param resource $file The file handle to write to + * @param int $value The value of the node * * @see http://source.icu-project.org/repos/icu/icuhtml/trunk/design/bnf_rb.txt */ @@ -131,9 +131,9 @@ private function writeInteger($file, $value) /** * Writes an "intvector" node. * - * @param resource $file The file handle to write to. - * @param array $value The value of the node. - * @param int $indentation The number of levels to indent. + * @param resource $file The file handle to write to + * @param array $value The value of the node + * @param int $indentation The number of levels to indent * * @see http://source.icu-project.org/repos/icu/icuhtml/trunk/design/bnf_rb.txt */ @@ -151,8 +151,8 @@ private function writeIntVector($file, array $value, $indentation) /** * Writes a "string" node. * - * @param resource $file The file handle to write to. - * @param string $value The value of the node. + * @param resource $file The file handle to write to + * @param string $value The value of the node * @param bool $requireBraces Whether to require braces to be printed * around the value. * @@ -172,9 +172,9 @@ private function writeString($file, $value, $requireBraces = true) /** * Writes an "array" node. * - * @param resource $file The file handle to write to. - * @param array $value The value of the node. - * @param int $indentation The number of levels to indent. + * @param resource $file The file handle to write to + * @param array $value The value of the node + * @param int $indentation The number of levels to indent * * @see http://source.icu-project.org/repos/icu/icuhtml/trunk/design/bnf_rb.txt */ @@ -196,9 +196,9 @@ private function writeArray($file, array $value, $indentation) /** * Writes a "table" node. * - * @param resource $file The file handle to write to. - * @param array|\Traversable $value The value of the node. - * @param int $indentation The number of levels to indent. + * @param resource $file The file handle to write to + * @param array|\Traversable $value The value of the node + * @param int $indentation The number of levels to indent * @param bool $fallback Whether the table should be merged * with the fallback locale. * diff --git a/src/Symfony/Component/Intl/Data/Generator/GeneratorConfig.php b/src/Symfony/Component/Intl/Data/Generator/GeneratorConfig.php index 221d3ab4aa8cb..78e16ef4d8dbc 100644 --- a/src/Symfony/Component/Intl/Data/Generator/GeneratorConfig.php +++ b/src/Symfony/Component/Intl/Data/Generator/GeneratorConfig.php @@ -68,7 +68,7 @@ public function getBundleWriters() * Returns the directory where the source versions of the resource bundles * are stored. * - * @return string An absolute path to a directory. + * @return string An absolute path to a directory */ public function getSourceDir() { @@ -78,7 +78,7 @@ public function getSourceDir() /** * Returns the ICU version of the bundles being converted. * - * @return string The ICU version string. + * @return string The ICU version string */ public function getIcuVersion() { diff --git a/src/Symfony/Component/Intl/Data/Provider/CurrencyDataProvider.php b/src/Symfony/Component/Intl/Data/Provider/CurrencyDataProvider.php index 9c76f2fd92eab..c2747f08062da 100644 --- a/src/Symfony/Component/Intl/Data/Provider/CurrencyDataProvider.php +++ b/src/Symfony/Component/Intl/Data/Provider/CurrencyDataProvider.php @@ -46,8 +46,8 @@ class CurrencyDataProvider * Creates a data provider that reads currency-related data from a * resource bundle. * - * @param string $path The path to the resource bundle. - * @param BundleEntryReaderInterface $reader The reader for reading the resource bundle. + * @param string $path The path to the resource bundle + * @param BundleEntryReaderInterface $reader The reader for reading the resource bundle */ public function __construct($path, BundleEntryReaderInterface $reader) { diff --git a/src/Symfony/Component/Intl/DateFormatter/IntlDateFormatter.php b/src/Symfony/Component/Intl/DateFormatter/IntlDateFormatter.php index bbc7b644413a5..7dd04a98e2680 100644 --- a/src/Symfony/Component/Intl/DateFormatter/IntlDateFormatter.php +++ b/src/Symfony/Component/Intl/DateFormatter/IntlDateFormatter.php @@ -131,7 +131,7 @@ class IntlDateFormatter /** * Constructor. * - * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en"). + * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en") * @param int $datetype Type of date formatting, one of the format type constants * @param int $timetype Type of time formatting, one of the format type constants * @param mixed $timezone Timezone identifier @@ -165,11 +165,11 @@ public function __construct($locale, $datetype, $timetype, $timezone = null, $ca /** * Static constructor. * - * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en"). + * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en") * @param int $datetype Type of date formatting, one of the format type constants * @param int $timetype Type of time formatting, one of the format type constants * @param string $timezone Timezone identifier - * @param int $calendar Calendar to use for formatting or parsing; default is Gregorian. + * @param int $calendar Calendar to use for formatting or parsing; default is Gregorian * One of the calendar constants. * @param string $pattern Optional pattern to use when formatting * @@ -192,7 +192,7 @@ public static function create($locale, $datetype, $timetype, $timezone = null, $ * @param int|\DateTime $timestamp The timestamp to format. \DateTime objects * are supported as of PHP 5.3.4. * - * @return string|bool The formatted value or false if formatting failed. + * @return string|bool The formatted value or false if formatting failed * * @see http://www.php.net/manual/en/intldateformatter.format.php * @@ -395,7 +395,7 @@ public function getTimeZone() /** * Returns whether the formatter is lenient. * - * @return bool Currently always returns false. + * @return bool Currently always returns false * * @see http://www.php.net/manual/en/intldateformatter.islenient.php * @@ -410,7 +410,7 @@ public function isLenient() * Not supported. Parse string to a field-based time value. * * @param string $value String to convert to a time value - * @param int $position Position at which to start the parsing in $value (zero-based). + * @param int $position Position at which to start the parsing in $value (zero-based) * If no error occurs before $value is consumed, $parse_pos will * contain -1 otherwise it will contain the position at which parsing * ended. If $parse_pos > strlen($value), the parse fails immediately. @@ -430,7 +430,7 @@ public function localtime($value, &$position = 0) * Parse string to a timestamp value. * * @param string $value String to convert to a time value - * @param int $position Not supported. Position at which to start the parsing in $value (zero-based). + * @param int $position Not supported. Position at which to start the parsing in $value (zero-based) * If no error occurs before $value is consumed, $parse_pos will * contain -1 otherwise it will contain the position at which parsing * ended. If $parse_pos > strlen($value), the parse fails immediately. @@ -463,7 +463,7 @@ public function parse($value, &$position = null) /** * Not supported. Set the formatter's calendar. * - * @param string $calendar The calendar to use. Default is IntlDateFormatter::GREGORIAN. + * @param string $calendar The calendar to use. Default is IntlDateFormatter::GREGORIAN * * @return bool true on success or false on failure * @@ -526,7 +526,7 @@ public function setPattern($pattern) /** * Set the formatter's timezone identifier. * - * @param string $timeZoneId The time zone ID string of the time zone to use. + * @param string $timeZoneId The time zone ID string of the time zone to use * If NULL or the empty string, the default time zone for the * runtime is used. * diff --git a/src/Symfony/Component/Intl/Intl.php b/src/Symfony/Component/Intl/Intl.php index 21031b5bbbbc9..c91d09054a28a 100644 --- a/src/Symfony/Component/Intl/Intl.php +++ b/src/Symfony/Component/Intl/Intl.php @@ -101,7 +101,7 @@ final class Intl /** * Returns whether the intl extension is installed. * - * @return bool Returns true if the intl extension is installed, false otherwise. + * @return bool Returns true if the intl extension is installed, false otherwise */ public static function isExtensionLoaded() { @@ -111,7 +111,7 @@ public static function isExtensionLoaded() /** * Returns the bundle containing currency information. * - * @return CurrencyBundleInterface The currency resource bundle. + * @return CurrencyBundleInterface The currency resource bundle */ public static function getCurrencyBundle() { @@ -129,7 +129,7 @@ public static function getCurrencyBundle() /** * Returns the bundle containing language information. * - * @return LanguageBundleInterface The language resource bundle. + * @return LanguageBundleInterface The language resource bundle */ public static function getLanguageBundle() { @@ -151,7 +151,7 @@ public static function getLanguageBundle() /** * Returns the bundle containing locale information. * - * @return LocaleBundleInterface The locale resource bundle. + * @return LocaleBundleInterface The locale resource bundle */ public static function getLocaleBundle() { @@ -168,7 +168,7 @@ public static function getLocaleBundle() /** * Returns the bundle containing region information. * - * @return RegionBundleInterface The region resource bundle. + * @return RegionBundleInterface The region resource bundle */ public static function getRegionBundle() { @@ -186,7 +186,7 @@ public static function getRegionBundle() /** * Returns the version of the installed ICU library. * - * @return null|string The ICU version or NULL if it could not be determined. + * @return null|string The ICU version or NULL if it could not be determined */ public static function getIcuVersion() { @@ -216,7 +216,7 @@ public static function getIcuVersion() /** * Returns the version of the installed ICU data. * - * @return string The version of the installed ICU data. + * @return string The version of the installed ICU data */ public static function getIcuDataVersion() { @@ -230,7 +230,7 @@ public static function getIcuDataVersion() /** * Returns the ICU version that the stub classes mimic. * - * @return string The ICU version of the stub classes. + * @return string The ICU version of the stub classes */ public static function getIcuStubVersion() { diff --git a/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php b/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php index fbbcf87ed0d46..7dce7c05d413f 100644 --- a/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php +++ b/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php @@ -259,8 +259,8 @@ class NumberFormatter /** * Constructor. * - * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en"). - * @param int $style Style of the formatting, one of the format style constants. + * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en") + * @param int $style Style of the formatting, one of the format style constants * The only supported styles are NumberFormatter::DECIMAL * and NumberFormatter::CURRENCY. * @param string $pattern Not supported. A pattern string in case $style is NumberFormat::PATTERN_DECIMAL or @@ -296,8 +296,8 @@ public function __construct($locale = 'en', $style = null, $pattern = null) /** * Static constructor. * - * @param string $locale The locale code. The only supported locale is "en" (or null using the default locale, i.e. "en"). - * @param int $style Style of the formatting, one of the format style constants. + * @param string $locale The locale code. The only supported locale is "en" (or null using the default locale, i.e. "en") + * @param int $style Style of the formatting, one of the format style constants * The only currently supported styles are NumberFormatter::DECIMAL * and NumberFormatter::CURRENCY. * @param string $pattern Not supported. A pattern string in case $style is NumberFormat::PATTERN_DECIMAL or @@ -358,7 +358,7 @@ public function formatCurrency($value, $currency) * Format a number. * * @param number $value The value to format - * @param int $type Type of the formatting, one of the format type constants. + * @param int $type Type of the formatting, one of the format type constants * Only type NumberFormatter::TYPE_DEFAULT is currently supported. * * @return bool|string The formatted value or false on error @@ -568,10 +568,10 @@ public function parse($value, $type = self::TYPE_DOUBLE, &$position = 0) /** * Set an attribute. * - * @param int $attr An attribute specifier, one of the numeric attribute constants. + * @param int $attr An attribute specifier, one of the numeric attribute constants * The only currently supported attributes are NumberFormatter::FRACTION_DIGITS, * NumberFormatter::GROUPING_USED and NumberFormatter::ROUNDING_MODE. - * @param int $value The attribute value. + * @param int $value The attribute value * * @return bool true on success or false on failure * diff --git a/src/Symfony/Component/Intl/ResourceBundle/CurrencyBundleInterface.php b/src/Symfony/Component/Intl/ResourceBundle/CurrencyBundleInterface.php index 8029e803477ac..eb82f6849e6a4 100644 --- a/src/Symfony/Component/Intl/ResourceBundle/CurrencyBundleInterface.php +++ b/src/Symfony/Component/Intl/ResourceBundle/CurrencyBundleInterface.php @@ -21,41 +21,41 @@ interface CurrencyBundleInterface extends ResourceBundleInterface /** * Returns the symbol used for a currency. * - * @param string $currency A currency code (e.g. "EUR"). - * @param string $displayLocale Optional. The locale to return the result in. + * @param string $currency A currency code (e.g. "EUR") + * @param string $displayLocale Optional. The locale to return the result in * Defaults to {@link \Locale::getDefault()}. * - * @return string|null The currency symbol or NULL if not found. + * @return string|null The currency symbol or NULL if not found */ public function getCurrencySymbol($currency, $displayLocale = null); /** * Returns the name of a currency. * - * @param string $currency A currency code (e.g. "EUR"). - * @param string $displayLocale Optional. The locale to return the name in. + * @param string $currency A currency code (e.g. "EUR") + * @param string $displayLocale Optional. The locale to return the name in * Defaults to {@link \Locale::getDefault()}. * - * @return string|null The name of the currency or NULL if not found. + * @return string|null The name of the currency or NULL if not found */ public function getCurrencyName($currency, $displayLocale = null); /** * Returns the names of all known currencies. * - * @param string $displayLocale Optional. The locale to return the names in. + * @param string $displayLocale Optional. The locale to return the names in * Defaults to {@link \Locale::getDefault()}. * - * @return string[] A list of currency names indexed by currency codes. + * @return string[] A list of currency names indexed by currency codes */ public function getCurrencyNames($displayLocale = null); /** * Returns the number of digits after the comma of a currency. * - * @param string $currency A currency code (e.g. "EUR"). + * @param string $currency A currency code (e.g. "EUR") * - * @return int|null The number of digits after the comma or NULL if not found. + * @return int|null The number of digits after the comma or NULL if not found */ public function getFractionDigits($currency); @@ -66,9 +66,9 @@ public function getFractionDigits($currency); * For example, 1230 rounded to the nearest 50 is 1250. 1.234 rounded to the * nearest 0.65 is 1.3. * - * @param string $currency A currency code (e.g. "EUR"). + * @param string $currency A currency code (e.g. "EUR") * - * @return float|int|null The rounding increment or NULL if not found. + * @return float|int|null The rounding increment or NULL if not found */ public function getRoundingIncrement($currency); } diff --git a/src/Symfony/Component/Intl/ResourceBundle/LanguageBundleInterface.php b/src/Symfony/Component/Intl/ResourceBundle/LanguageBundleInterface.php index 65601b92a2473..aa0c3e0f2c0b6 100644 --- a/src/Symfony/Component/Intl/ResourceBundle/LanguageBundleInterface.php +++ b/src/Symfony/Component/Intl/ResourceBundle/LanguageBundleInterface.php @@ -21,44 +21,44 @@ interface LanguageBundleInterface extends ResourceBundleInterface /** * Returns the name of a language. * - * @param string $language A language code (e.g. "en"). - * @param string|null $region Optional. A region code (e.g. "US"). - * @param string $displayLocale Optional. The locale to return the name in. + * @param string $language A language code (e.g. "en") + * @param string|null $region Optional. A region code (e.g. "US") + * @param string $displayLocale Optional. The locale to return the name in * Defaults to {@link \Locale::getDefault()}. * - * @return string|null The name of the language or NULL if not found. + * @return string|null The name of the language or NULL if not found */ public function getLanguageName($language, $region = null, $displayLocale = null); /** * Returns the names of all known languages. * - * @param string $displayLocale Optional. The locale to return the names in. + * @param string $displayLocale Optional. The locale to return the names in * Defaults to {@link \Locale::getDefault()}. * - * @return string[] A list of language names indexed by language codes. + * @return string[] A list of language names indexed by language codes */ public function getLanguageNames($displayLocale = null); /** * Returns the name of a script. * - * @param string $script A script code (e.g. "Hans"). - * @param string $language Optional. A language code (e.g. "zh"). - * @param string $displayLocale Optional. The locale to return the name in. + * @param string $script A script code (e.g. "Hans") + * @param string $language Optional. A language code (e.g. "zh") + * @param string $displayLocale Optional. The locale to return the name in * Defaults to {@link \Locale::getDefault()}. * - * @return string|null The name of the script or NULL if not found. + * @return string|null The name of the script or NULL if not found */ public function getScriptName($script, $language = null, $displayLocale = null); /** * Returns the names of all known scripts. * - * @param string $displayLocale Optional. The locale to return the names in. + * @param string $displayLocale Optional. The locale to return the names in * Defaults to {@link \Locale::getDefault()}. * - * @return string[] A list of script names indexed by script codes. + * @return string[] A list of script names indexed by script codes */ public function getScriptNames($displayLocale = null); } diff --git a/src/Symfony/Component/Intl/ResourceBundle/LocaleBundleInterface.php b/src/Symfony/Component/Intl/ResourceBundle/LocaleBundleInterface.php index 28547891c9d68..6fa4e5c0abbf5 100644 --- a/src/Symfony/Component/Intl/ResourceBundle/LocaleBundleInterface.php +++ b/src/Symfony/Component/Intl/ResourceBundle/LocaleBundleInterface.php @@ -21,21 +21,21 @@ interface LocaleBundleInterface extends ResourceBundleInterface /** * Returns the name of a locale. * - * @param string $locale The locale to return the name of (e.g. "de_AT"). - * @param string $displayLocale Optional. The locale to return the name in. + * @param string $locale The locale to return the name of (e.g. "de_AT") + * @param string $displayLocale Optional. The locale to return the name in * Defaults to {@link \Locale::getDefault()}. * - * @return string|null The name of the locale or NULL if not found. + * @return string|null The name of the locale or NULL if not found */ public function getLocaleName($locale, $displayLocale = null); /** * Returns the names of all known locales. * - * @param string $displayLocale Optional. The locale to return the names in. + * @param string $displayLocale Optional. The locale to return the names in * Defaults to {@link \Locale::getDefault()}. * - * @return string[] A list of locale names indexed by locale codes. + * @return string[] A list of locale names indexed by locale codes */ public function getLocaleNames($displayLocale = null); } diff --git a/src/Symfony/Component/Intl/ResourceBundle/RegionBundleInterface.php b/src/Symfony/Component/Intl/ResourceBundle/RegionBundleInterface.php index ed7b09536ff23..12d0dd240824c 100644 --- a/src/Symfony/Component/Intl/ResourceBundle/RegionBundleInterface.php +++ b/src/Symfony/Component/Intl/ResourceBundle/RegionBundleInterface.php @@ -21,21 +21,21 @@ interface RegionBundleInterface extends ResourceBundleInterface /** * Returns the name of a country. * - * @param string $country A country code (e.g. "US"). - * @param string $displayLocale Optional. The locale to return the name in. + * @param string $country A country code (e.g. "US") + * @param string $displayLocale Optional. The locale to return the name in * Defaults to {@link \Locale::getDefault()}. * - * @return string|null The name of the country or NULL if not found. + * @return string|null The name of the country or NULL if not found */ public function getCountryName($country, $displayLocale = null); /** * Returns the names of all known countries. * - * @param string $displayLocale Optional. The locale to return the names in. + * @param string $displayLocale Optional. The locale to return the names in * Defaults to {@link \Locale::getDefault()}. * - * @return string[] A list of country names indexed by country codes. + * @return string[] A list of country names indexed by country codes */ public function getCountryNames($displayLocale = null); } diff --git a/src/Symfony/Component/Intl/ResourceBundle/ResourceBundleInterface.php b/src/Symfony/Component/Intl/ResourceBundle/ResourceBundleInterface.php index 497a66a312eee..5c4c97483da94 100644 --- a/src/Symfony/Component/Intl/ResourceBundle/ResourceBundleInterface.php +++ b/src/Symfony/Component/Intl/ResourceBundle/ResourceBundleInterface.php @@ -21,7 +21,7 @@ interface ResourceBundleInterface /** * Returns the list of locales that this bundle supports. * - * @return string[] A list of locale codes. + * @return string[] A list of locale codes */ public function getLocales(); } diff --git a/src/Symfony/Component/Intl/Util/IcuVersion.php b/src/Symfony/Component/Intl/Util/IcuVersion.php index 23818e7bd7c77..e7324e7fd381a 100644 --- a/src/Symfony/Component/Intl/Util/IcuVersion.php +++ b/src/Symfony/Component/Intl/Util/IcuVersion.php @@ -43,13 +43,13 @@ class IcuVersion * IcuVersion::compare('1', '10', '==') * // => true * - * @param string $version1 A version string. - * @param string $version2 A version string to compare. - * @param string $operator The comparison operator. + * @param string $version1 A version string + * @param string $version2 A version string to compare + * @param string $operator The comparison operator * @param int|null $precision The number of components to compare. Pass * NULL to compare the versions unchanged. * - * @return bool Whether the comparison succeeded. + * @return bool Whether the comparison succeeded * * @see normalize() */ @@ -80,7 +80,7 @@ public static function compare($version1, $version2, $operator, $precision = nul * IcuVersion::normalize('1.2.3.4', 2); * // => '12.3' * - * @param string $version An ICU version string. + * @param string $version An ICU version string * @param int|null $precision The number of components to include. Pass * NULL to return the version unchanged. * diff --git a/src/Symfony/Component/Intl/Util/SvnCommit.php b/src/Symfony/Component/Intl/Util/SvnCommit.php index 483d92bc93e7d..c5ae1f1d79fa7 100644 --- a/src/Symfony/Component/Intl/Util/SvnCommit.php +++ b/src/Symfony/Component/Intl/Util/SvnCommit.php @@ -37,7 +37,7 @@ public function __construct(\SimpleXMLElement $svnInfo) /** * Returns the revision of the commit. * - * @return string The revision of the commit. + * @return string The revision of the commit */ public function getRevision() { @@ -47,7 +47,7 @@ public function getRevision() /** * Returns the author of the commit. * - * @return string The author name. + * @return string The author name */ public function getAuthor() { @@ -57,7 +57,7 @@ public function getAuthor() /** * Returns the date of the commit. * - * @return string The commit date. + * @return string The commit date */ public function getDate() { diff --git a/src/Symfony/Component/Intl/Util/SvnRepository.php b/src/Symfony/Component/Intl/Util/SvnRepository.php index 3b891b380c853..6e5d87b13ffd1 100644 --- a/src/Symfony/Component/Intl/Util/SvnRepository.php +++ b/src/Symfony/Component/Intl/Util/SvnRepository.php @@ -22,7 +22,7 @@ class SvnRepository { /** - * @var string The path to the repository. + * @var string The path to the repository */ private $path; @@ -39,10 +39,10 @@ class SvnRepository /** * Downloads the ICU data for the given version. * - * @param string $url The URL to download from. - * @param string $targetDir The directory in which to store the repository. + * @param string $url The URL to download from + * @param string $targetDir The directory in which to store the repository * - * @return SvnRepository The directory where the data is stored. + * @return SvnRepository The directory where the data is stored * * @throws RuntimeException If an error occurs during the download. */ @@ -73,7 +73,7 @@ public static function download($url, $targetDir) /** * Reads the SVN repository at the given path. * - * @param string $path The path to the repository. + * @param string $path The path to the repository */ public function __construct($path) { @@ -83,7 +83,7 @@ public function __construct($path) /** * Returns the path to the repository. * - * @return string The path to the repository. + * @return string The path to the repository */ public function getPath() { @@ -93,7 +93,7 @@ public function getPath() /** * Returns the URL of the repository. * - * @return string The URL of the repository. + * @return string The URL of the repository */ public function getUrl() { @@ -103,7 +103,7 @@ public function getUrl() /** * Returns the last commit of the repository. * - * @return SvnCommit The last commit. + * @return SvnCommit The last commit */ public function getLastCommit() { @@ -117,7 +117,7 @@ public function getLastCommit() /** * Returns information about the SVN repository. * - * @return \SimpleXMLElement The XML result from the "svn info" command. + * @return \SimpleXMLElement The XML result from the "svn info" command * * @throws RuntimeException If the "svn info" command failed. */ diff --git a/src/Symfony/Component/Intl/Util/Version.php b/src/Symfony/Component/Intl/Util/Version.php index 2facc19d53a23..11e97fe8bdd94 100644 --- a/src/Symfony/Component/Intl/Util/Version.php +++ b/src/Symfony/Component/Intl/Util/Version.php @@ -33,13 +33,13 @@ class Version * Version::compare('1.2.3', '1.2.4', '==', 2) * // => true * - * @param string $version1 A version string. - * @param string $version2 A version string to compare. - * @param string $operator The comparison operator. + * @param string $version1 A version string + * @param string $version2 A version string to compare + * @param string $operator The comparison operator * @param int|null $precision The number of components to compare. Pass * NULL to compare the versions unchanged. * - * @return bool Whether the comparison succeeded. + * @return bool Whether the comparison succeeded * * @see normalize() */ @@ -63,7 +63,7 @@ public static function compare($version1, $version2, $operator, $precision = nul * Version::normalize('1.2.3', 2); * // => '1.2' * - * @param string $version A version string. + * @param string $version A version string * @param int|null $precision The number of components to include. Pass * NULL to return the version unchanged. * diff --git a/src/Symfony/Component/Locale/Locale.php b/src/Symfony/Component/Locale/Locale.php index 767f412f03a5b..ebf33f6bdbf73 100644 --- a/src/Symfony/Component/Locale/Locale.php +++ b/src/Symfony/Component/Locale/Locale.php @@ -180,7 +180,7 @@ public static function getIcuDataDirectory() /** * Returns the fallback locale for a given locale, if any. * - * @param string $locale The locale to find the fallback for. + * @param string $locale The locale to find the fallback for * * @return string|null The fallback locale, or null if no parent exists */ diff --git a/src/Symfony/Component/OptionsResolver/OptionsResolverInterface.php b/src/Symfony/Component/OptionsResolver/OptionsResolverInterface.php index aebc8df22e858..cefba9cabeb39 100644 --- a/src/Symfony/Component/OptionsResolver/OptionsResolverInterface.php +++ b/src/Symfony/Component/OptionsResolver/OptionsResolverInterface.php @@ -43,7 +43,7 @@ interface OptionsResolverInterface * @param array $defaultValues A list of option names as keys and default * values or closures as values. * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance */ public function setDefaults(array $defaultValues); @@ -58,7 +58,7 @@ public function setDefaults(array $defaultValues); * @param array $defaultValues A list of option names as keys and default * values or closures as values. * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance */ public function replaceDefaults(array $defaultValues); @@ -71,9 +71,9 @@ public function replaceDefaults(array $defaultValues); * if you want to determine whether an option has been set or not because otherwise * {@link resolve()} would trigger an exception for unknown options. * - * @param array $optionNames A list of option names. + * @param array $optionNames A list of option names * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance */ public function setOptional(array $optionNames); @@ -83,9 +83,9 @@ public function setOptional(array $optionNames); * If these options are not passed to {@link resolve()} and no default has been set for * them, an exception will be thrown. * - * @param array $optionNames A list of option names. + * @param array $optionNames A list of option names * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance */ public function setRequired($optionNames); @@ -96,7 +96,7 @@ public function setRequired($optionNames); * with values acceptable for that option as * values. * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance * * @throws InvalidOptionsException If an option has not been defined * (see {@link isKnown()}) for which @@ -113,7 +113,7 @@ public function setAllowedValues($allowedValues); * with values acceptable for that option as * values. * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance * * @throws InvalidOptionsException If an option has not been defined * (see {@link isKnown()}) for which @@ -127,7 +127,7 @@ public function addAllowedValues($allowedValues); * @param array $allowedTypes A list of option names as keys and type * names passed as string or array as values. * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance * * @throws InvalidOptionsException If an option has not been defined for * which an allowed type is set. @@ -142,7 +142,7 @@ public function setAllowedTypes($allowedTypes); * @param array $allowedTypes A list of option names as keys and type * names passed as string or array as values. * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance * * @throws InvalidOptionsException If an option has not been defined for * which an allowed type is set. @@ -163,9 +163,9 @@ public function addAllowedTypes($allowedTypes); * * The closure should return the normalized value. * - * @param array $normalizers An array of closures. + * @param array $normalizers An array of closures * - * @return OptionsResolverInterface The resolver instance. + * @return OptionsResolverInterface The resolver instance */ public function setNormalizers(array $normalizers); @@ -175,9 +175,9 @@ public function setNormalizers(array $normalizers); * An option is known if it has been passed to either {@link setDefaults()}, * {@link setRequired()} or {@link setOptional()} before. * - * @param string $option The name of the option. + * @param string $option The name of the option * - * @return bool Whether the option is known. + * @return bool Whether the option is known */ public function isKnown($option); @@ -188,18 +188,18 @@ public function isKnown($option); * but not to {@link setDefaults()}. That is, the option has been declared * as required and no default value has been set. * - * @param string $option The name of the option. + * @param string $option The name of the option * - * @return bool Whether the option is required. + * @return bool Whether the option is required */ public function isRequired($option); /** * Returns the combination of the default and the passed options. * - * @param array $options The custom option values. + * @param array $options The custom option values * - * @return array A list of options and their values. + * @return array A list of options and their values * * @throws InvalidOptionsException If any of the passed options has not * been defined or does not contain an diff --git a/src/Symfony/Component/Process/Pipes/PipesInterface.php b/src/Symfony/Component/Process/Pipes/PipesInterface.php index 09d3f61d6ec94..b91c393d870e4 100644 --- a/src/Symfony/Component/Process/Pipes/PipesInterface.php +++ b/src/Symfony/Component/Process/Pipes/PipesInterface.php @@ -39,10 +39,10 @@ public function getFiles(); /** * Reads data in file handles and pipes. * - * @param bool $blocking Whether to use blocking calls or not. - * @param bool $close Whether to close pipes if they've reached EOF. + * @param bool $blocking Whether to use blocking calls or not + * @param bool $close Whether to close pipes if they've reached EOF * - * @return string[] An array of read data indexed by their fd. + * @return string[] An array of read data indexed by their fd */ public function readAndWrite($blocking, $close = false); diff --git a/src/Symfony/Component/Process/Pipes/WindowsPipes.php b/src/Symfony/Component/Process/Pipes/WindowsPipes.php index 23e412ca3af43..071dd0334a74f 100644 --- a/src/Symfony/Component/Process/Pipes/WindowsPipes.php +++ b/src/Symfony/Component/Process/Pipes/WindowsPipes.php @@ -47,14 +47,31 @@ public function __construct($disableOutput, $input) // Workaround for this problem is to use temporary files instead of pipes on Windows platform. // // @see https://bugs.php.net/bug.php?id=51800 - $this->files = array( - Process::STDOUT => tempnam(sys_get_temp_dir(), 'out_sf_proc'), - Process::STDERR => tempnam(sys_get_temp_dir(), 'err_sf_proc'), + $pipes = array( + Process::STDOUT => Process::OUT, + Process::STDERR => Process::ERR, ); - foreach ($this->files as $offset => $file) { - if (false === $file || false === $this->fileHandles[$offset] = @fopen($file, 'rb')) { - throw new RuntimeException('A temporary file could not be opened to write the process output to, verify that your TEMP environment variable is writable'); + $tmpDir = sys_get_temp_dir(); + if (!@fopen($file = $tmpDir.'\\sf_proc_00.check', 'wb')) { + throw new RuntimeException('A temporary file could not be opened to write the process output to, verify that your TEMP environment variable is writable'); + } + @unlink($file); + for ($i = 0;; ++$i) { + foreach ($pipes as $pipe => $name) { + $file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name); + if (file_exists($file) && !@unlink($file)) { + continue 2; + } + $h = @fopen($file, 'xb'); + if (!$h || !$this->fileHandles[$pipe] = fopen($file, 'rb')) { + continue 2; + } + if (isset($this->files[$pipe])) { + @unlink($this->files[$pipe]); + } + $this->files[$pipe] = $file; } + break; } } diff --git a/src/Symfony/Component/Process/Process.php b/src/Symfony/Component/Process/Process.php index 67ea6545891f6..d6adf21fa9390 100644 --- a/src/Symfony/Component/Process/Process.php +++ b/src/Symfony/Component/Process/Process.php @@ -593,7 +593,7 @@ public function getExitCode() * This method relies on the Unix exit code status standardization * and might not be relevant for other operating systems. * - * @return null|string A string representation for the exit status code, null if the Process is not terminated. + * @return null|string A string representation for the exit status code, null if the Process is not terminated * * @see http://tldp.org/LDP/abs/html/exitcodes.html * @see http://en.wikipedia.org/wiki/Unix_signal @@ -881,7 +881,7 @@ public function setTimeout($timeout) * * @param int|float|null $timeout The timeout in seconds * - * @return self The current Process instance. + * @return self The current Process instance * * @throws LogicException if the output is disabled * @throws InvalidArgumentException if the timeout is negative @@ -1265,7 +1265,7 @@ protected function buildCallback($callback) /** * Updates the status of the process, reads pipes. * - * @param bool $blocking Whether to use a blocking read call. + * @param bool $blocking Whether to use a blocking read call */ protected function updateStatus($blocking) { @@ -1351,8 +1351,8 @@ private function validateTimeout($timeout) /** * Reads pipes, executes callback. * - * @param bool $blocking Whether to use blocking calls or not. - * @param bool $close Whether to close file handles or not. + * @param bool $blocking Whether to use blocking calls or not + * @param bool $close Whether to close file handles or not */ private function readPipes($blocking, $close) { @@ -1478,7 +1478,7 @@ private function doSignal($signal, $throwException) /** * Ensures the process is running or terminated, throws a LogicException if the process has a not started. * - * @param string $functionName The function name that was called. + * @param string $functionName The function name that was called * * @throws LogicException If the process has not run. */ @@ -1492,7 +1492,7 @@ private function requireProcessIsStarted($functionName) /** * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`. * - * @param string $functionName The function name that was called. + * @param string $functionName The function name that was called * * @throws LogicException If the process is not yet terminated. */ diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index bb7914603ebab..f06b135e26821 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -54,6 +54,9 @@ protected function tearDown() public function testThatProcessDoesNotThrowWarningDuringRun() { + if ('\\' === DIRECTORY_SEPARATOR) { + $this->markTestSkipped('This test is transient on Windows'); + } @trigger_error('Test Error', E_USER_NOTICE); $process = $this->getProcess(self::$phpBin." -r 'sleep(3)'"); $process->run(); @@ -1180,7 +1183,8 @@ public function pipesCodeProvider() /** * @dataProvider provideVariousIncrementals */ - public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method) { + public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method) + { $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }'), null, null, null, null); $process->start(); $result = ''; @@ -1195,7 +1199,8 @@ public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method) $process->stop(); } - public function provideVariousIncrementals() { + public function provideVariousIncrementals() + { return array( array('php://stdout', 'getIncrementalOutput'), array('php://stderr', 'getIncrementalErrorOutput'), diff --git a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php index a1ff632231dd2..da0c5da93cdef 100644 --- a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php +++ b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php @@ -328,7 +328,7 @@ public function isWritable($objectOrArray, $propertyPath) * @param int $lastIndex The index up to which should be read * @param bool $ignoreInvalidIndices Whether to ignore invalid indices or throw an exception * - * @return array The values read in the path. + * @return array The values read in the path * * @throws UnexpectedTypeException If a value within the path is neither object nor array. * @throws NoSuchIndexException If a non-existing index is accessed @@ -444,7 +444,7 @@ private function readIndex($zval, $index) * Reads the a property from an object. * * @param array $zval The array containing the object to read from - * @param string $property The property to read. + * @param string $property The property to read * * @return array The array containing the value of the property * @@ -714,6 +714,17 @@ private function getWriteAccessInfo($class, $property, $value) // we call the getter and hope the __call do the job $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_MAGIC; $access[self::ACCESS_NAME] = $setter; + } elseif (null !== $methods = $this->findAdderAndRemover($reflClass, $singulars)) { + $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_NOT_FOUND; + $access[self::ACCESS_NAME] = sprintf( + 'The property "%s" in class "%s" can be defined with the methods "%s()" but '. + 'the new value must be an array or an instance of \Traversable, '. + '"%s" given.', + $property, + $reflClass->name, + implode('()", "', $methods), + is_object($value) ? get_class($value) : gettype($value) + ); } else { $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_NOT_FOUND; $access[self::ACCESS_NAME] = sprintf( diff --git a/src/Symfony/Component/PropertyAccess/PropertyPathBuilder.php b/src/Symfony/Component/PropertyAccess/PropertyPathBuilder.php index 39bf2da2e443b..57751bf13e741 100644 --- a/src/Symfony/Component/PropertyAccess/PropertyPathBuilder.php +++ b/src/Symfony/Component/PropertyAccess/PropertyPathBuilder.php @@ -44,10 +44,10 @@ public function __construct($path = null) /** * Appends a (sub-) path to the current path. * - * @param PropertyPathInterface|string $path The path to append. + * @param PropertyPathInterface|string $path The path to append * @param int $offset The offset where the appended * piece starts in $path. - * @param int $length The length of the appended piece. + * @param int $length The length of the appended piece * If 0, the full path is appended. */ public function append($path, $offset = 0, $length = 0) @@ -110,12 +110,12 @@ public function remove($offset, $length = 1) /** * Replaces a sub-path by a different (sub-) path. * - * @param int $offset The offset at which to replace. - * @param int $length The length of the piece to replace. - * @param PropertyPathInterface|string $path The path to insert. + * @param int $offset The offset at which to replace + * @param int $length The length of the piece to replace + * @param PropertyPathInterface|string $path The path to insert * @param int $pathOffset The offset where the inserted piece * starts in $path. - * @param int $pathLength The length of the inserted piece. + * @param int $pathLength The length of the inserted piece * If 0, the full path is inserted. * * @throws OutOfBoundsException If the offset is invalid @@ -149,7 +149,7 @@ public function replace($offset, $length, $path, $pathOffset = 0, $pathLength = * Replaces a property element by an index element. * * @param int $offset The offset at which to replace - * @param string $name The new name of the element. Optional. + * @param string $name The new name of the element. Optional * * @throws OutOfBoundsException If the offset is invalid */ @@ -170,7 +170,7 @@ public function replaceByIndex($offset, $name = null) * Replaces an index element by a property element. * * @param int $offset The offset at which to replace - * @param string $name The new name of the element. Optional. + * @param string $name The new name of the element. Optional * * @throws OutOfBoundsException If the offset is invalid */ diff --git a/src/Symfony/Component/PropertyAccess/StringUtil.php b/src/Symfony/Component/PropertyAccess/StringUtil.php index caa8c3d7e1a0d..d4df676ec0a48 100644 --- a/src/Symfony/Component/PropertyAccess/StringUtil.php +++ b/src/Symfony/Component/PropertyAccess/StringUtil.php @@ -24,7 +24,6 @@ class StringUtil * @var array * * @see http://english-zone.com/spelling/plurals.html - * @see http://www.scribd.com/doc/3271143/List-of-100-Irregular-Plural-Nouns-in-English */ private static $pluralMap = array( // First entry: plural suffix, reversed @@ -69,6 +68,15 @@ class StringUtil // movies (movie) array('seivom', 6, true, true, 'movie'), + // feet (foot) + array('teef', 4, true, true, 'foot'), + + // geese (goose) + array('eseeg', 5, true, true, 'goose'), + + // teeth (tooth) + array('hteet', 5, true, true, 'tooth'), + // news (news) array('swen', 4, true, true, 'news'), @@ -214,11 +222,6 @@ public static function singularify($plural) } } - // Convert teeth to tooth, feet to foot - if (false !== ($pos = strpos($plural, 'ee')) && strlen($plural) > 3 && 'feedback' !== $plural) { - return substr_replace($plural, 'oo', $pos, 2); - } - // Assume that plural and singular is identical return $plural; } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php index be8aba80d3d88..17518468ebad8 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTest.php @@ -194,4 +194,15 @@ public function testIsWritableReturnsFalseIfNoAdderNorRemoverExists() $this->assertFalse($this->propertyAccessor->isWritable($car, 'axes', $axes)); } + + /** + * @expectedException \Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException + * expectedExceptionMessageRegExp /The property "axes" in class "Mock_PropertyAccessorCollectionTest_Car[^"]*" can be defined with the methods "addAxis()", "removeAxis()" but the new value must be an array or an instance of \Traversable, "string" given./ + */ + public function testSetValueFailsIfAdderAndRemoverExistButValueIsNotTraversable() + { + $car = $this->getMock(__CLASS__.'_Car'); + + $this->propertyAccessor->setValue($car, 'axes', 'Not an array or Traversable'); + } } diff --git a/src/Symfony/Component/PropertyAccess/Tests/StringUtilTest.php b/src/Symfony/Component/PropertyAccess/Tests/StringUtilTest.php index 983e355cb9038..e6d0e5e908ba4 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/StringUtilTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/StringUtilTest.php @@ -53,6 +53,7 @@ public function singularifyProvider() array('children', 'child'), array('circuses', array('circus', 'circuse', 'circusis')), array('cliffs', 'cliff'), + array('committee', 'committee'), array('crises', array('cris', 'crise', 'crisis')), array('criteria', array('criterion', 'criterium')), array('cups', 'cup'), diff --git a/src/Symfony/Component/PropertyInfo/Tests/Extractors/PhpDocExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/Extractors/PhpDocExtractorTest.php index 6049df7f63749..332d1c4f8c318 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Extractors/PhpDocExtractorTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Extractors/PhpDocExtractorTest.php @@ -43,7 +43,7 @@ public function typesProvider() { return array( array('foo', null, 'Short description.', 'Long description.'), - array('bar', array(new Type(Type::BUILTIN_TYPE_STRING)), 'This is bar.', null), + array('bar', array(new Type(Type::BUILTIN_TYPE_STRING)), 'This is bar', null), array('baz', array(new Type(Type::BUILTIN_TYPE_INT)), 'Should be used.', null), array('foo2', array(new Type(Type::BUILTIN_TYPE_FLOAT)), null, null), array('foo3', array(new Type(Type::BUILTIN_TYPE_CALLABLE)), null, null), diff --git a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Dummy.php b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Dummy.php index 7068722c4ba71..41a513ac362e1 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Dummy.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Dummy.php @@ -19,14 +19,14 @@ class Dummy extends ParentDummy { /** - * @var string This is bar. + * @var string This is bar */ private $bar; /** * Should be used. * - * @var int Should be ignored. + * @var int Should be ignored */ protected $baz; diff --git a/src/Symfony/Component/Routing/Annotation/Route.php b/src/Symfony/Component/Routing/Annotation/Route.php index 7e7e056bd1670..191aa68a57a18 100644 --- a/src/Symfony/Component/Routing/Annotation/Route.php +++ b/src/Symfony/Component/Routing/Annotation/Route.php @@ -34,7 +34,7 @@ class Route /** * Constructor. * - * @param array $data An array of key/value parameters. + * @param array $data An array of key/value parameters * * @throws \BadMethodCallException */ diff --git a/src/Symfony/Component/Routing/CHANGELOG.md b/src/Symfony/Component/Routing/CHANGELOG.md index 7f5d9f0ec0296..04ac1d319822e 100644 --- a/src/Symfony/Component/Routing/CHANGELOG.md +++ b/src/Symfony/Component/Routing/CHANGELOG.md @@ -7,6 +7,22 @@ CHANGELOG * allowed specifying a directory to recursively load all routing configuration files it contains * Added ObjectRouteLoader and ServiceRouteLoader that allow routes to be loaded by calling a method on an object/service. + * [DEPRECATION] Deprecated the hardcoded value for the `$referenceType` argument of the `UrlGeneratorInterface::generate` method. + Use the constants defined in the `UrlGeneratorInterface` instead. + + Before: + + ```php + $router->generate('blog_show', array('slug' => 'my-blog-post'), true); + ``` + + After: + + ```php + use Symfony\Component\Routing\Generator\UrlGeneratorInterface; + + $router->generate('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL); + ``` 2.5.0 ----- diff --git a/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php b/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php index f6b99a16ae8b2..f66b928971981 100644 --- a/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php +++ b/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php @@ -69,7 +69,7 @@ public function supports($resource, $type = null) if (!is_string($resource)) { return false; } - + try { $path = $this->locator->locate($resource); } catch (\Exception $e) { diff --git a/src/Symfony/Component/Routing/Loader/XmlFileLoader.php b/src/Symfony/Component/Routing/Loader/XmlFileLoader.php index b5c24f9871c2f..537a81e9a44b1 100644 --- a/src/Symfony/Component/Routing/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/XmlFileLoader.php @@ -219,7 +219,7 @@ protected function loadFile($file) * @param \DOMElement $node Element to parse that contains the configs * @param string $path Full path of the XML file being processed * - * @return array An array with the defaults as first item, requirements as second and options as third. + * @return array An array with the defaults as first item, requirements as second and options as third * * @throws \InvalidArgumentException When the XML is invalid */ diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/DumperCollection.php b/src/Symfony/Component/Routing/Matcher/Dumper/DumperCollection.php index e7dea88ed39a1..0f2815b73e46b 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/DumperCollection.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/DumperCollection.php @@ -26,7 +26,7 @@ class DumperCollection implements \IteratorAggregate private $parent; /** - * @var (DumperCollection|DumperRoute)[] + * @var DumperCollection[]|DumperRoute[] */ private $children = array(); @@ -38,7 +38,7 @@ class DumperCollection implements \IteratorAggregate /** * Returns the children routes and collections. * - * @return (DumperCollection|DumperRoute)[] Array of DumperCollection|DumperRoute + * @return DumperCollection[]|DumperRoute[] Array of DumperCollection|DumperRoute */ public function all() { @@ -76,7 +76,7 @@ public function setAll(array $children) /** * Returns an iterator over the children. * - * @return \Iterator The iterator + * @return \Iterator|DumperCollection[]|DumperRoute[] The iterator */ public function getIterator() { diff --git a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php index 4dd89699a2371..7c27bc879653d 100644 --- a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php +++ b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcherInterface.php @@ -21,7 +21,7 @@ interface RedirectableUrlMatcherInterface /** * Redirects the user to another URL. * - * @param string $path The path info to redirect to. + * @param string $path The path info to redirect to * @param string $route The route name that matched * @param string|null $scheme The URL scheme (null to keep the current one) * diff --git a/src/Symfony/Component/Routing/RouteCollection.php b/src/Symfony/Component/Routing/RouteCollection.php index d6ac840ca66f0..2ccb90f3b0966 100644 --- a/src/Symfony/Component/Routing/RouteCollection.php +++ b/src/Symfony/Component/Routing/RouteCollection.php @@ -49,7 +49,7 @@ public function __clone() * * @see all() * - * @return \ArrayIterator An \ArrayIterator object for iterating over routes + * @return \ArrayIterator|Route[] An \ArrayIterator object for iterating over routes */ public function getIterator() { diff --git a/src/Symfony/Component/Routing/Router.php b/src/Symfony/Component/Routing/Router.php index 2cbbb2bdad342..d43029e706dad 100644 --- a/src/Symfony/Component/Routing/Router.php +++ b/src/Symfony/Component/Routing/Router.php @@ -219,7 +219,7 @@ public function getContext() /** * Sets the ConfigCache factory to use. * - * @param ConfigCacheFactoryInterface $configCacheFactory The factory to use. + * @param ConfigCacheFactoryInterface $configCacheFactory The factory to use */ public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory) { diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php index 71dea3230783e..bbbfe6453e4ba 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php @@ -26,7 +26,7 @@ class AnonymousToken extends AbstractToken * Constructor. * * @param string $secret A secret used to make sure the token is created by the app and not by a malicious client - * @param string|object $user The user can be a UserInterface instance, or an object implementing a __toString method or the username as a regular string. + * @param string|object $user The user can be a UserInterface instance, or an object implementing a __toString method or the username as a regular string * @param RoleInterface[] $roles An array of roles */ public function __construct($secret, $user, array $roles = array()) diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php index 5a3fc95327c08..b4b5e70b188fb 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php @@ -26,7 +26,7 @@ class PreAuthenticatedToken extends AbstractToken /** * Constructor. * - * @param string|object $user The user can be a UserInterface instance, or an object implementing a __toString method or the username as a regular string. + * @param string|object $user The user can be a UserInterface instance, or an object implementing a __toString method or the username as a regular string * @param mixed $credentials The user credentials * @param string $providerKey The provider key * @param RoleInterface[]|string[] $roles An array of roles diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php b/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php index be90802a9b6df..4e1dd7b2fc46b 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php @@ -33,7 +33,7 @@ public function __toString(); /** * Returns the user roles. * - * @return RoleInterface[] An array of RoleInterface instances. + * @return RoleInterface[] An array of RoleInterface instances */ public function getRoles(); diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php index 9248136982aba..33b00f01f82ae 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php @@ -26,7 +26,7 @@ class UsernamePasswordToken extends AbstractToken /** * Constructor. * - * @param string|object $user The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method. + * @param string|object $user The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method * @param string $credentials This usually is the password of the user * @param string $providerKey The provider key * @param RoleInterface[]|string[] $roles An array of roles diff --git a/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php b/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php index c1981deb96df3..e09d72e564f12 100644 --- a/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php +++ b/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php @@ -97,7 +97,7 @@ public function supportsClass($class) /** * Returns the user by given username. * - * @param string $username The username. + * @param string $username The username * * @return User * diff --git a/src/Symfony/Component/Security/Guard/GuardAuthenticatorInterface.php b/src/Symfony/Component/Security/Guard/GuardAuthenticatorInterface.php index 947594cecfa05..b28f06d337d63 100644 --- a/src/Symfony/Component/Security/Guard/GuardAuthenticatorInterface.php +++ b/src/Symfony/Component/Security/Guard/GuardAuthenticatorInterface.php @@ -39,11 +39,15 @@ interface GuardAuthenticatorInterface extends AuthenticationEntryPointInterface * Whatever value you return here will be passed to getUser() and checkCredentials() * * For example, for a form login, you might: - * - * return array( - * 'username' => $request->request->get('_username'), - * 'password' => $request->request->get('_password'), - * ); + * + * if ($request->request->has('_username')) { + * return array( + * 'username' => $request->request->get('_username'), + * 'password' => $request->request->get('_password'), + * ); + * } else { + * return; + * } * * Or for an API token that's on a header, you might use: * diff --git a/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php b/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php index 3e6399263963b..ea5c356c33c0b 100644 --- a/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php +++ b/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php @@ -47,7 +47,7 @@ class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandle * * @param HttpKernelInterface $httpKernel * @param HttpUtils $httpUtils - * @param array $options Options for processing a failed authentication attempt. + * @param array $options Options for processing a failed authentication attempt * @param LoggerInterface $logger Optional logger */ public function __construct(HttpKernelInterface $httpKernel, HttpUtils $httpUtils, array $options = array(), LoggerInterface $logger = null) diff --git a/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php b/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php index 078a3663847dd..bfc0c8b5b72e1 100644 --- a/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php +++ b/src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php @@ -40,7 +40,7 @@ class DefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandle * Constructor. * * @param HttpUtils $httpUtils - * @param array $options Options for processing a successful authentication attempt. + * @param array $options Options for processing a successful authentication attempt */ public function __construct(HttpUtils $httpUtils, array $options = array()) { diff --git a/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php b/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php index 910f4ceb1d00f..dd89e0faacd93 100644 --- a/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php +++ b/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php @@ -25,7 +25,7 @@ interface DecoderInterface * * @param string $data Data to decode * @param string $format Format name - * @param array $context options that decoders have access to. + * @param array $context options that decoders have access to * * The format parameter specifies which format the data is in; valid values * depend on the specific implementation. Authors implementing this interface diff --git a/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php b/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php index fe7e777daad32..05e9b2789b170 100644 --- a/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php +++ b/src/Symfony/Component/Serializer/Encoder/EncoderInterface.php @@ -25,7 +25,7 @@ interface EncoderInterface * * @param mixed $data Data to encode * @param string $format Format name - * @param array $context options that normalizers/encoders have access to. + * @param array $context options that normalizers/encoders have access to * * @return scalar * diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php index 4c17fb6b8d859..671ab97852ff1 100644 --- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php @@ -508,7 +508,7 @@ private function resolveXmlRootName(array $context = array()) /** * Create a DOM document, taking serializer options into account. * - * @param array $context options that the encoder has access to. + * @param array $context options that the encoder has access to * * @return \DOMDocument */ diff --git a/src/Symfony/Component/Serializer/Mapping/ClassMetadataInterface.php b/src/Symfony/Component/Serializer/Mapping/ClassMetadataInterface.php index 5889f0da11886..c00981b64f069 100644 --- a/src/Symfony/Component/Serializer/Mapping/ClassMetadataInterface.php +++ b/src/Symfony/Component/Serializer/Mapping/ClassMetadataInterface.php @@ -27,7 +27,7 @@ interface ClassMetadataInterface /** * Returns the name of the backing PHP class. * - * @return string The name of the backing class. + * @return string The name of the backing class */ public function getName(); diff --git a/src/Symfony/Component/Serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php b/src/Symfony/Component/Serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php index 80720fa6babeb..d3daf12e46dd5 100644 --- a/src/Symfony/Component/Serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php +++ b/src/Symfony/Component/Serializer/NameConverter/CamelCaseToSnakeCaseNameConverter.php @@ -29,8 +29,8 @@ class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface private $lowerCamelCase; /** - * @param null|array $attributes The list of attributes to rename or null for all attributes. - * @param bool $lowerCamelCase Use lowerCamelCase style. + * @param null|array $attributes The list of attributes to rename or null for all attributes + * @param bool $lowerCamelCase Use lowerCamelCase style */ public function __construct(array $attributes = null, $lowerCamelCase = true) { diff --git a/src/Symfony/Component/Serializer/Normalizer/CustomNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/CustomNormalizer.php index be8b7d5fd747d..b676b833ca26b 100644 --- a/src/Symfony/Component/Serializer/Normalizer/CustomNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/CustomNormalizer.php @@ -38,8 +38,8 @@ public function denormalize($data, $class, $format = null, array $context = arra /** * Checks if the given class implements the NormalizableInterface. * - * @param mixed $data Data to normalize. - * @param string $format The format being (de-)serialized from or into. + * @param mixed $data Data to normalize + * @param string $format The format being (de-)serialized from or into * * @return bool */ @@ -51,9 +51,9 @@ public function supportsNormalization($data, $format = null) /** * Checks if the given class implements the NormalizableInterface. * - * @param mixed $data Data to denormalize from. - * @param string $type The class to which the data should be denormalized. - * @param string $format The format being deserialized from. + * @param mixed $data Data to denormalize from + * @param string $type The class to which the data should be denormalized + * @param string $format The format being deserialized from * * @return bool */ diff --git a/src/Symfony/Component/Serializer/Normalizer/DenormalizableInterface.php b/src/Symfony/Component/Serializer/Normalizer/DenormalizableInterface.php index 8ad1386a6cbd4..4fe7a313a1755 100644 --- a/src/Symfony/Component/Serializer/Normalizer/DenormalizableInterface.php +++ b/src/Symfony/Component/Serializer/Normalizer/DenormalizableInterface.php @@ -29,7 +29,7 @@ interface DenormalizableInterface * * @param DenormalizerInterface $denormalizer The denormalizer is given so that you * can use it to denormalize objects contained within this object - * @param array|scalar $data The data from which to re-create the object. + * @param array|scalar $data The data from which to re-create the object * @param string|null $format The format is optionally given to be able to denormalize differently * based on different input formats * @param array $context options for denormalizing diff --git a/src/Symfony/Component/Serializer/Normalizer/DenormalizerInterface.php b/src/Symfony/Component/Serializer/Normalizer/DenormalizerInterface.php index 8b6c2333958fe..23df4829a8cbd 100644 --- a/src/Symfony/Component/Serializer/Normalizer/DenormalizerInterface.php +++ b/src/Symfony/Component/Serializer/Normalizer/DenormalizerInterface.php @@ -33,9 +33,9 @@ public function denormalize($data, $class, $format = null, array $context = arra /** * Checks whether the given class is supported for denormalization by this normalizer. * - * @param mixed $data Data to denormalize from. - * @param string $type The class to which the data should be denormalized. - * @param string $format The format being deserialized from. + * @param mixed $data Data to denormalize from + * @param string $type The class to which the data should be denormalized + * @param string $format The format being deserialized from * * @return bool */ diff --git a/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php index fc7ac9f4631de..003c3a68807fb 100644 --- a/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php @@ -164,7 +164,7 @@ private function supports($class) * * @param \ReflectionMethod $method the method to check * - * @return bool whether the method is a getter or boolean getter. + * @return bool whether the method is a getter or boolean getter */ private function isGetMethod(\ReflectionMethod $method) { diff --git a/src/Symfony/Component/Serializer/Normalizer/NormalizerInterface.php b/src/Symfony/Component/Serializer/Normalizer/NormalizerInterface.php index f4bd355232b0b..f7007840da1f4 100644 --- a/src/Symfony/Component/Serializer/Normalizer/NormalizerInterface.php +++ b/src/Symfony/Component/Serializer/Normalizer/NormalizerInterface.php @@ -32,8 +32,8 @@ public function normalize($object, $format = null, array $context = array()); /** * Checks whether the given class is supported for normalization by this normalizer. * - * @param mixed $data Data to normalize. - * @param string $format The format being (de-)serialized from or into. + * @param mixed $data Data to normalize + * @param string $format The format being (de-)serialized from or into * * @return bool */ diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php index 717004af05c5a..5742b0c70acc7 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php @@ -249,7 +249,8 @@ public function testEncodeSerializerXmlRootNodeNameOption() $this->assertEquals($expected, $serializer->serialize($array, 'xml', $options)); } - public function testEncodeTraversableWhenNormalizable() { + public function testEncodeTraversableWhenNormalizable() + { $this->encoder = new XmlEncoder(); $serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder())); $this->encoder->setSerializer($serializer); @@ -261,7 +262,6 @@ public function testEncodeTraversableWhenNormalizable() { XML; $this->assertEquals($expected, $serializer->serialize(new NormalizableTraversableDummy(), 'xml')); - } public function testDecode() diff --git a/src/Symfony/Component/Stopwatch/Section.php b/src/Symfony/Component/Stopwatch/Section.php index 80e17c8b0a24c..fb416efedce23 100644 --- a/src/Symfony/Component/Stopwatch/Section.php +++ b/src/Symfony/Component/Stopwatch/Section.php @@ -67,7 +67,7 @@ public function get($id) /** * Creates or re-opens a child section. * - * @param string|null $id null to create a new section, the identifier to re-open an existing one. + * @param string|null $id null to create a new section, the identifier to re-open an existing one * * @return Section A child section */ diff --git a/src/Symfony/Component/Translation/Loader/MoFileLoader.php b/src/Symfony/Component/Translation/Loader/MoFileLoader.php index c27a88e3d275e..2fcada28477a7 100644 --- a/src/Symfony/Component/Translation/Loader/MoFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/MoFileLoader.php @@ -37,7 +37,7 @@ class MoFileLoader extends FileLoader /** * The size of the header of a MO file in bytes. * - * @var int Number of bytes. + * @var int Number of bytes */ const MO_HEADER_SIZE = 28; diff --git a/src/Symfony/Component/Translation/Loader/XliffFileLoader.php b/src/Symfony/Component/Translation/Loader/XliffFileLoader.php index a02f544a9132a..4e2b7c182ba38 100644 --- a/src/Symfony/Component/Translation/Loader/XliffFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/XliffFileLoader.php @@ -173,10 +173,16 @@ private function validateSchema($file, \DOMDocument $dom, $schema) { $internalErrors = libxml_use_internal_errors(true); + $disableEntities = libxml_disable_entity_loader(false); + if (!@$dom->schemaValidateSource($schema)) { + libxml_disable_entity_loader($disableEntities); + throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors)))); } + libxml_disable_entity_loader($disableEntities); + $dom->normalizeDocument(); libxml_clear_errors(); diff --git a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php index 9aafa4b161358..2f466d879cfab 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php @@ -46,6 +46,20 @@ public function testLoadWithInternalErrorsEnabled() libxml_use_internal_errors($internalErrors); } + public function testLoadWithExternalEntitiesDisabled() + { + $disableEntities = libxml_disable_entity_loader(true); + + $loader = new XliffFileLoader(); + $resource = __DIR__.'/../fixtures/resources.xlf'; + $catalogue = $loader->load($resource, 'en', 'domain1'); + + libxml_disable_entity_loader($disableEntities); + + $this->assertEquals('en', $catalogue->getLocale()); + $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources()); + } + public function testLoadWithResname() { $loader = new XliffFileLoader(); diff --git a/src/Symfony/Component/Translation/Tests/PluralizationRulesTest.php b/src/Symfony/Component/Translation/Tests/PluralizationRulesTest.php index 5de544e0c1b1c..8ce2c58defb9e 100644 --- a/src/Symfony/Component/Translation/Tests/PluralizationRulesTest.php +++ b/src/Symfony/Component/Translation/Tests/PluralizationRulesTest.php @@ -93,7 +93,7 @@ public function failingLangcodes() * We validate only on the plural coverage. Thus the real rules is not tested. * * @param string $nplural plural expected - * @param array $matrix containing langcodes and their plural index values. + * @param array $matrix containing langcodes and their plural index values * @param bool $expectSuccess */ protected function validateMatrix($nplural, $matrix, $expectSuccess = true) diff --git a/src/Symfony/Component/Translation/Tests/TranslatorTest.php b/src/Symfony/Component/Translation/Tests/TranslatorTest.php index 9fd06c9f1151e..f5dad8fc91d9d 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorTest.php @@ -285,12 +285,12 @@ public function testFallbackCatalogueResources() $resources = $translator->getCatalogue('en')->getResources(); $this->assertCount(1, $resources); - $this->assertContains( __DIR__.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'resources.yml', $resources); + $this->assertContains(__DIR__.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'resources.yml', $resources); $resources = $translator->getCatalogue('en_GB')->getResources(); $this->assertCount(2, $resources); - $this->assertContains( __DIR__.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'empty.yml', $resources); - $this->assertContains( __DIR__.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'resources.yml', $resources); + $this->assertContains(__DIR__.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'empty.yml', $resources); + $this->assertContains(__DIR__.DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'resources.yml', $resources); } /** diff --git a/src/Symfony/Component/Validator/ClassBasedInterface.php b/src/Symfony/Component/Validator/ClassBasedInterface.php index 7c2eb8f0f7c92..c57da274be1ee 100644 --- a/src/Symfony/Component/Validator/ClassBasedInterface.php +++ b/src/Symfony/Component/Validator/ClassBasedInterface.php @@ -24,7 +24,7 @@ interface ClassBasedInterface /** * Returns the name of the backing PHP class. * - * @return string The name of the backing class. + * @return string The name of the backing class */ public function getClassName(); } diff --git a/src/Symfony/Component/Validator/ConstraintViolation.php b/src/Symfony/Component/Validator/ConstraintViolation.php index 31b44d23cd3da..516004a7c169b 100644 --- a/src/Symfony/Component/Validator/ConstraintViolation.php +++ b/src/Symfony/Component/Validator/ConstraintViolation.php @@ -105,7 +105,7 @@ public function __construct($message, $messageTemplate, array $parameters, $root /** * Converts the violation into a string for debugging purposes. * - * @return string The violation as string. + * @return string The violation as string */ public function __toString() { diff --git a/src/Symfony/Component/Validator/ConstraintViolationInterface.php b/src/Symfony/Component/Validator/ConstraintViolationInterface.php index 896fabc2786c9..11028fe0ab1aa 100644 --- a/src/Symfony/Component/Validator/ConstraintViolationInterface.php +++ b/src/Symfony/Component/Validator/ConstraintViolationInterface.php @@ -38,7 +38,7 @@ interface ConstraintViolationInterface /** * Returns the violation message. * - * @return string The violation message. + * @return string The violation message */ public function getMessage(); @@ -49,7 +49,7 @@ public function getMessage(); * returned by {@link getMessageParameters}. Typically you'll pass the * message template and parameters to a translation engine. * - * @return string The raw violation message. + * @return string The raw violation message */ public function getMessageTemplate(); @@ -78,7 +78,7 @@ public function getMessageParameters(); * This method returns the value of the parameter for choosing the right * pluralization form (in this case "choices"). * - * @return int|null The number to use to pluralize of the message. + * @return int|null The number to use to pluralize of the message * * @deprecated since version 2.7, to be replaced by getPlural() in 3.0. */ @@ -119,7 +119,7 @@ public function getInvalidValue(); /** * Returns a machine-digestible error code for the violation. * - * @return string|null The error code. + * @return string|null The error code */ public function getCode(); } diff --git a/src/Symfony/Component/Validator/ConstraintViolationList.php b/src/Symfony/Component/Validator/ConstraintViolationList.php index cccfa86aea968..3490237bc2d6b 100644 --- a/src/Symfony/Component/Validator/ConstraintViolationList.php +++ b/src/Symfony/Component/Validator/ConstraintViolationList.php @@ -38,7 +38,7 @@ public function __construct(array $violations = array()) /** * Converts the violation into a string for debugging purposes. * - * @return string The violation as string. + * @return string The violation as string */ public function __toString() { @@ -107,6 +107,8 @@ public function remove($offset) /** * {@inheritdoc} + * + * @return \ArrayIterator|ConstraintViolationInterface[] */ public function getIterator() { diff --git a/src/Symfony/Component/Validator/ConstraintViolationListInterface.php b/src/Symfony/Component/Validator/ConstraintViolationListInterface.php index 8d15bd72b887e..d96755c9a277e 100644 --- a/src/Symfony/Component/Validator/ConstraintViolationListInterface.php +++ b/src/Symfony/Component/Validator/ConstraintViolationListInterface.php @@ -21,23 +21,23 @@ interface ConstraintViolationListInterface extends \Traversable, \Countable, \Ar /** * Adds a constraint violation to this list. * - * @param ConstraintViolationInterface $violation The violation to add. + * @param ConstraintViolationInterface $violation The violation to add */ public function add(ConstraintViolationInterface $violation); /** * Merges an existing violation list into this list. * - * @param ConstraintViolationListInterface $otherList The list to merge. + * @param ConstraintViolationListInterface $otherList The list to merge */ public function addAll(ConstraintViolationListInterface $otherList); /** * Returns the violation at a given offset. * - * @param int $offset The offset of the violation. + * @param int $offset The offset of the violation * - * @return ConstraintViolationInterface The violation. + * @return ConstraintViolationInterface The violation * * @throws \OutOfBoundsException If the offset does not exist. */ @@ -46,24 +46,24 @@ public function get($offset); /** * Returns whether the given offset exists. * - * @param int $offset The violation offset. + * @param int $offset The violation offset * - * @return bool Whether the offset exists. + * @return bool Whether the offset exists */ public function has($offset); /** * Sets a violation at a given offset. * - * @param int $offset The violation offset. - * @param ConstraintViolationInterface $violation The violation. + * @param int $offset The violation offset + * @param ConstraintViolationInterface $violation The violation */ public function set($offset, ConstraintViolationInterface $violation); /** * Removes a violation at a given offset. * - * @param int $offset The offset to remove. + * @param int $offset The offset to remove */ public function remove($offset); } diff --git a/src/Symfony/Component/Validator/Constraints/EmailValidator.php b/src/Symfony/Component/Validator/Constraints/EmailValidator.php index 42fe82ef9c72c..6ae25e016d921 100644 --- a/src/Symfony/Component/Validator/Constraints/EmailValidator.php +++ b/src/Symfony/Component/Validator/Constraints/EmailValidator.php @@ -56,8 +56,8 @@ public function validate($value, Constraint $constraint) } if ($constraint->strict) { - if (!class_exists('\Egulias\EmailValidator\EmailValidator')) { - throw new RuntimeException('Strict email validation requires egulias/email-validator'); + if (!class_exists('\Egulias\EmailValidator\EmailValidator') || interface_exists('\Egulias\EmailValidator\Validation\EmailValidation')) { + throw new RuntimeException('Strict email validation requires egulias/email-validator:~1.2'); } $strictValidator = new \Egulias\EmailValidator\EmailValidator(); diff --git a/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php b/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php index 2ef80b66f041a..9c28bde9ea631 100644 --- a/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php +++ b/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php @@ -111,7 +111,7 @@ public function getValidator(); * * In other cases, null is returned. * - * @return object|null The currently validated object or null. + * @return object|null The currently validated object or null */ public function getObject(); diff --git a/src/Symfony/Component/Validator/ExecutionContext.php b/src/Symfony/Component/Validator/ExecutionContext.php index 5875e94ef45d7..52cccb2f68b7d 100644 --- a/src/Symfony/Component/Validator/ExecutionContext.php +++ b/src/Symfony/Component/Validator/ExecutionContext.php @@ -66,13 +66,13 @@ class ExecutionContext implements ExecutionContextInterface /** * Creates a new execution context. * - * @param GlobalExecutionContextInterface $globalContext The global context storing node-independent state. - * @param TranslatorInterface $translator The translator for translating violation messages. - * @param null|string $translationDomain The domain of the validation messages. - * @param MetadataInterface $metadata The metadata of the validated node. - * @param mixed $value The value of the validated node. - * @param string $group The current validation group. - * @param string $propertyPath The property path to the current node. + * @param GlobalExecutionContextInterface $globalContext The global context storing node-independent state + * @param TranslatorInterface $translator The translator for translating violation messages + * @param null|string $translationDomain The domain of the validation messages + * @param MetadataInterface $metadata The metadata of the validated node + * @param mixed $value The value of the validated node + * @param string $group The current validation group + * @param string $propertyPath The property path to the current node */ public function __construct(GlobalExecutionContextInterface $globalContext, TranslatorInterface $translator, $translationDomain = null, MetadataInterface $metadata = null, $value = null, $group = null, $propertyPath = '') { @@ -266,8 +266,8 @@ public function getMetadataFactory() /** * Executes the validators of the given constraints for the given value. * - * @param mixed $value The value to validate. - * @param Constraint[] $constraints The constraints to match against. + * @param mixed $value The value to validate + * @param Constraint[] $constraints The constraints to match against */ private function executeConstraintValidators($value, array $constraints) { @@ -286,7 +286,7 @@ private function executeConstraintValidators($value, array $constraints) * is passed, an array containing the current * group of the context is returned. * - * @return array An array of validation groups. + * @return array An array of validation groups */ private function resolveGroups($groups) { diff --git a/src/Symfony/Component/Validator/ExecutionContextInterface.php b/src/Symfony/Component/Validator/ExecutionContextInterface.php index b07e928e2c17f..075fecb0c520a 100644 --- a/src/Symfony/Component/Validator/ExecutionContextInterface.php +++ b/src/Symfony/Component/Validator/ExecutionContextInterface.php @@ -145,8 +145,8 @@ public function addViolationAt($subPath, $message, array $parameters = array(), * Any violations generated during the validation will be added to the * violation list that you can access with {@link getViolations}. * - * @param mixed $value The value to validate. - * @param string $subPath The path to append to the context's property path. + * @param mixed $value The value to validate + * @param string $subPath The path to append to the context's property path * @param null|string|string[] $groups The groups to validate in. If you don't pass any * groups here, the current group of the context * will be used. @@ -181,9 +181,9 @@ public function validate($value, $subPath = '', $groups = null, $traverse = fals * $context->validate($address->street, new NotNull(), 'street'); * * - * @param mixed $value The value to validate. - * @param Constraint|Constraint[] $constraints The constraint(s) to validate against. - * @param string $subPath The path to append to the context's property path. + * @param mixed $value The value to validate + * @param Constraint|Constraint[] $constraints The constraint(s) to validate against + * @param string $subPath The path to append to the context's property path * @param null|string|string[] $groups The groups to validate in. If you don't pass any * groups here, the current group of the context * will be used. @@ -197,7 +197,7 @@ public function validateValue($value, $constraints, $subPath = '', $groups = nul /** * Returns the violations generated by the validator so far. * - * @return ConstraintViolationListInterface The constraint violation list. + * @return ConstraintViolationListInterface The constraint violation list */ public function getViolations(); @@ -210,7 +210,7 @@ public function getViolations(); * * The current value is returned by {@link getValue}. * - * @return mixed The root value of the validation. + * @return mixed The root value of the validation */ public function getRoot(); @@ -220,7 +220,7 @@ public function getRoot(); * If you want to retrieve the object that was originally passed to the * validator, use {@link getRoot}. * - * @return mixed The currently validated value. + * @return mixed The currently validated value */ public function getValue(); @@ -245,7 +245,7 @@ public function getMetadata(); /** * Returns the used metadata factory. * - * @return MetadataFactoryInterface The metadata factory. + * @return MetadataFactoryInterface The metadata factory * * @deprecated since version 2.5, to be removed in 3.0. * Use {@link Context\ExecutionContextInterface::getValidator()} @@ -258,7 +258,7 @@ public function getMetadataFactory(); /** * Returns the validation group that is currently being validated. * - * @return string The current validation group. + * @return string The current validation group */ public function getGroup(); @@ -269,7 +269,7 @@ public function getGroup(); * {@link ClassBasedInterface} or if no metadata is available for the * current node, this method returns null. * - * @return string|null The class name or null, if no class name could be found. + * @return string|null The class name or null, if no class name could be found */ public function getClassName(); @@ -280,7 +280,7 @@ public function getClassName(); * {@link PropertyMetadataInterface} or if no metadata is available for the * current node, this method returns null. * - * @return string|null The property name or null, if no property name could be found. + * @return string|null The property name or null, if no property name could be found */ public function getPropertyName(); diff --git a/src/Symfony/Component/Validator/GlobalExecutionContextInterface.php b/src/Symfony/Component/Validator/GlobalExecutionContextInterface.php index 5c646f294baee..d9bd315afd2e7 100644 --- a/src/Symfony/Component/Validator/GlobalExecutionContextInterface.php +++ b/src/Symfony/Component/Validator/GlobalExecutionContextInterface.php @@ -35,14 +35,14 @@ interface GlobalExecutionContextInterface /** * Returns the violations generated by the validator so far. * - * @return ConstraintViolationListInterface A list of constraint violations. + * @return ConstraintViolationListInterface A list of constraint violations */ public function getViolations(); /** * Returns the value at which validation was started in the object graph. * - * @return mixed The root value. + * @return mixed The root value * * @see ExecutionContextInterface::getRoot() */ @@ -51,21 +51,21 @@ public function getRoot(); /** * Returns the visitor instance used to validate the object graph nodes. * - * @return ValidationVisitorInterface The validation visitor. + * @return ValidationVisitorInterface The validation visitor */ public function getVisitor(); /** * Returns the factory for constraint validators. * - * @return ConstraintValidatorFactoryInterface The constraint validator factory. + * @return ConstraintValidatorFactoryInterface The constraint validator factory */ public function getValidatorFactory(); /** * Returns the factory for validation metadata objects. * - * @return MetadataFactoryInterface The metadata factory. + * @return MetadataFactoryInterface The metadata factory */ public function getMetadataFactory(); } diff --git a/src/Symfony/Component/Validator/PropertyMetadataContainerInterface.php b/src/Symfony/Component/Validator/PropertyMetadataContainerInterface.php index 5441be1c3d063..b5c9cf4da9dee 100644 --- a/src/Symfony/Component/Validator/PropertyMetadataContainerInterface.php +++ b/src/Symfony/Component/Validator/PropertyMetadataContainerInterface.php @@ -24,7 +24,7 @@ interface PropertyMetadataContainerInterface /** * Check if there's any metadata attached to the given named property. * - * @param string $property The property name. + * @param string $property The property name * * @return bool */ @@ -36,7 +36,7 @@ public function hasPropertyMetadata($property); * If your implementation does not support properties, simply throw an * exception in this method (for example a BadMethodCallException). * - * @param string $property The property name. + * @param string $property The property name * * @return PropertyMetadataInterface[] A list of metadata instances. Empty if * no metadata exists for the property. diff --git a/src/Symfony/Component/Validator/PropertyMetadataInterface.php b/src/Symfony/Component/Validator/PropertyMetadataInterface.php index 46e7c692c85ca..64ae881e320f2 100644 --- a/src/Symfony/Component/Validator/PropertyMetadataInterface.php +++ b/src/Symfony/Component/Validator/PropertyMetadataInterface.php @@ -31,16 +31,16 @@ interface PropertyMetadataInterface extends MetadataInterface /** * Returns the name of the property. * - * @return string The property name. + * @return string The property name */ public function getPropertyName(); /** * Extracts the value of the property from the given container. * - * @param mixed $containingValue The container to extract the property value from. + * @param mixed $containingValue The container to extract the property value from * - * @return mixed The value of the property. + * @return mixed The value of the property */ public function getPropertyValue($containingValue); } diff --git a/src/Symfony/Component/Validator/Validation.php b/src/Symfony/Component/Validator/Validation.php index 1693f7311add4..94ed62c52559b 100644 --- a/src/Symfony/Component/Validator/Validation.php +++ b/src/Symfony/Component/Validator/Validation.php @@ -42,7 +42,7 @@ final class Validation * If you want to configure the validator, use * {@link createValidatorBuilder()} instead. * - * @return ValidatorInterface The new validator. + * @return ValidatorInterface The new validator */ public static function createValidator() { @@ -52,7 +52,7 @@ public static function createValidator() /** * Creates a configurable builder for validator objects. * - * @return ValidatorBuilderInterface The new builder. + * @return ValidatorBuilderInterface The new builder */ public static function createValidatorBuilder() { diff --git a/src/Symfony/Component/Validator/ValidationVisitor.php b/src/Symfony/Component/Validator/ValidationVisitor.php index 838646260f36b..82af6a9e727de 100644 --- a/src/Symfony/Component/Validator/ValidationVisitor.php +++ b/src/Symfony/Component/Validator/ValidationVisitor.php @@ -70,12 +70,12 @@ class ValidationVisitor implements ValidationVisitorInterface, GlobalExecutionCo /** * Creates a new validation visitor. * - * @param mixed $root The value passed to the validator. - * @param MetadataFactoryInterface $metadataFactory The factory for obtaining metadata instances. - * @param ConstraintValidatorFactoryInterface $validatorFactory The factory for creating constraint validators. - * @param TranslatorInterface $translator The translator for translating violation messages. - * @param string|null $translationDomain The domain of the translation messages. - * @param ObjectInitializerInterface[] $objectInitializers The initializers for preparing objects before validation. + * @param mixed $root The value passed to the validator + * @param MetadataFactoryInterface $metadataFactory The factory for obtaining metadata instances + * @param ConstraintValidatorFactoryInterface $validatorFactory The factory for creating constraint validators + * @param TranslatorInterface $translator The translator for translating violation messages + * @param string|null $translationDomain The domain of the translation messages + * @param ObjectInitializerInterface[] $objectInitializers The initializers for preparing objects before validation * * @throws UnexpectedTypeException If any of the object initializers is not an instance of ObjectInitializerInterface */ diff --git a/src/Symfony/Component/Validator/ValidationVisitorInterface.php b/src/Symfony/Component/Validator/ValidationVisitorInterface.php index 0ab7b7366776c..b6c6e9f1cb9d3 100644 --- a/src/Symfony/Component/Validator/ValidationVisitorInterface.php +++ b/src/Symfony/Component/Validator/ValidationVisitorInterface.php @@ -56,11 +56,11 @@ interface ValidationVisitorInterface * does not find metadata for the given value, it will fail with an * exception. * - * @param mixed $value The value to validate. - * @param string $group The validation group to validate. - * @param string $propertyPath The current property path in the validation graph. - * @param bool $traverse Whether to traverse the value if it is traversable. - * @param bool $deep Whether to traverse nested traversable values recursively. + * @param mixed $value The value to validate + * @param string $group The validation group to validate + * @param string $propertyPath The current property path in the validation graph + * @param bool $traverse Whether to traverse the value if it is traversable + * @param bool $deep Whether to traverse nested traversable values recursively * * @throws Exception\NoSuchMetadataException If no metadata can be found for * the given value. @@ -73,10 +73,10 @@ public function validate($value, $group, $propertyPath, $traverse = false, $deep * This method implements the Visitor design pattern. See also * {@link ValidationVisitorInterface}. * - * @param MetadataInterface $metadata The metadata holding the constraints. - * @param mixed $value The value to validate. - * @param string $group The validation group to validate. - * @param string $propertyPath The current property path in the validation graph. + * @param MetadataInterface $metadata The metadata holding the constraints + * @param mixed $value The value to validate + * @param string $group The validation group to validate + * @param string $propertyPath The current property path in the validation graph */ public function visit(MetadataInterface $metadata, $value, $group, $propertyPath); } diff --git a/src/Symfony/Component/Validator/Validator/ValidatorInterface.php b/src/Symfony/Component/Validator/Validator/ValidatorInterface.php index 3aafa34ea09cc..1cc9c6dd55940 100644 --- a/src/Symfony/Component/Validator/Validator/ValidatorInterface.php +++ b/src/Symfony/Component/Validator/Validator/ValidatorInterface.php @@ -38,7 +38,7 @@ interface ValidatorInterface extends MetadataFactoryInterface * validate. If none is given, * "Default" is assumed * - * @return ConstraintViolationListInterface A list of constraint violations. + * @return ConstraintViolationListInterface A list of constraint violations * If the list is empty, validation * succeeded */ @@ -53,7 +53,7 @@ public function validate($value, $constraints = null, $groups = null); * @param array|null $groups The validation groups to validate. If * none is given, "Default" is assumed * - * @return ConstraintViolationListInterface A list of constraint violations. + * @return ConstraintViolationListInterface A list of constraint violations * If the list is empty, validation * succeeded */ @@ -70,7 +70,7 @@ public function validateProperty($object, $propertyName, $groups = null); * @param array|null $groups The validation groups to validate. If * none is given, "Default" is assumed * - * @return ConstraintViolationListInterface A list of constraint violations. + * @return ConstraintViolationListInterface A list of constraint violations * If the list is empty, validation * succeeded */ diff --git a/src/Symfony/Component/Validator/ValidatorBuilderInterface.php b/src/Symfony/Component/Validator/ValidatorBuilderInterface.php index e15fb7aa14e67..690d286789955 100644 --- a/src/Symfony/Component/Validator/ValidatorBuilderInterface.php +++ b/src/Symfony/Component/Validator/ValidatorBuilderInterface.php @@ -187,7 +187,7 @@ public function setApiVersion($apiVersion); /** * Builds and returns a new validator object. * - * @return ValidatorInterface The built validator. + * @return ValidatorInterface The built validator */ public function getValidator(); } diff --git a/src/Symfony/Component/Validator/ValidatorInterface.php b/src/Symfony/Component/Validator/ValidatorInterface.php index cffc1388d7f6f..58b8cd6e4cbb7 100644 --- a/src/Symfony/Component/Validator/ValidatorInterface.php +++ b/src/Symfony/Component/Validator/ValidatorInterface.php @@ -32,9 +32,9 @@ interface ValidatorInterface * disabled in Symfony 3.0. * * @param mixed $value The value to validate - * @param array|null $groups The validation groups to validate. - * @param bool $traverse Whether to traverse the value if it is traversable. - * @param bool $deep Whether to traverse nested traversable values recursively. + * @param array|null $groups The validation groups to validate + * @param bool $traverse Whether to traverse the value if it is traversable + * @param bool $deep Whether to traverse nested traversable values recursively * * @return ConstraintViolationListInterface A list of constraint violations. If the * list is empty, validation succeeded. @@ -47,9 +47,9 @@ public function validate($value, $groups = null, $traverse = false, $deep = fals * The accepted values depend on the {@link MetadataFactoryInterface} * implementation. * - * @param mixed $containingValue The value containing the property. - * @param string $property The name of the property to validate. - * @param array|null $groups The validation groups to validate. + * @param mixed $containingValue The value containing the property + * @param string $property The name of the property to validate + * @param array|null $groups The validation groups to validate * * @return ConstraintViolationListInterface A list of constraint violations. If the * list is empty, validation succeeded. @@ -62,11 +62,11 @@ public function validateProperty($containingValue, $property, $groups = null); * The accepted values depend on the {@link MetadataFactoryInterface} * implementation. * - * @param mixed $containingValue The value containing the property. + * @param mixed $containingValue The value containing the property * @param string $property The name of the property to validate * @param string $value The value to validate against the * constraints of the property. - * @param array|null $groups The validation groups to validate. + * @param array|null $groups The validation groups to validate * * @return ConstraintViolationListInterface A list of constraint violations. If the * list is empty, validation succeeded. @@ -76,9 +76,9 @@ public function validatePropertyValue($containingValue, $property, $value, $grou /** * Validates a value against a constraint or a list of constraints. * - * @param mixed $value The value to validate. - * @param Constraint|Constraint[] $constraints The constraint(s) to validate against. - * @param array|null $groups The validation groups to validate. + * @param mixed $value The value to validate + * @param Constraint|Constraint[] $constraints The constraint(s) to validate against + * @param array|null $groups The validation groups to validate * * @return ConstraintViolationListInterface A list of constraint violations. If the * list is empty, validation succeeded. @@ -92,7 +92,7 @@ public function validateValue($value, $constraints, $groups = null); /** * Returns the factory for metadata instances. * - * @return MetadataFactoryInterface The metadata factory. + * @return MetadataFactoryInterface The metadata factory * * @deprecated since version 2.5, to be removed in 3.0. * Use {@link Validator\ValidatorInterface::getMetadataFor()} or diff --git a/src/Symfony/Component/VarDumper/Caster/Caster.php b/src/Symfony/Component/VarDumper/Caster/Caster.php index 23e72e87701ee..4312e59352f1d 100644 --- a/src/Symfony/Component/VarDumper/Caster/Caster.php +++ b/src/Symfony/Component/VarDumper/Caster/Caster.php @@ -36,10 +36,10 @@ class Caster /** * Casts objects to arrays and adds the dynamic property prefix. * - * @param object $obj The object to cast. - * @param \ReflectionClass $reflector The class reflector to use for inspecting the object definition. + * @param object $obj The object to cast + * @param \ReflectionClass $reflector The class reflector to use for inspecting the object definition * - * @return array The array-cast of the object, with prefixed dynamic properties. + * @return array The array-cast of the object, with prefixed dynamic properties */ public static function castObject($obj, \ReflectionClass $reflector) { @@ -70,9 +70,9 @@ public static function castObject($obj, \ReflectionClass $reflector) * By default, a single match in the $filter bit field filters properties out, following an "or" logic. * When EXCLUDE_STRICT is set, an "and" logic is applied: all bits must match for a property to be removed. * - * @param array $a The array containing the properties to filter. - * @param int $filter A bit field of Caster::EXCLUDE_* constants specifying which properties to filter out. - * @param string[] $listedProperties List of properties to exclude when Caster::EXCLUDE_VERBOSE is set, and to preserve when Caster::EXCLUDE_NOT_IMPORTANT is set. + * @param array $a The array containing the properties to filter + * @param int $filter A bit field of Caster::EXCLUDE_* constants specifying which properties to filter out + * @param string[] $listedProperties List of properties to exclude when Caster::EXCLUDE_VERBOSE is set, and to preserve when Caster::EXCLUDE_NOT_IMPORTANT is set * * @return array The filtered array */ diff --git a/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php b/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php index 50dc79161bacf..c11071f611fd7 100644 --- a/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php +++ b/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php @@ -125,7 +125,7 @@ abstract class AbstractCloner implements ClonerInterface private $filter = 0; /** - * @param callable[]|null $casters A map of casters. + * @param callable[]|null $casters A map of casters * * @see addCasters */ @@ -146,7 +146,7 @@ public function __construct(array $casters = null) * Resource types are to be prefixed with a `:`, * see e.g. static::$defaultCasters. * - * @param callable[] $casters A map of casters. + * @param callable[] $casters A map of casters */ public function addCasters(array $casters) { @@ -178,10 +178,10 @@ public function setMaxString($maxString) /** * Clones a PHP variable. * - * @param mixed $var Any PHP variable. - * @param int $filter A bit field of Caster::EXCLUDE_* constants. + * @param mixed $var Any PHP variable + * @param int $filter A bit field of Caster::EXCLUDE_* constants * - * @return Data The cloned variable represented by a Data object. + * @return Data The cloned variable represented by a Data object */ public function cloneVar($var, $filter = 0) { @@ -204,19 +204,19 @@ public function cloneVar($var, $filter = 0) /** * Effectively clones the PHP variable. * - * @param mixed $var Any PHP variable. + * @param mixed $var Any PHP variable * - * @return array The cloned variable represented in an array. + * @return array The cloned variable represented in an array */ abstract protected function doClone($var); /** * Casts an object to an array representation. * - * @param Stub $stub The Stub for the casted object. - * @param bool $isNested True if the object is nested in the dumped structure. + * @param Stub $stub The Stub for the casted object + * @param bool $isNested True if the object is nested in the dumped structure * - * @return array The object casted as array. + * @return array The object casted as array */ protected function castObject(Stub $stub, $isNested) { @@ -253,10 +253,10 @@ protected function castObject(Stub $stub, $isNested) /** * Casts a resource to an array representation. * - * @param Stub $stub The Stub for the casted resource. - * @param bool $isNested True if the object is nested in the dumped structure. + * @param Stub $stub The Stub for the casted resource + * @param bool $isNested True if the object is nested in the dumped structure * - * @return array The resource casted as array. + * @return array The resource casted as array */ protected function castResource(Stub $stub, $isNested) { @@ -276,13 +276,13 @@ protected function castResource(Stub $stub, $isNested) /** * Calls a custom caster. * - * @param callable $callback The caster. - * @param object|resource $obj The object/resource being casted. - * @param array $a The result of the previous cast for chained casters. - * @param Stub $stub The Stub for the casted object/resource. - * @param bool $isNested True if $obj is nested in the dumped structure. + * @param callable $callback The caster + * @param object|resource $obj The object/resource being casted + * @param array $a The result of the previous cast for chained casters + * @param Stub $stub The Stub for the casted object/resource + * @param bool $isNested True if $obj is nested in the dumped structure * - * @return array The casted object/resource. + * @return array The casted object/resource */ private function callCaster($callback, $obj, $a, $stub, $isNested) { diff --git a/src/Symfony/Component/VarDumper/Cloner/ClonerInterface.php b/src/Symfony/Component/VarDumper/Cloner/ClonerInterface.php index c1df5933dbf2e..7ed287a2ddf0d 100644 --- a/src/Symfony/Component/VarDumper/Cloner/ClonerInterface.php +++ b/src/Symfony/Component/VarDumper/Cloner/ClonerInterface.php @@ -19,9 +19,9 @@ interface ClonerInterface /** * Clones a PHP variable. * - * @param mixed $var Any PHP variable. + * @param mixed $var Any PHP variable * - * @return Data The cloned variable represented by a Data object. + * @return Data The cloned variable represented by a Data object */ public function cloneVar($var); } diff --git a/src/Symfony/Component/VarDumper/Cloner/Data.php b/src/Symfony/Component/VarDumper/Cloner/Data.php index 0aa13ef1ecaf9..cf21f0e4bcc43 100644 --- a/src/Symfony/Component/VarDumper/Cloner/Data.php +++ b/src/Symfony/Component/VarDumper/Cloner/Data.php @@ -22,7 +22,7 @@ class Data private $useRefHandles = -1; /** - * @param array $data A array as returned by ClonerInterface::cloneVar(). + * @param array $data A array as returned by ClonerInterface::cloneVar() */ public function __construct(array $data) { @@ -30,7 +30,7 @@ public function __construct(array $data) } /** - * @return array The raw data structure. + * @return array The raw data structure */ public function getRawData() { @@ -40,9 +40,9 @@ public function getRawData() /** * Returns a depth limited clone of $this. * - * @param int $maxDepth The max dumped depth level. + * @param int $maxDepth The max dumped depth level * - * @return self A clone of $this. + * @return self A clone of $this */ public function withMaxDepth($maxDepth) { @@ -55,9 +55,9 @@ public function withMaxDepth($maxDepth) /** * Limits the number of elements per depth level. * - * @param int $maxItemsPerDepth The max number of items dumped per depth level. + * @param int $maxItemsPerDepth The max number of items dumped per depth level * - * @return self A clone of $this. + * @return self A clone of $this */ public function withMaxItemsPerDepth($maxItemsPerDepth) { @@ -70,9 +70,9 @@ public function withMaxItemsPerDepth($maxItemsPerDepth) /** * Enables/disables objects' identifiers tracking. * - * @param bool $useRefHandles False to hide global ref. handles. + * @param bool $useRefHandles False to hide global ref. handles * - * @return self A clone of $this. + * @return self A clone of $this */ public function withRefHandles($useRefHandles) { @@ -85,11 +85,11 @@ public function withRefHandles($useRefHandles) /** * Returns a depth limited clone of $this. * - * @param int $maxDepth The max dumped depth level. - * @param int $maxItemsPerDepth The max number of items dumped per depth level. - * @param bool $useRefHandles False to hide ref. handles. + * @param int $maxDepth The max dumped depth level + * @param int $maxItemsPerDepth The max number of items dumped per depth level + * @param bool $useRefHandles False to hide ref. handles * - * @return self A depth limited clone of $this. + * @return self A depth limited clone of $this * * @deprecated since Symfony 2.7, to be removed in 3.0. Use withMaxDepth, withMaxItemsPerDepth or withRefHandles instead. */ @@ -117,10 +117,10 @@ public function dump(DumperInterface $dumper) /** * Depth-first dumping of items. * - * @param DumperInterface $dumper The dumper being used for dumping. - * @param Cursor $cursor A cursor used for tracking dumper state position. - * @param array &$refs A map of all references discovered while dumping. - * @param mixed $item A Stub object or the original value being dumped. + * @param DumperInterface $dumper The dumper being used for dumping + * @param Cursor $cursor A cursor used for tracking dumper state position + * @param array &$refs A map of all references discovered while dumping + * @param mixed $item A Stub object or the original value being dumped */ private function dumpItem($dumper, $cursor, &$refs, $item) { @@ -209,13 +209,13 @@ private function dumpItem($dumper, $cursor, &$refs, $item) * Dumps children of hash structures. * * @param DumperInterface $dumper - * @param Cursor $parentCursor The cursor of the parent hash. - * @param array &$refs A map of all references discovered while dumping. - * @param array $children The children to dump. - * @param int $hashCut The number of items removed from the original hash. - * @param string $hashType A Cursor::HASH_* const. + * @param Cursor $parentCursor The cursor of the parent hash + * @param array &$refs A map of all references discovered while dumping + * @param array $children The children to dump + * @param int $hashCut The number of items removed from the original hash + * @param string $hashType A Cursor::HASH_* const * - * @return int The final number of removed items. + * @return int The final number of removed items */ private function dumpChildren($dumper, $parentCursor, &$refs, $children, $hashCut, $hashType) { diff --git a/src/Symfony/Component/VarDumper/Cloner/DumperInterface.php b/src/Symfony/Component/VarDumper/Cloner/DumperInterface.php index eba23d42297ec..cb7981694f981 100644 --- a/src/Symfony/Component/VarDumper/Cloner/DumperInterface.php +++ b/src/Symfony/Component/VarDumper/Cloner/DumperInterface.php @@ -21,40 +21,40 @@ interface DumperInterface /** * Dumps a scalar value. * - * @param Cursor $cursor The Cursor position in the dump. - * @param string $type The PHP type of the value being dumped. - * @param scalar $value The scalar value being dumped. + * @param Cursor $cursor The Cursor position in the dump + * @param string $type The PHP type of the value being dumped + * @param scalar $value The scalar value being dumped */ public function dumpScalar(Cursor $cursor, $type, $value); /** * Dumps a string. * - * @param Cursor $cursor The Cursor position in the dump. - * @param string $str The string being dumped. - * @param bool $bin Whether $str is UTF-8 or binary encoded. - * @param int $cut The number of characters $str has been cut by. + * @param Cursor $cursor The Cursor position in the dump + * @param string $str The string being dumped + * @param bool $bin Whether $str is UTF-8 or binary encoded + * @param int $cut The number of characters $str has been cut by */ public function dumpString(Cursor $cursor, $str, $bin, $cut); /** * Dumps while entering an hash. * - * @param Cursor $cursor The Cursor position in the dump. - * @param int $type A Cursor::HASH_* const for the type of hash. - * @param string $class The object class, resource type or array count. - * @param bool $hasChild When the dump of the hash has child item. + * @param Cursor $cursor The Cursor position in the dump + * @param int $type A Cursor::HASH_* const for the type of hash + * @param string $class The object class, resource type or array count + * @param bool $hasChild When the dump of the hash has child item */ public function enterHash(Cursor $cursor, $type, $class, $hasChild); /** * Dumps while leaving an hash. * - * @param Cursor $cursor The Cursor position in the dump. - * @param int $type A Cursor::HASH_* const for the type of hash. - * @param string $class The object class, resource type or array count. - * @param bool $hasChild When the dump of the hash has child item. - * @param int $cut The number of items the hash has been cut by. + * @param Cursor $cursor The Cursor position in the dump + * @param int $type A Cursor::HASH_* const for the type of hash + * @param string $class The object class, resource type or array count + * @param bool $hasChild When the dump of the hash has child item + * @param int $cut The number of items the hash has been cut by */ public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut); } diff --git a/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php b/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php index 58fd202c0ea16..c78783b00caec 100644 --- a/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php @@ -32,8 +32,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface private $charset; /** - * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput. - * @param string $charset The default character encoding to use for non-UTF8 strings. + * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput + * @param string $charset The default character encoding to use for non-UTF8 strings */ public function __construct($output = null, $charset = null) { @@ -49,9 +49,9 @@ public function __construct($output = null, $charset = null) /** * Sets the output destination of the dumps. * - * @param callable|resource|string $output A line dumper callable, an opened stream or an output path. + * @param callable|resource|string $output A line dumper callable, an opened stream or an output path * - * @return callable|resource|string The previous output destination. + * @return callable|resource|string The previous output destination */ public function setOutput($output) { @@ -74,9 +74,9 @@ public function setOutput($output) /** * Sets the default character encoding to use for non-UTF8 strings. * - * @param string $charset The default character encoding to use for non-UTF8 strings. + * @param string $charset The default character encoding to use for non-UTF8 strings * - * @return string The previous charset. + * @return string The previous charset */ public function setCharset($charset) { @@ -93,9 +93,9 @@ public function setCharset($charset) /** * Sets the indentation pad string. * - * @param string $pad A string the will be prepended to dumped lines, repeated by nesting level. + * @param string $pad A string the will be prepended to dumped lines, repeated by nesting level * - * @return string The indent pad. + * @return string The indent pad */ public function setIndentPad($pad) { @@ -108,8 +108,8 @@ public function setIndentPad($pad) /** * Dumps a Data object. * - * @param Data $data A Data object. - * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path. + * @param Data $data A Data object + * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path */ public function dump(Data $data, $output = null) { @@ -136,7 +136,7 @@ public function dump(Data $data, $output = null) /** * Dumps the current line. * - * @param int $depth The recursive depth in the dumped structure for the line being dumped. + * @param int $depth The recursive depth in the dumped structure for the line being dumped */ protected function dumpLine($depth) { @@ -147,8 +147,8 @@ protected function dumpLine($depth) /** * Generic line dumper callback. * - * @param string $line The line to write. - * @param int $depth The recursive depth in the dumped structure. + * @param string $line The line to write + * @param int $depth The recursive depth in the dumped structure */ protected function echoLine($line, $depth, $indentPad) { @@ -160,9 +160,9 @@ protected function echoLine($line, $depth, $indentPad) /** * Converts a non-UTF-8 string to UTF-8. * - * @param string $s The non-UTF-8 string to convert. + * @param string $s The non-UTF-8 string to convert * - * @return string The string converted to UTF-8. + * @return string The string converted to UTF-8 */ protected function utf8Encode($s) { diff --git a/src/Symfony/Component/VarDumper/Dumper/CliDumper.php b/src/Symfony/Component/VarDumper/Dumper/CliDumper.php index bbbfa8a668a98..42442894bfbdd 100644 --- a/src/Symfony/Component/VarDumper/Dumper/CliDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/CliDumper.php @@ -97,7 +97,7 @@ public function setMaxStringWidth($maxStringWidth) /** * Configures styles. * - * @param array $styles A map of style names to style definitions. + * @param array $styles A map of style names to style definitions */ public function setStyles(array $styles) { @@ -280,9 +280,9 @@ public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut) /** * Dumps an ellipsis for cut children. * - * @param Cursor $cursor The Cursor position in the dump. - * @param bool $hasChild When the dump of the hash has child item. - * @param int $cut The number of items the hash has been cut by. + * @param Cursor $cursor The Cursor position in the dump + * @param bool $hasChild When the dump of the hash has child item + * @param int $cut The number of items the hash has been cut by */ protected function dumpEllipsis(Cursor $cursor, $hasChild, $cut) { @@ -300,7 +300,7 @@ protected function dumpEllipsis(Cursor $cursor, $hasChild, $cut) /** * Dumps a key in a hash structure. * - * @param Cursor $cursor The Cursor position in the dump. + * @param Cursor $cursor The Cursor position in the dump */ protected function dumpKey(Cursor $cursor) { @@ -368,11 +368,11 @@ protected function dumpKey(Cursor $cursor) /** * Decorates a value with some style. * - * @param string $style The type of style being applied. - * @param string $value The value being styled. - * @param array $attr Optional context information. + * @param string $style The type of style being applied + * @param string $value The value being styled + * @param array $attr Optional context information * - * @return string The value with style decoration. + * @return string The value with style decoration */ protected function style($style, $value, $attr = array()) { @@ -412,7 +412,7 @@ protected function style($style, $value, $attr = array()) } /** - * @return bool Tells if the current output stream supports ANSI colors or not. + * @return bool Tells if the current output stream supports ANSI colors or not */ protected function supportsColors() { diff --git a/src/Symfony/Component/VarDumper/Dumper/DataDumperInterface.php b/src/Symfony/Component/VarDumper/Dumper/DataDumperInterface.php index ee6060cebf647..2c3d9db850d08 100644 --- a/src/Symfony/Component/VarDumper/Dumper/DataDumperInterface.php +++ b/src/Symfony/Component/VarDumper/Dumper/DataDumperInterface.php @@ -23,7 +23,7 @@ interface DataDumperInterface /** * Dumps a Data object. * - * @param Data $data A Data object. + * @param Data $data A Data object */ public function dump(Data $data); } diff --git a/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php b/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php index 8a48554623ec7..a8fda206a06a7 100644 --- a/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php @@ -78,7 +78,7 @@ public function setStyles(array $styles) /** * Sets an HTML header that will be dumped once in the output stream. * - * @param string $header An HTML string. + * @param string $header An HTML string */ public function setDumpHeader($header) { @@ -88,8 +88,8 @@ public function setDumpHeader($header) /** * Sets an HTML prefix and suffix that will encapse every single dump. * - * @param string $prefix The prepended HTML string. - * @param string $suffix The appended HTML string. + * @param string $prefix The prepended HTML string + * @param string $suffix The appended HTML string */ public function setDumpBoundaries($prefix, $suffix) { diff --git a/src/Symfony/Component/Yaml/Dumper.php b/src/Symfony/Component/Yaml/Dumper.php index 9bd9389c07483..05817f5d73063 100644 --- a/src/Symfony/Component/Yaml/Dumper.php +++ b/src/Symfony/Component/Yaml/Dumper.php @@ -28,7 +28,7 @@ class Dumper /** * Sets the indentation. * - * @param int $num The amount of spaces to use for indentation of nested nodes. + * @param int $num The amount of spaces to use for indentation of nested nodes */ public function setIndentation($num) { diff --git a/src/Symfony/Component/Yaml/Escaper.php b/src/Symfony/Component/Yaml/Escaper.php index 7bac8dde40ead..a74f14dd9c17a 100644 --- a/src/Symfony/Component/Yaml/Escaper.php +++ b/src/Symfony/Component/Yaml/Escaper.php @@ -46,7 +46,7 @@ class Escaper * * @param string $value A PHP value * - * @return bool True if the value would require double quotes. + * @return bool True if the value would require double quotes */ public static function requiresDoubleQuoting($value) { @@ -70,7 +70,7 @@ public static function escapeWithDoubleQuotes($value) * * @param string $value A PHP value * - * @return bool True if the value would require single quotes. + * @return bool True if the value would require single quotes */ public static function requiresSingleQuoting($value) { diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php index 3c02243d9025d..7cdb964393bc2 100644 --- a/src/Symfony/Component/Yaml/Parser.php +++ b/src/Symfony/Component/Yaml/Parser.php @@ -30,17 +30,21 @@ class Parser private $currentLineNb = -1; private $currentLine = ''; private $refs = array(); + private $skippedLineNumbers = array(); + private $locallySkippedLineNumbers = array(); /** * Constructor. * * @param int $offset The offset of YAML document (used for line numbers in error messages) * @param int|null $totalNumberOfLines The overall number of lines being parsed + * @param int[] $skippedLineNumbers Number of comment lines that have been skipped by the parser */ - public function __construct($offset = 0, $totalNumberOfLines = null) + public function __construct($offset = 0, $totalNumberOfLines = null, array $skippedLineNumbers = array()) { $this->offset = $offset; $this->totalNumberOfLines = $totalNumberOfLines; + $this->skippedLineNumbers = $skippedLineNumbers; } /** @@ -101,25 +105,18 @@ public function parse($value, $exceptionOnInvalidType = false, $objectSupport = // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new self($c, $this->totalNumberOfLines); - $parser->refs = &$this->refs; - $data[] = $parser->parse($this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap); + $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap); } else { if (isset($values['leadspaces']) && preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches) ) { // this is a compact notation element, add to next block and parse - $c = $this->getRealCurrentLineNb(); - $parser = new self($c, $this->totalNumberOfLines); - $parser->refs = &$this->refs; - $block = $values['value']; if ($this->isNextLineIndented()) { $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1); } - $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap); + $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $exceptionOnInvalidType, $objectSupport, $objectForMap); } else { $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap, $context); } @@ -175,10 +172,7 @@ public function parse($value, $exceptionOnInvalidType = false, $objectSupport = } else { $value = $this->getNextEmbedBlock(); } - $c = $this->getRealCurrentLineNb() + 1; - $parser = new self($c, $this->totalNumberOfLines); - $parser->refs = &$this->refs; - $parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap); + $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $exceptionOnInvalidType, $objectSupport, $objectForMap); if (!is_array($parsed)) { throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); @@ -226,10 +220,7 @@ public function parse($value, $exceptionOnInvalidType = false, $objectSupport = $data[$key] = null; } } else { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new self($c, $this->totalNumberOfLines); - $parser->refs = &$this->refs; - $value = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap); + $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap); // Spec: Keys MUST be unique; first one wins. // But overwriting is allowed when a merge node is used in current block. if ($allowOverwrite || !isset($data[$key])) { @@ -323,6 +314,24 @@ public function parse($value, $exceptionOnInvalidType = false, $objectSupport = return empty($data) ? null : $data; } + private function parseBlock($offset, $yaml, $exceptionOnInvalidType, $objectSupport, $objectForMap) + { + $skippedLineNumbers = $this->skippedLineNumbers; + + foreach ($this->locallySkippedLineNumbers as $lineNumber) { + if ($lineNumber < $offset) { + continue; + } + + $skippedLineNumbers[] = $lineNumber; + } + + $parser = new self($offset, $this->totalNumberOfLines, $skippedLineNumbers); + $parser->refs = &$this->refs; + + return $parser->parse($yaml, $exceptionOnInvalidType, $objectSupport, $objectForMap); + } + /** * Returns the current line number (takes the offset into account). * @@ -330,7 +339,17 @@ public function parse($value, $exceptionOnInvalidType = false, $objectSupport = */ private function getRealCurrentLineNb() { - return $this->currentLineNb + $this->offset; + $realCurrentLineNumber = $this->currentLineNb + $this->offset; + + foreach ($this->skippedLineNumbers as $skippedLineNumber) { + if ($skippedLineNumber > $realCurrentLineNumber) { + break; + } + + ++$realCurrentLineNumber; + } + + return $realCurrentLineNumber; } /** @@ -433,6 +452,14 @@ private function getNextEmbedBlock($indentation = null, $inSequence = false) // we ignore "comment" lines only when we are not inside a scalar block if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) { + // remember ignored comment lines (they are used later in nested + // parser calls to determine real line numbers) + // + // CAUTION: beware to not populate the global property here as it + // will otherwise influence the getRealCurrentLineNb() call here + // for consecutive comment lines and subsequent embedded blocks + $this->locallySkippedLineNumbers[] = $this->getRealCurrentLineNb(); + continue; } @@ -468,10 +495,18 @@ private function moveToNextLine() /** * Moves the parser to the previous line. + * + * @return bool */ private function moveToPreviousLine() { + if ($this->currentLineNb < 1) { + return false; + } + $this->currentLine = $this->lines[--$this->currentLineNb]; + + return true; } /** diff --git a/src/Symfony/Component/Yaml/Tests/ParserTest.php b/src/Symfony/Component/Yaml/Tests/ParserTest.php index d05ff391fcd12..7b3681953558b 100644 --- a/src/Symfony/Component/Yaml/Tests/ParserTest.php +++ b/src/Symfony/Component/Yaml/Tests/ParserTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Yaml\Tests; +use Symfony\Bridge\PhpUnit\ErrorAssert; use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Parser; @@ -656,6 +657,25 @@ public function testSequenceInMappingStartedBySingleDashLine() $this->assertSame($expected, $this->parser->parse($yaml)); } + public function testSequenceFollowedByCommentEmbeddedInMapping() + { + $yaml = << array( + 'b' => array('c'), + 'd' => 'e', + ), + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + /** * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ @@ -911,27 +931,14 @@ public function testFloatKeys() */ public function testColonInMappingValueException() { - $yaml = <<parser; + + ErrorAssert::assertDeprecationsAreTriggered('Using a colon in the unquoted mapping value "bar: baz" in line 1 is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', function () use ($parser) { + $yaml = <<parse($yaml); }); - - $this->parser->parse($yaml); - - restore_error_handler(); - - $this->assertCount(1, $deprecations); - $this->assertContains('Using a colon in the unquoted mapping value "bar: baz" in line 1 is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', $deprecations[0]); } public function testColonInMappingValueExceptionNotTriggeredByColonInComment() @@ -1128,6 +1135,74 @@ public function testAdditionallyIndentedLinesAreParsedAsNewLinesInFoldedBlocks() $this->parser->parse($yaml) ); } + + /** + * @param $lineNumber + * @param $yaml + * @dataProvider parserThrowsExceptionWithCorrectLineNumberProvider + */ + public function testParserThrowsExceptionWithCorrectLineNumber($lineNumber, $yaml) + { + $this->setExpectedException( + '\Symfony\Component\Yaml\Exception\ParseException', + sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber) + ); + + $this->parser->parse($yaml); + } + + public function parserThrowsExceptionWithCorrectLineNumberProvider() + { + return array( + array( + 4, + <<