diff --git a/.github/build-packages.php b/.github/build-packages.php index 02a2239732be2..56112b753ad32 100644 --- a/.github/build-packages.php +++ b/.github/build-packages.php @@ -11,7 +11,7 @@ $mergeBase = trim(shell_exec(sprintf('git merge-base %s HEAD', array_shift($dirs)))); $packages = array(); -$flags = PHP_VERSION_ID >= 50400 ? JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE : 0; +$flags = \PHP_VERSION_ID >= 50400 ? JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE : 0; foreach ($dirs as $k => $dir) { if (!system("git diff --name-only $mergeBase -- $dir", $exitStatus)) { diff --git a/CHANGELOG-3.2.md b/CHANGELOG-3.2.md index c76c8add66003..de1e0fd980928 100644 --- a/CHANGELOG-3.2.md +++ b/CHANGELOG-3.2.md @@ -7,6 +7,29 @@ in 3.2 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/v3.2.0...v3.2.1 +* 3.2.9 (2017-05-29) + + * bug #22847 [Console] ChoiceQuestion must have choices (ro0NL) + * bug #22900 [FrameworkBundle][Console] Fix the override of a command registered by the kernel (aaa2000) + * bug #22910 [Filesystem] improve error handling in lock() (xabbuh) + * bug #22924 [Cache] Dont use pipelining with RedisCluster (nicolas-grekas) + * bug #22718 [Console] Fixed different behaviour of key and value user inputs in multiple choice question (borNfreee) + * bug #22829 [Yaml] fix colon without space deprecation (xabbuh) + * bug #22901 Fix missing abstract key in XmlDumper (weaverryan) + * bug #22912 [DI] Avoid private call to Container::has() (ro0NL) + * bug #22866 [DI] Check for privates before shared services (ro0NL) + * bug #22874 [WebProfilerBundle] Fix sub-requests display in time profiler panel (nicolas-grekas) + * bug #22817 [PhpUnitBridge] optional error handler arguments (xabbuh) + * bug #22752 Improved how profiler errors are displayed on small screens (javiereguiluz) + * bug #22715 [FrameworkBundle] remove Security deps from the require section (xabbuh) + * bug #22647 [VarDumper] Fix dumping of non-nested stubs (nicolas-grekas) + * bug #22409 [Yaml] respect inline level when dumping objects as maps (goetas, xabbuh) + * bug #22584 [Security] Avoid unnecessary route lookup for empty logout path (ro0NL) + * bug #22690 [Console] Fix errors not rethrown even if not handled by console.error listeners (chalasr) + * bug #22669 [FrameworkBundle] AbstractConfigCommand: do not try registering bundles twice (ogizanagi) + * bug #22676 [FrameworkBundle] Adding the extension XML (flug) + * bug #22652 [Workflow] Move twig extension registration to twig bundle (ogizanagi) + * 3.2.8 (2017-05-01) * bug #22550 Allow Upper Case property names in ObjectNormalizer (insekticid) diff --git a/CHANGELOG-3.3.md b/CHANGELOG-3.3.md index 17b9ed1ed3073..8a6626da32d0f 100644 --- a/CHANGELOG-3.3.md +++ b/CHANGELOG-3.3.md @@ -7,6 +7,36 @@ in 3.3 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/v3.3.0...v3.3.1 +* 3.3.1 (2017-06-05) + + * bug #23067 [HttpFoundation][FrameworkBundle] Revert "trusted proxies" BC break (nicolas-grekas) + * bug #23065 [Cache] Fallback to positional when keyed results are broken (nicolas-grekas) + * bug #22981 [DependencyInjection] Fix named args support in ChildDefinition (dunglas) + * bug #23050 [Form][Profiler] Fixes form collector triggering deprecations (ogizanagi) + * bug #22971 [Profiler] Fix code excerpt wrapping (ogizanagi) + * bug #23049 [FrameworkBundle] mitigate BC break with empty trusted_proxies (xabbuh) + * bug #23045 [Cache] fix Redis scheme detection (xabbuh) + * bug #23013 Parse the _controller format in sub-requests (weaverryan) + * bug #23015 [PhpUnitBridge] Fix detection of PHPUnit 5 (enumag) + * bug #23041 [Config] Always protected ClassExistenceResource against bad parents (nicolas-grekas) + * bug #22988 [PropertyInfo][DoctrineBridge] The bigint Doctrine's type must be converted to string (dunglas) + * bug #23014 Fix optional cache warmers are always instantiated whereas they should be lazy-loaded (romainneutron) + * feature #23022 [Di] Remove closure-proxy arguments (nicolas-grekas) + * bug #23024 [EventDispatcher] Fix ContainerAwareEventDispatcher::hasListeners(null) (nicolas-grekas) + * bug #23008 [EventDispatcher] Handle laziness internally instead of relying on ClosureProxyArgument (nicolas-grekas) + * bug #23018 [FrameworkBundle] Fix CacheCollectorPass priority (chalasr) + * bug #23009 [Routing] Allow GET requests to be redirected. Fixes #23004 (frankdejonge) + * bug #22996 [Form] Fix \IntlDateFormatter timezone parameter usage to bypass PHP bug #66323 (romainneutron) + * bug #22965 [Cache] Ignore missing annotations.php (ro0NL) + * bug #22993 [DI] Autowiring exception thrown when inlined service is removed (weaverryan) + * bug #22999 Better DI type deprecation message (weaverryan) + * bug #22985 [Config] Allow empty globs (nicolas-grekas) + * bug #22961 [HttpKernel] Support unknown format in LoggerDataCollector (iltar) + * bug #22991 [DI] Don't throw Autowire exception for removed service with private __construct (weaverryan) + * bug #22968 [Profiler] Fix text selection & click on file links on exception pages (ogizanagi) + * bug #22994 Harden the debugging of Twig filters and functions (stof) + * bug #22960 [Cache] Fix decoration of TagAware adapters in dev (chalasr) + * 3.3.0 (2017-05-29) * bug #22940 [Config] Fallback to regular import when glob fails (nicolas-grekas) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c543c10dc0336..6816e9794a0a2 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -24,20 +24,20 @@ Symfony is the result of the work of many people who made the code better - Wouter De Jong (wouterj) - Romain Neutron (romain) - Grégoire Pineau (lyrixx) + - Robin Chalas (chalas_r) - Joseph Bielawski (stloyd) + - Maxime Steinhausser (ogizanagi) - Karma Dordrak (drak) - - Robin Chalas (chalas_r) - Lukas Kahwe Smith (lsmith) - Martin Hasoň (hason) - - Maxime Steinhausser (ogizanagi) - Jeremy Mikola (jmikola) - Jean-François Simon (jfsimon) - Benjamin Eberlei (beberlei) - Igor Wiedler (igorw) - Eriksen Costa (eriksencosta) - Jules Pietri (heah) - - Sarah Khalil (saro0h) - Roland Franssen (ro0) + - Sarah Khalil (saro0h) - Jonathan Wage (jwage) - Guilhem Niot (energetick) - Diego Saint Esteben (dosten) @@ -49,10 +49,10 @@ Symfony is the result of the work of many people who made the code better - Alexander Mols (asm89) - Bulat Shakirzyanov (avalanche123) - Peter Rehm (rpet) + - Iltar van der Berg (kjarli) - Saša Stamenković (umpirsky) - Henrik Bjørnskov (henrikbjorn) - Miha Vrhovnik - - Roland Franssen (ro0) - Diego Saint Esteben (dii3g0) - Konstantin Kudryashov (everzet) - Bilal Amarni (bamarni) @@ -64,8 +64,8 @@ Symfony is the result of the work of many people who made the code better - Michel Weimerskirch (mweimerskirch) - Eric Clemmons (ericclemmons) - Charles Sarrazin (csarrazi) - - Pierre du Plessis (pierredup) - Christian Raue + - Pierre du Plessis (pierredup) - Arnout Boks (aboks) - Deni - Henrik Westphal (snc) @@ -77,12 +77,12 @@ Symfony is the result of the work of many people who made the code better - Lee McDermott - Brandon Turner - Luis Cordova (cordoval) + - Jérémy DERUSSÉ (jderusse) - Graham Campbell (graham) - Daniel Holmes (dholmes) - Toni Uebernickel (havvg) - Bart van den Burg (burgov) - Jordan Alliot (jalliot) - - Jérémy DERUSSÉ (jderusse) - John Wards (johnwards) - Dariusz Ruminski - Fran Moreno (franmomu) @@ -92,8 +92,8 @@ Symfony is the result of the work of many people who made the code better - Arnaud Le Blanc (arnaud-lb) - Maxime STEINHAUSSER - Michal Piotrowski (eventhorizon) - - Tim Nagel (merk) - Issei Murasawa (issei_m) + - Tim Nagel (merk) - Brice BERNARD (brikou) - Alexander M. Turek (derrabus) - Baptiste Clavié (talus) @@ -115,6 +115,7 @@ Symfony is the result of the work of many people who made the code better - Fabien Pennequin (fabienpennequin) - Gordon Franke (gimler) - Eric GELOEN (gelo) + - Yonel Ceruto González (yonelceruto) - Daniel Wehner (dawehner) - Tugdual Saunier (tucksaun) - Théo FIDRY (theofidry) @@ -122,7 +123,6 @@ Symfony is the result of the work of many people who made the code better - Florian Lonqueu-Brochard (florianlb) - Sebastiaan Stok (sstok) - Stefano Sala (stefano.sala) - - Yonel Ceruto González (yonelceruto) - Evgeniy (ewgraf) - Juti Noppornpitak (shiroyuki) - Tigran Azatyan (tigranazatyan) @@ -157,6 +157,7 @@ Symfony is the result of the work of many people who made the code better - Amal Raghav (kertz) - Jonathan Ingram (jonathaningram) - Artur Kotyrba + - David Maicher (dmaicher) - jeremyFreeAgent (Jérémy Romey) (jeremyfreeagent) - James Halsall (jaitsu) - Warnar Boekkooi (boekkooi) @@ -166,6 +167,7 @@ Symfony is the result of the work of many people who made the code better - Possum - Dorian Villet (gnutix) - Richard Miller (mr_r_miller) + - Julien Falque (julienfalque) - Mario A. Alvarez Garcia (nomack84) - Dennis Benkert (denderello) - Benjamin Dulau (dbenjamin) @@ -180,7 +182,6 @@ Symfony is the result of the work of many people who made the code better - Daniel Espendiller - sun (sun) - Larry Garfield (crell) - - Julien Falque (julienfalque) - Martin Schuhfuß (usefulthink) - apetitpa - Matthieu Bontemps (mbontemps) @@ -203,6 +204,7 @@ Symfony is the result of the work of many people who made the code better - Tom Van Looy (tvlooy) - Sven Paulus (subsven) - Rui Marinho (ruimarinho) + - Marek Štípek (maryo) - SpacePossum - Eugene Wissner - Julien Brochet (mewt) @@ -217,7 +219,6 @@ Symfony is the result of the work of many people who made the code better - julien pauli (jpauli) - Lorenz Schori - Sébastien Lavoie (lavoiesl) - - David Maicher (dmaicher) - Francois Zaninotto - Alexander Kotynia (olden) - Daniel Tschinder @@ -254,6 +255,7 @@ Symfony is the result of the work of many people who made the code better - Albert Casademont (acasademont) - Jhonny Lidfors (jhonne) - Diego Agulló (aeoris) + - Andreas Schempp (aschempp) - jdhoek - Pavel Batanov (scaytrase) - Nikita Konstantinov @@ -272,8 +274,8 @@ Symfony is the result of the work of many people who made the code better - Michael Holm (hollo) - Marc Weistroff (futurecat) - Christian Schmidt - - Marek Štípek (maryo) - Hidde Wieringa (hiddewie) + - Chad Sikorra (chadsikorra) - Jordan Samouh (jordansamouh) - Chris Smith (cs278) - Florian Klein (docteurklein) @@ -303,10 +305,10 @@ Symfony is the result of the work of many people who made the code better - Francesc Rosàs (frosas) - Massimiliano Arione (garak) - Julien Galenski (ruian) - - Andreas Schempp (aschempp) - Bongiraud Dominique - janschoenherr - Thomas Schulz (king2500) + - Dariusz Rumiński - Berny Cantos (xphere81) - Ricard Clau (ricardclau) - Mark Challoner (markchalloner) @@ -385,7 +387,6 @@ Symfony is the result of the work of many people who made the code better - Christophe L. (christophelau) - Anthon Pang (robocoder) - Emanuele Gaspari (inmarelibero) - - Dariusz Rumiński - Sébastien Santoro (dereckson) - Brian King - Michel Salib (michelsalib) @@ -402,6 +403,7 @@ Symfony is the result of the work of many people who made the code better - Jan Rosier (rosier) - Thomas Royer (cydonia7) - Josip Kruslin + - Asmir Mustafic (goetas) - vagrant - EdgarPE - Florian Pfitzer (marmelatze) @@ -420,7 +422,6 @@ Symfony is the result of the work of many people who made the code better - Marcin Sikoń (marphi) - Dominik Zogg (dominik.zogg) - Marek Pietrzak - - Chad Sikorra (chadsikorra) - franek (franek) - Christian Wahler - Gintautas Miselis @@ -544,7 +545,6 @@ Symfony is the result of the work of many people who made the code better - Andre Rømcke (andrerom) - Nahuel Cuesta (ncuesta) - Chris Boden (cboden) - - Asmir Mustafic (goetas) - Stefan Gehrig (sgehrig) - Hany el-Kerdany - Wang Jingyu @@ -582,6 +582,7 @@ Symfony is the result of the work of many people who made the code better - Sergey Kolodyazhnyy (skolodyazhnyy) - umpirski - Denis Brumann (dbrumann) + - Michael Babker (mbabker) - Quentin de Longraye (quentinus95) - Chris Heng (gigablah) - Richard Bradley @@ -629,6 +630,7 @@ Symfony is the result of the work of many people who made the code better - twifty - Indra Gunawan (guind) - Peter Ward + - insekticid - Julien DIDIER (juliendidier) - Dominik Ritter (dritter) - Sebastian Grodzicki (sgrodzicki) @@ -745,6 +747,7 @@ Symfony is the result of the work of many people who made the code better - Jan Kramer (jankramer) - abdul malik ikhsan (samsonasik) - Henry Snoek (snoek09) + - Jérémy M (th3mouk) - Simone Di Maulo (toretto460) - Christian Morgan - Alexander Miehe (engerim) @@ -761,6 +764,7 @@ Symfony is the result of the work of many people who made the code better - Douglas Reith (douglas_reith) - Harry Walter (haswalt) - Johnson Page (jwpage) + - Ruben Gonzalez (rubenruateltek) - Michael Roterman (wtfzdotnet) - Arno Geurts - Adán Lobato (adanlobato) @@ -886,6 +890,7 @@ Symfony is the result of the work of many people who made the code better - Eddie Jaoude - Antanas Arvasevicius - Haritz Iturbe (hizai) + - Baptiste Meyer (meyerbaptiste) - Nerijus Arlauskas (nercury) - SPolischook - Diego Sapriza @@ -914,6 +919,7 @@ Symfony is the result of the work of many people who made the code better - Jeremy Bush - wizhippo - Viacheslav Sychov + - Tyson Andre - Carlos Ortega Huetos - rpg600 - Péter Buri (burci) @@ -1014,6 +1020,7 @@ Symfony is the result of the work of many people who made the code better - Conrad Kleinespel - Sebastian Utz - Adrien Gallou (agallou) + - Maks Rafalko (bornfree) - Karol Sójko (karolsojko) - Grzegorz Zdanowski (kiler129) - sl_toto (sl_toto) @@ -1048,7 +1055,6 @@ Symfony is the result of the work of many people who made the code better - Kim Laï Trinh - Jason Desrosiers - m.chwedziak - - insekticid - Philip Frank - Lance McNearney - Giorgio Premi @@ -1058,6 +1064,7 @@ Symfony is the result of the work of many people who made the code better - Alberto Pirovano (geezmo) - Pete Mitchell (peterjmit) - Tom Corrigan (tomcorrigan) + - adev - Luis Galeas - Martin Pärtel - George Mponos (gmponos) @@ -1226,6 +1233,7 @@ Symfony is the result of the work of many people who made the code better - Romain Dorgueil - Grayson Koonce (breerly) - Fabien LUCAS (flucas2) + - Indra Gunawan (indragunawan) - Karim Cassam Chenaï (ka) - Nicolas Bastien (nicolas_bastien) - Denis (yethee) @@ -1273,6 +1281,7 @@ Symfony is the result of the work of many people who made the code better - Daan van Renterghem - Nicole Cordes - Bram Van der Sype (brammm) + - Christopher Hertel (chertel) - Guile (guile) - Julien Moulin (lizjulien) - Mauro Foti (skler) @@ -1291,6 +1300,7 @@ Symfony is the result of the work of many people who made the code better - Johann Pardanaud - Trevor Suarez - gedrox + - Alan Bondarchuk - dropfen - Andrey Chernykh - Edvinas Klovas @@ -1303,6 +1313,7 @@ Symfony is the result of the work of many people who made the code better - bertillon - Bertalan Attila - Yannick Bensacq (cibou) + - Gawain Lynch (gawain) - Luca Genuzio (genuzio) - Hans Nilsson (hansnilsson) - Andrew Marcinkevičius (ifdattic) @@ -1312,7 +1323,6 @@ Symfony is the result of the work of many people who made the code better - Dan Patrick (mdpatrick) - Rares Vlaseanu (raresvla) - tante kinast (tante) - - Jérémy M (th3mouk) - Vincent LEFORT (vlefort) - Sadicov Vladimir (xtech) - Kevin EMO (zarcox) @@ -1336,7 +1346,6 @@ Symfony is the result of the work of many people who made the code better - Jonny Schmid (schmidjon) - Götz Gottwald - Veres Lajos - - Michael Babker - grifx - Robert Campbell - Matt Lehner @@ -1415,9 +1424,11 @@ Symfony is the result of the work of many people who made the code better - Yanick Witschi - Ondrej Mirtes - akimsko + - Ben Scott - Youpie - srsbiz - Taylan Kasap + - Michael Orlitzky - Nicolas A. Bérard-Nault - Saem Ghani - Stefan Oderbolz @@ -1430,6 +1441,7 @@ Symfony is the result of the work of many people who made the code better - Ben - Evgeniy Tetenchuk - dasmfm + - Mathias Geat - Arnaud Buathier (arnapou) - chesteroni (chesteroni) - Mauricio Lopez (diaspar) @@ -1516,6 +1528,7 @@ Symfony is the result of the work of many people who made the code better - Abdulkadir N. A. - Yevgen Kovalienia - Lebnik + - Ondřej Führer - Sema - Elan Ruusamäe - Thorsten Hallwas @@ -1568,6 +1581,7 @@ Symfony is the result of the work of many people who made the code better - Bill Hance (billhance) - Bernd Matzner (bmatzner) - Bram Tweedegolf (bram_tweedegolf) + - Brandon Kelly (brandonkelly) - Choong Wei Tjeng (choonge) - Kousuke Ebihara (co3k) - Loïc Vernet (coil) @@ -1675,6 +1689,7 @@ Symfony is the result of the work of many people who made the code better - Andrew Carter (andrewcarteruk) - Adam Elsodaney (archfizz) - Daniel Kolvik (dkvk) + - Marc Lemay (flug) - Jeroen De Dauw (jeroendedauw) - Maxime COLIN (maximecolin) - Muharrem Demirci (mdemirci) diff --git a/UPGRADE-3.3.md b/UPGRADE-3.3.md index 05f44e549e11b..b8d2524654386 100644 --- a/UPGRADE-3.3.md +++ b/UPGRADE-3.3.md @@ -127,7 +127,7 @@ EventDispatcher --------------- * The `ContainerAwareEventDispatcher` class has been deprecated. - Use `EventDispatcher` with closure-proxy injection instead. + Use `EventDispatcher` with closure factories instead. Finder ------ diff --git a/UPGRADE-4.0.md b/UPGRADE-4.0.md index 6c10190c7c502..b06145202e7cd 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -132,7 +132,7 @@ EventDispatcher --------------- * The `ContainerAwareEventDispatcher` class has been removed. - Use `EventDispatcher` with closure-proxy injection instead. + Use `EventDispatcher` with closure factories instead. ExpressionLanguage ------------------ diff --git a/composer.json b/composer.json index 13ad97446582a..f91e8fc1a86b2 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "php": ">=5.5.9", "doctrine/common": "~2.4", "fig/link-util": "^1.0", - "twig/twig": "~1.32|~2.2", + "twig/twig": "~1.34|~2.4", "psr/cache": "~1.0", "psr/container": "^1.0", "psr/link": "^1.0", diff --git a/phpunit b/phpunit index 559660b1df25f..53e1a8dc31dbf 100755 --- a/phpunit +++ b/phpunit @@ -7,7 +7,7 @@ if (!file_exists(__DIR__.'/vendor/symfony/phpunit-bridge/bin/simple-phpunit')) { echo "Unable to find the `simple-phpunit` script in `vendor/symfony/phpunit-bridge/bin/`.\nPlease run `composer update` before running this command.\n"; exit(1); } -if (PHP_VERSION_ID >= 70000 && !getenv('SYMFONY_PHPUNIT_VERSION')) { +if (\PHP_VERSION_ID >= 70000 && !getenv('SYMFONY_PHPUNIT_VERSION')) { putenv('SYMFONY_PHPUNIT_VERSION=6.0'); } putenv('SYMFONY_PHPUNIT_DIR='.__DIR__.'/.phpunit'); diff --git a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php index aba31792f99ee..e07c7b0bc2cba 100644 --- a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php +++ b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php @@ -174,13 +174,13 @@ private function getPhpType($doctrineType) { switch ($doctrineType) { case DBALType::SMALLINT: - case DBALType::BIGINT: case DBALType::INTEGER: return Type::BUILTIN_TYPE_INT; case DBALType::FLOAT: return Type::BUILTIN_TYPE_FLOAT; + case DBALType::BIGINT: case DBALType::STRING: case DBALType::TEXT: case DBALType::GUID: @@ -196,9 +196,6 @@ private function getPhpType($doctrineType) case DBALType::OBJECT: return Type::BUILTIN_TYPE_OBJECT; - - default: - return; } } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php b/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php index 782c39431cd66..8cbd2c3eacb3c 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php @@ -148,13 +148,13 @@ private function createCollector($queries) $registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock(); $registry - ->expects($this->any()) - ->method('getConnectionNames') - ->will($this->returnValue(array('default' => 'doctrine.dbal.default_connection'))); + ->expects($this->any()) + ->method('getConnectionNames') + ->will($this->returnValue(array('default' => 'doctrine.dbal.default_connection'))); $registry - ->expects($this->any()) - ->method('getManagerNames') - ->will($this->returnValue(array('default' => 'doctrine.orm.default_entity_manager'))); + ->expects($this->any()) + ->method('getManagerNames') + ->will($this->returnValue(array('default' => 'doctrine.orm.default_entity_manager'))); $registry->expects($this->any()) ->method('getConnection') ->will($this->returnValue($connection)); diff --git a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php index 277922daefd51..48822d5888fbc 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php @@ -55,6 +55,7 @@ public function testGetProperties() 'bool', 'binary', 'customFoo', + 'bigint', 'foo', 'bar', 'indexedBar', @@ -76,6 +77,7 @@ public function typesProvider() return array( array('id', array(new Type(Type::BUILTIN_TYPE_INT))), array('guid', array(new Type(Type::BUILTIN_TYPE_STRING))), + array('bigint', array(new Type(Type::BUILTIN_TYPE_STRING))), array('float', array(new Type(Type::BUILTIN_TYPE_FLOAT))), array('decimal', array(new Type(Type::BUILTIN_TYPE_STRING))), array('bool', array(new Type(Type::BUILTIN_TYPE_BOOL))), diff --git a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/Fixtures/DoctrineDummy.php b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/Fixtures/DoctrineDummy.php index ad3b7b9227652..580e75803db8f 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/Fixtures/DoctrineDummy.php +++ b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/Fixtures/DoctrineDummy.php @@ -90,5 +90,10 @@ class DoctrineDummy */ private $customFoo; + /** + * @Column(type="bigint") + */ + private $bigint; + public $notMapped; } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php index 0045e76cbca83..a9476f6f17f12 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php @@ -105,8 +105,8 @@ protected function createEntityManagerMock($repositoryMock) ->getMock() ; $em->expects($this->any()) - ->method('getRepository') - ->will($this->returnValue($repositoryMock)) + ->method('getRepository') + ->will($this->returnValue($repositoryMock)) ; $classMetadata = $this->getMockBuilder('Doctrine\Common\Persistence\Mapping\ClassMetadata')->getMock(); @@ -131,8 +131,8 @@ protected function createEntityManagerMock($repositoryMock) ; $classMetadata->reflFields = array('name' => $refl); $em->expects($this->any()) - ->method('getClassMetadata') - ->will($this->returnValue($classMetadata)) + ->method('getClassMetadata') + ->will($this->returnValue($classMetadata)) ; return $em; @@ -363,8 +363,8 @@ public function testValidateUniquenessUsingCustomRepositoryMethod() $repository = $this->createRepositoryMock(); $repository->expects($this->once()) - ->method('findByCustom') - ->will($this->returnValue(array())) + ->method('findByCustom') + ->will($this->returnValue(array())) ; $this->em = $this->createEntityManagerMock($repository); $this->registry = $this->createRegistryMock($this->em); diff --git a/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php b/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php index f85dbb367ca9c..2dad6ef0095bc 100644 --- a/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php +++ b/src/Symfony/Bridge/PhpUnit/SymfonyTestsListener.php @@ -16,7 +16,7 @@ use PHPUnit\Framework\TestSuite; use PHPUnit\Framework\Warning; -if (class_exists('PHPUnit_Framework_BaseTestListener')) { +if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '6.0.0', '<')) { class_alias('Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListener', 'Symfony\Bridge\PhpUnit\SymfonyTestsListener'); return; diff --git a/src/Symfony/Bridge/PhpUnit/TextUI/Command.php b/src/Symfony/Bridge/PhpUnit/TextUI/Command.php index 77b617fdcc269..408533292a656 100644 --- a/src/Symfony/Bridge/PhpUnit/TextUI/Command.php +++ b/src/Symfony/Bridge/PhpUnit/TextUI/Command.php @@ -13,7 +13,7 @@ use PHPUnit\TextUI\Command as BaseCommand; -if (class_exists('PHPUnit_TextUI_Command')) { +if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '6.0.0', '<')) { class_alias('Symfony\Bridge\PhpUnit\Legacy\Command', 'Symfony\Bridge\PhpUnit\TextUI\Command'); return; diff --git a/src/Symfony/Bridge/PhpUnit/TextUI/TestRunner.php b/src/Symfony/Bridge/PhpUnit/TextUI/TestRunner.php index 2d18b4f9afa2b..07fe2d165b627 100644 --- a/src/Symfony/Bridge/PhpUnit/TextUI/TestRunner.php +++ b/src/Symfony/Bridge/PhpUnit/TextUI/TestRunner.php @@ -14,7 +14,7 @@ use PHPUnit\TextUI\TestRunner as BaseRunner; use Symfony\Bridge\PhpUnit\SymfonyTestsListener; -if (class_exists('PHPUnit_TextUI_Command')) { +if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '6.0.0', '<')) { class_alias('Symfony\Bridge\PhpUnit\Legacy\TestRunner', 'Symfony\Bridge\PhpUnit\TextUI\TestRunner'); return; diff --git a/src/Symfony/Bridge/Twig/CHANGELOG.md b/src/Symfony/Bridge/Twig/CHANGELOG.md index 9c635c9508f29..b59d85ea0b4a4 100644 --- a/src/Symfony/Bridge/Twig/CHANGELOG.md +++ b/src/Symfony/Bridge/Twig/CHANGELOG.md @@ -34,7 +34,7 @@ CHANGELOG // ... $rendererEngine = new TwigRendererEngine(array('form_div_layout.html.twig'), $twig); // require Twig 1.30+ - $twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array( + $twig->addRuntimeLoader(new \Twig\RuntimeLoader\FactoryRuntimeLoader(array( TwigRenderer::class => function () use ($rendererEngine, $csrfTokenManager) { return new TwigRenderer($rendererEngine, $csrfTokenManager); }, diff --git a/src/Symfony/Bridge/Twig/Command/DebugCommand.php b/src/Symfony/Bridge/Twig/Command/DebugCommand.php index 4748444cd181f..e6357df51ea8e 100644 --- a/src/Symfony/Bridge/Twig/Command/DebugCommand.php +++ b/src/Symfony/Bridge/Twig/Command/DebugCommand.php @@ -17,6 +17,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; +use Twig\Environment; /** * Lists twig functions, filters, globals and tests present in the current project. @@ -35,18 +36,13 @@ public function __construct($name = 'debug:twig') parent::__construct($name); } - /** - * Sets the twig environment. - * - * @param \Twig_Environment $twig - */ - public function setTwigEnvironment(\Twig_Environment $twig) + public function setTwigEnvironment(Environment $twig) { $this->twig = $twig; } /** - * @return \Twig_Environment $twig + * @return Environment $twig */ protected function getTwigEnvironment() { @@ -156,14 +152,20 @@ private function getMetadata($type, $entity) throw new \UnexpectedValueException('Unsupported callback type'); } + $args = $refl->getParameters(); + // filter out context/environment args - $args = array_filter($refl->getParameters(), function ($param) use ($entity) { - if ($entity->needsContext() && $param->getName() === 'context') { - return false; - } + if ($entity->needsEnvironment()) { + array_shift($args); + } + if ($entity->needsContext()) { + array_shift($args); + } - return !$param->getClass() || $param->getClass()->getName() !== 'Twig_Environment'; - }); + if ($type === 'filters') { + // remove the value the filter is applied on + array_shift($args); + } // format args $args = array_map(function ($param) { @@ -174,11 +176,6 @@ private function getMetadata($type, $entity) return $param->getName(); }, $args); - if ($type === 'filters') { - // remove the value the filter is applied on - array_shift($args); - } - return $args; } } diff --git a/src/Symfony/Bridge/Twig/Command/LintCommand.php b/src/Symfony/Bridge/Twig/Command/LintCommand.php index b252ee274cd57..d20b9cf1934ca 100644 --- a/src/Symfony/Bridge/Twig/Command/LintCommand.php +++ b/src/Symfony/Bridge/Twig/Command/LintCommand.php @@ -18,6 +18,10 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Finder\Finder; +use Twig\Environment; +use Twig\Error\Error; +use Twig\Loader\ArrayLoader; +use Twig\Source; /** * Command that will validate your template syntax and output encountered errors. @@ -37,18 +41,13 @@ public function __construct($name = 'lint:twig') parent::__construct($name); } - /** - * Sets the twig environment. - * - * @param \Twig_Environment $twig - */ - public function setTwigEnvironment(\Twig_Environment $twig) + public function setTwigEnvironment(Environment $twig) { $this->twig = $twig; } /** - * @return \Twig_Environment $twig + * @return Environment $twig */ protected function getTwigEnvironment() { @@ -111,7 +110,7 @@ protected function execute(InputInterface $input, OutputInterface $output) return $this->display($input, $output, $io, $filesInfo); } - private function getFilesInfo(\Twig_Environment $twig, array $filenames) + private function getFilesInfo(Environment $twig, array $filenames) { $filesInfo = array(); foreach ($filenames as $filename) { @@ -134,16 +133,16 @@ protected function findFiles($filename) throw new \RuntimeException(sprintf('File or directory "%s" is not readable', $filename)); } - private function validate(\Twig_Environment $twig, $template, $file) + private function validate(Environment $twig, $template, $file) { $realLoader = $twig->getLoader(); try { - $temporaryLoader = new \Twig_Loader_Array(array((string) $file => $template)); + $temporaryLoader = new ArrayLoader(array((string) $file => $template)); $twig->setLoader($temporaryLoader); - $nodeTree = $twig->parse($twig->tokenize(new \Twig_Source($template, (string) $file))); + $nodeTree = $twig->parse($twig->tokenize(new Source($template, (string) $file))); $twig->compile($nodeTree); $twig->setLoader($realLoader); - } catch (\Twig_Error $e) { + } catch (Error $e) { $twig->setLoader($realLoader); return array('template' => $template, 'file' => $file, 'valid' => false, 'exception' => $e); @@ -205,7 +204,7 @@ private function displayJson(OutputInterface $output, $filesInfo) return min($errors, 1); } - private function renderException(OutputInterface $output, $template, \Twig_Error $exception, $file = null) + private function renderException(OutputInterface $output, $template, Error $exception, $file = null) { $line = $exception->getTemplateLine(); diff --git a/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php b/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php index f075709654c95..f28c92422ae48 100644 --- a/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php +++ b/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php @@ -15,6 +15,9 @@ use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Twig\Markup; +use Twig\Profiler\Dumper\HtmlDumper; +use Twig\Profiler\Profile; /** * TwigDataCollector. @@ -26,7 +29,7 @@ class TwigDataCollector extends DataCollector implements LateDataCollectorInterf private $profile; private $computed; - public function __construct(\Twig_Profiler_Profile $profile) + public function __construct(Profile $profile) { $this->profile = $profile; } @@ -73,7 +76,7 @@ public function getMacroCount() public function getHtmlCallGraph() { - $dumper = new \Twig_Profiler_Dumper_Html(); + $dumper = new HtmlDumper(); $dump = $dumper->dump($this->getProfile()); // needed to remove the hardcoded CSS styles @@ -87,14 +90,14 @@ public function getHtmlCallGraph() '', ), $dump); - return new \Twig_Markup($dump, 'UTF-8'); + return new Markup($dump, 'UTF-8'); } public function getProfile() { if (null === $this->profile) { - if (PHP_VERSION_ID >= 70000) { - $this->profile = unserialize($this->data['profile'], array('allowed_classes' => array('Twig_Profiler_Profile'))); + if (\PHP_VERSION_ID >= 70000) { + $this->profile = unserialize($this->data['profile'], array('allowed_classes' => array('Twig_Profiler_Profile', 'Twig\Profiler\Profile'))); } else { $this->profile = unserialize($this->data['profile']); } @@ -112,7 +115,7 @@ private function getComputedData($index) return $this->computed[$index]; } - private function computeData(\Twig_Profiler_Profile $profile) + private function computeData(Profile $profile) { $data = array( 'template_count' => 0, diff --git a/src/Symfony/Bridge/Twig/Extension/AssetExtension.php b/src/Symfony/Bridge/Twig/Extension/AssetExtension.php index f599a9eb5c9b6..d5d70fb397f69 100644 --- a/src/Symfony/Bridge/Twig/Extension/AssetExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/AssetExtension.php @@ -12,13 +12,15 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\Asset\Packages; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * Twig extension for the Symfony Asset component. * * @author Fabien Potencier */ -class AssetExtension extends \Twig_Extension +class AssetExtension extends AbstractExtension { private $packages; @@ -33,8 +35,8 @@ public function __construct(Packages $packages) public function getFunctions() { return array( - new \Twig_SimpleFunction('asset', array($this, 'getAssetUrl')), - new \Twig_SimpleFunction('asset_version', array($this, 'getAssetVersion')), + new TwigFunction('asset', array($this, 'getAssetUrl')), + new TwigFunction('asset_version', array($this, 'getAssetVersion')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php index 9861277db0f81..83a8f7eed44d1 100644 --- a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php @@ -12,13 +12,15 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Twig\Extension\AbstractExtension; +use Twig\TwigFilter; /** * Twig extension relate to PHP code and used by the profiler and the default exception templates. * * @author Fabien Potencier */ -class CodeExtension extends \Twig_Extension +class CodeExtension extends AbstractExtension { private $fileLinkFormat; private $rootDir; @@ -44,15 +46,15 @@ public function __construct($fileLinkFormat, $rootDir, $charset) public function getFilters() { return array( - new \Twig_SimpleFilter('abbr_class', array($this, 'abbrClass'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('abbr_method', array($this, 'abbrMethod'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('format_args', array($this, 'formatArgs'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('format_args_as_text', array($this, 'formatArgsAsText')), - new \Twig_SimpleFilter('file_excerpt', array($this, 'fileExcerpt'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('format_file', array($this, 'formatFile'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('format_file_from_text', array($this, 'formatFileFromText'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('format_log_message', array($this, 'formatLogMessage'), array('is_safe' => array('html'))), - new \Twig_SimpleFilter('file_link', array($this, 'getFileLink')), + new TwigFilter('abbr_class', array($this, 'abbrClass'), array('is_safe' => array('html'))), + new TwigFilter('abbr_method', array($this, 'abbrMethod'), array('is_safe' => array('html'))), + new TwigFilter('format_args', array($this, 'formatArgs'), array('is_safe' => array('html'))), + new TwigFilter('format_args_as_text', array($this, 'formatArgsAsText')), + new TwigFilter('file_excerpt', array($this, 'fileExcerpt'), array('is_safe' => array('html'))), + new TwigFilter('format_file', array($this, 'formatFile'), array('is_safe' => array('html'))), + new TwigFilter('format_file_from_text', array($this, 'formatFileFromText'), array('is_safe' => array('html'))), + new TwigFilter('format_log_message', array($this, 'formatLogMessage'), array('is_safe' => array('html'))), + new TwigFilter('file_link', array($this, 'getFileLink')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/DumpExtension.php b/src/Symfony/Bridge/Twig/Extension/DumpExtension.php index 2407f61013e86..767163f87da1c 100644 --- a/src/Symfony/Bridge/Twig/Extension/DumpExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/DumpExtension.php @@ -14,13 +14,17 @@ use Symfony\Bridge\Twig\TokenParser\DumpTokenParser; use Symfony\Component\VarDumper\Cloner\ClonerInterface; use Symfony\Component\VarDumper\Dumper\HtmlDumper; +use Twig\Environment; +use Twig\Extension\AbstractExtension; +use Twig\Template; +use Twig\TwigFunction; /** * Provides integration of the dump() function with Twig. * * @author Nicolas Grekas */ -class DumpExtension extends \Twig_Extension +class DumpExtension extends AbstractExtension { private $cloner; private $dumper; @@ -34,7 +38,7 @@ public function __construct(ClonerInterface $cloner, HtmlDumper $dumper = null) public function getFunctions() { return array( - new \Twig_SimpleFunction('dump', array($this, 'dump'), array('is_safe' => array('html'), 'needs_context' => true, 'needs_environment' => true)), + new TwigFunction('dump', array($this, 'dump'), array('is_safe' => array('html'), 'needs_context' => true, 'needs_environment' => true)), ); } @@ -48,7 +52,7 @@ public function getName() return 'dump'; } - public function dump(\Twig_Environment $env, $context) + public function dump(Environment $env, $context) { if (!$env->isDebug()) { return; @@ -57,7 +61,7 @@ public function dump(\Twig_Environment $env, $context) if (2 === func_num_args()) { $vars = array(); foreach ($context as $key => $value) { - if (!$value instanceof \Twig_Template) { + if (!$value instanceof Template) { $vars[$key] = $value; } } diff --git a/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php b/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php index 6b30a279419b7..fc64fa3e3775d 100644 --- a/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php @@ -12,13 +12,15 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\ExpressionLanguage\Expression; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * ExpressionExtension gives a way to create Expressions from a template. * * @author Fabien Potencier */ -class ExpressionExtension extends \Twig_Extension +class ExpressionExtension extends AbstractExtension { /** * {@inheritdoc} @@ -26,7 +28,7 @@ class ExpressionExtension extends \Twig_Extension public function getFunctions() { return array( - new \Twig_SimpleFunction('expression', array($this, 'createExpression')), + new TwigFunction('expression', array($this, 'createExpression')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/FormExtension.php b/src/Symfony/Bridge/Twig/Extension/FormExtension.php index 81a8683c35b97..362879e43a89e 100644 --- a/src/Symfony/Bridge/Twig/Extension/FormExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/FormExtension.php @@ -15,6 +15,12 @@ use Symfony\Bridge\Twig\Form\TwigRendererInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Twig\Environment; +use Twig\Extension\AbstractExtension; +use Twig\Extension\InitRuntimeInterface; +use Twig\TwigFilter; +use Twig\TwigFunction; +use Twig\TwigTest; /** * FormExtension extends Twig with form capabilities. @@ -22,7 +28,7 @@ * @author Fabien Potencier * @author Bernhard Schussek */ -class FormExtension extends \Twig_Extension implements \Twig_Extension_InitRuntimeInterface +class FormExtension extends AbstractExtension implements InitRuntimeInterface { /** * @deprecated since version 3.2, to be removed in 4.0 alongside with magic methods below @@ -32,7 +38,7 @@ class FormExtension extends \Twig_Extension implements \Twig_Extension_InitRunti public function __construct($renderer = null) { if ($renderer instanceof TwigRendererInterface) { - @trigger_error(sprintf('Passing a Twig Form Renderer to the "%s" constructor is deprecated since version 3.2 and won\'t be possible in 4.0. Pass the Twig_Environment to the TwigRendererEngine constructor instead.', static::class), E_USER_DEPRECATED); + @trigger_error(sprintf('Passing a Twig Form Renderer to the "%s" constructor is deprecated since version 3.2 and won\'t be possible in 4.0. Pass the Twig\Environment to the TwigRendererEngine constructor instead.', static::class), E_USER_DEPRECATED); } elseif (null !== $renderer && !(is_array($renderer) && isset($renderer[0], $renderer[1]) && $renderer[0] instanceof ContainerInterface)) { throw new \InvalidArgumentException(sprintf('Passing any arguments the constructor of %s is reserved for internal use.', __CLASS__)); } @@ -44,7 +50,7 @@ public function __construct($renderer = null) * * To be removed in 4.0 */ - public function initRuntime(\Twig_Environment $environment) + public function initRuntime(Environment $environment) { if ($this->renderer instanceof TwigRendererInterface) { $this->renderer->setEnvironment($environment); @@ -70,15 +76,15 @@ public function getTokenParsers() public function getFunctions() { return array( - new \Twig_SimpleFunction('form_widget', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form_errors', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form_label', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form_row', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form_rest', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form_start', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('form_end', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))), - new \Twig_SimpleFunction('csrf_token', array('Symfony\Bridge\Twig\Form\TwigRenderer', 'renderCsrfToken')), + new TwigFunction('form_widget', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form_errors', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form_label', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form_row', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form_rest', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form_start', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('form_end', null, array('node_class' => 'Symfony\Bridge\Twig\Node\RenderBlockNode', 'is_safe' => array('html'))), + new TwigFunction('csrf_token', array('Symfony\Bridge\Twig\Form\TwigRenderer', 'renderCsrfToken')), ); } @@ -88,7 +94,7 @@ public function getFunctions() public function getFilters() { return array( - new \Twig_SimpleFilter('humanize', array('Symfony\Bridge\Twig\Form\TwigRenderer', 'humanize')), + new TwigFilter('humanize', array('Symfony\Bridge\Twig\Form\TwigRenderer', 'humanize')), ); } @@ -98,7 +104,7 @@ public function getFilters() public function getTests() { return array( - new \Twig_SimpleTest('selectedchoice', 'Symfony\Bridge\Twig\Extension\twig_is_selected_choice'), + new TwigTest('selectedchoice', 'Symfony\Bridge\Twig\Extension\twig_is_selected_choice'), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php b/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php index 69d6d326f4d08..90b515ee320ba 100644 --- a/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php @@ -14,13 +14,15 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\RequestContext; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * Twig extension for the Symfony HttpFoundation component. * * @author Fabien Potencier */ -class HttpFoundationExtension extends \Twig_Extension +class HttpFoundationExtension extends AbstractExtension { private $requestStack; private $requestContext; @@ -37,8 +39,8 @@ public function __construct(RequestStack $requestStack, RequestContext $requestC public function getFunctions() { return array( - new \Twig_SimpleFunction('absolute_url', array($this, 'generateAbsoluteUrl')), - new \Twig_SimpleFunction('relative_path', array($this, 'generateRelativePath')), + new TwigFunction('absolute_url', array($this, 'generateAbsoluteUrl')), + new TwigFunction('relative_path', array($this, 'generateRelativePath')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php b/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php index 43b23bb9f6695..45142e7402a67 100644 --- a/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php @@ -12,20 +12,22 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\HttpKernel\Controller\ControllerReference; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * Provides integration with the HttpKernel component. * * @author Fabien Potencier */ -class HttpKernelExtension extends \Twig_Extension +class HttpKernelExtension extends AbstractExtension { public function getFunctions() { return array( - new \Twig_SimpleFunction('render', array(HttpKernelRuntime::class, 'renderFragment'), array('is_safe' => array('html'))), - new \Twig_SimpleFunction('render_*', array(HttpKernelRuntime::class, 'renderFragmentStrategy'), array('is_safe' => array('html'))), - new \Twig_SimpleFunction('controller', static::class.'::controller'), + new TwigFunction('render', array(HttpKernelRuntime::class, 'renderFragment'), array('is_safe' => array('html'))), + new TwigFunction('render_*', array(HttpKernelRuntime::class, 'renderFragmentStrategy'), array('is_safe' => array('html'))), + new TwigFunction('controller', static::class.'::controller'), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php b/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php index ea105e8d955e4..17abb779899ac 100644 --- a/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php @@ -12,13 +12,15 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * LogoutUrlHelper provides generator functions for the logout URL to Twig. * * @author Jeremy Mikola */ -class LogoutUrlExtension extends \Twig_Extension +class LogoutUrlExtension extends AbstractExtension { private $generator; @@ -33,8 +35,8 @@ public function __construct(LogoutUrlGenerator $generator) public function getFunctions() { return array( - new \Twig_SimpleFunction('logout_url', array($this, 'getLogoutUrl')), - new \Twig_SimpleFunction('logout_path', array($this, 'getLogoutPath')), + new TwigFunction('logout_url', array($this, 'getLogoutUrl')), + new TwigFunction('logout_path', array($this, 'getLogoutPath')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php b/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php index 648a6c8036d75..21214f81196ad 100644 --- a/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php @@ -12,16 +12,18 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\Stopwatch\Stopwatch; +use Twig\Extension\ProfilerExtension as BaseProfilerExtension; +use Twig\Profiler\Profile; /** * @author Fabien Potencier */ -class ProfilerExtension extends \Twig_Extension_Profiler +class ProfilerExtension extends BaseProfilerExtension { private $stopwatch; private $events; - public function __construct(\Twig_Profiler_Profile $profile, Stopwatch $stopwatch = null) + public function __construct(Profile $profile, Stopwatch $stopwatch = null) { parent::__construct($profile); @@ -29,7 +31,7 @@ public function __construct(\Twig_Profiler_Profile $profile, Stopwatch $stopwatc $this->events = new \SplObjectStorage(); } - public function enter(\Twig_Profiler_Profile $profile) + public function enter(Profile $profile) { if ($this->stopwatch && $profile->isTemplate()) { $this->events[$profile] = $this->stopwatch->start($profile->getName(), 'template'); @@ -38,7 +40,7 @@ public function enter(\Twig_Profiler_Profile $profile) parent::enter($profile); } - public function leave(\Twig_Profiler_Profile $profile) + public function leave(Profile $profile) { parent::leave($profile); diff --git a/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php b/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php index 81cef949c7408..97b1ea31360ce 100644 --- a/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php @@ -12,13 +12,18 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Twig\Extension\AbstractExtension; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Node; +use Twig\TwigFunction; /** * Provides integration of the Routing component with Twig. * * @author Fabien Potencier */ -class RoutingExtension extends \Twig_Extension +class RoutingExtension extends AbstractExtension { private $generator; @@ -35,8 +40,8 @@ public function __construct(UrlGeneratorInterface $generator) public function getFunctions() { return array( - new \Twig_SimpleFunction('url', array($this, 'getUrl'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))), - new \Twig_SimpleFunction('path', array($this, 'getPath'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))), + new TwigFunction('url', array($this, 'getUrl'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))), + new TwigFunction('path', array($this, 'getPath'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))), ); } @@ -82,9 +87,11 @@ public function getUrl($name, $parameters = array(), $schemeRelative = false) * - path('route', {'param1': 'value1', 'param2': 'value2'}) * If param1 and param2 reference placeholder in the route, it would still be safe. But we don't know. * - * @param \Twig_Node $argsNode The arguments of the path/url function + * @param Node $argsNode The arguments of the path/url function * * @return array An array with the contexts the URL is safe + * + * To be made @final in 3.4, and the type-hint be changed to "\Twig\Node\Node" in 4.0. */ public function isUrlGenerationSafe(\Twig_Node $argsNode) { @@ -93,8 +100,8 @@ public function isUrlGenerationSafe(\Twig_Node $argsNode) $argsNode->hasNode(1) ? $argsNode->getNode(1) : null ); - if (null === $paramsNode || $paramsNode instanceof \Twig_Node_Expression_Array && count($paramsNode) <= 2 && - (!$paramsNode->hasNode(1) || $paramsNode->getNode(1) instanceof \Twig_Node_Expression_Constant) + if (null === $paramsNode || $paramsNode instanceof ArrayExpression && count($paramsNode) <= 2 && + (!$paramsNode->hasNode(1) || $paramsNode->getNode(1) instanceof ConstantExpression) ) { return array('html'); } diff --git a/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php b/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php index fa5fae2e77a01..193726a684371 100644 --- a/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php @@ -14,13 +14,15 @@ use Symfony\Component\Security\Acl\Voter\FieldVote; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * SecurityExtension exposes security context features. * * @author Fabien Potencier */ -class SecurityExtension extends \Twig_Extension +class SecurityExtension extends AbstractExtension { private $securityChecker; @@ -52,7 +54,7 @@ public function isGranted($role, $object = null, $field = null) public function getFunctions() { return array( - new \Twig_SimpleFunction('is_granted', array($this, 'isGranted')), + new TwigFunction('is_granted', array($this, 'isGranted')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php b/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php index 52af92324c228..635188b7389e4 100644 --- a/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php @@ -13,13 +13,14 @@ use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Bridge\Twig\TokenParser\StopwatchTokenParser; +use Twig\Extension\AbstractExtension; /** * Twig extension for the stopwatch helper. * * @author Wouter J */ -class StopwatchExtension extends \Twig_Extension +class StopwatchExtension extends AbstractExtension { private $stopwatch; diff --git a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php index f1f2fbd20b82e..5155169a8173d 100644 --- a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php @@ -17,18 +17,22 @@ use Symfony\Component\Translation\TranslatorInterface; use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor; use Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor; +use Twig\Extension\AbstractExtension; +use Twig\NodeVisitor\NodeVisitorInterface; +use Twig\TokenParser\AbstractTokenParser; +use Twig\TwigFilter; /** * Provides integration of the Translation component with Twig. * * @author Fabien Potencier */ -class TranslationExtension extends \Twig_Extension +class TranslationExtension extends AbstractExtension { private $translator; private $translationNodeVisitor; - public function __construct(TranslatorInterface $translator, \Twig_NodeVisitorInterface $translationNodeVisitor = null) + public function __construct(TranslatorInterface $translator, NodeVisitorInterface $translationNodeVisitor = null) { if (!$translationNodeVisitor) { $translationNodeVisitor = new TranslationNodeVisitor(); @@ -49,15 +53,15 @@ public function getTranslator() public function getFilters() { return array( - new \Twig_SimpleFilter('trans', array($this, 'trans')), - new \Twig_SimpleFilter('transchoice', array($this, 'transchoice')), + new TwigFilter('trans', array($this, 'trans')), + new TwigFilter('transchoice', array($this, 'transchoice')), ); } /** * Returns the token parser instance to add to the existing list. * - * @return array An array of Twig_TokenParser instances + * @return AbstractTokenParser[] */ public function getTokenParsers() { diff --git a/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php b/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php index 14e1fc2736bae..3d90c3bf21c74 100644 --- a/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php @@ -14,13 +14,15 @@ use Fig\Link\GenericLinkProvider; use Fig\Link\Link; use Symfony\Component\HttpFoundation\RequestStack; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * Twig extension for the Symfony WebLink component. * * @author Kévin Dunglas */ -class WebLinkExtension extends \Twig_Extension +class WebLinkExtension extends AbstractExtension { private $requestStack; @@ -35,12 +37,12 @@ public function __construct(RequestStack $requestStack) public function getFunctions() { return array( - new \Twig_SimpleFunction('link', array($this, 'link')), - new \Twig_SimpleFunction('preload', array($this, 'preload')), - new \Twig_SimpleFunction('dns_prefetch', array($this, 'dnsPrefetch')), - new \Twig_SimpleFunction('preconnect', array($this, 'preconnect')), - new \Twig_SimpleFunction('prefetch', array($this, 'prefetch')), - new \Twig_SimpleFunction('prerender', array($this, 'prerender')), + new TwigFunction('link', array($this, 'link')), + new TwigFunction('preload', array($this, 'preload')), + new TwigFunction('dns_prefetch', array($this, 'dnsPrefetch')), + new TwigFunction('preconnect', array($this, 'preconnect')), + new TwigFunction('prefetch', array($this, 'prefetch')), + new TwigFunction('prerender', array($this, 'prerender')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php b/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php index 86fc9726dbaff..2d19857c96a00 100644 --- a/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php @@ -13,13 +13,15 @@ use Symfony\Component\Workflow\Registry; use Symfony\Component\Workflow\Transition; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; /** * WorkflowExtension. * * @author Grégoire Pineau */ -class WorkflowExtension extends \Twig_Extension +class WorkflowExtension extends AbstractExtension { private $workflowRegistry; @@ -31,10 +33,10 @@ public function __construct(Registry $workflowRegistry) public function getFunctions() { return array( - new \Twig_SimpleFunction('workflow_can', array($this, 'canTransition')), - new \Twig_SimpleFunction('workflow_transitions', array($this, 'getEnabledTransitions')), - new \Twig_SimpleFunction('workflow_has_marked_place', array($this, 'hasMarkedPlace')), - new \Twig_SimpleFunction('workflow_marked_places', array($this, 'getMarkedPlaces')), + new TwigFunction('workflow_can', array($this, 'canTransition')), + new TwigFunction('workflow_transitions', array($this, 'getEnabledTransitions')), + new TwigFunction('workflow_has_marked_place', array($this, 'hasMarkedPlace')), + new TwigFunction('workflow_marked_places', array($this, 'getMarkedPlaces')), ); } diff --git a/src/Symfony/Bridge/Twig/Extension/YamlExtension.php b/src/Symfony/Bridge/Twig/Extension/YamlExtension.php index df33135db97f9..79418fb8ff9f1 100644 --- a/src/Symfony/Bridge/Twig/Extension/YamlExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/YamlExtension.php @@ -13,13 +13,15 @@ use Symfony\Component\Yaml\Dumper as YamlDumper; use Symfony\Component\Yaml\Yaml; +use Twig\Extension\AbstractExtension; +use Twig\TwigFilter; /** * Provides integration of the Yaml component with Twig. * * @author Fabien Potencier */ -class YamlExtension extends \Twig_Extension +class YamlExtension extends AbstractExtension { /** * {@inheritdoc} @@ -27,8 +29,8 @@ class YamlExtension extends \Twig_Extension public function getFilters() { return array( - new \Twig_SimpleFilter('yaml_encode', array($this, 'encode')), - new \Twig_SimpleFilter('yaml_dump', array($this, 'dump')), + new TwigFilter('yaml_encode', array($this, 'encode')), + new TwigFilter('yaml_dump', array($this, 'dump')), ); } diff --git a/src/Symfony/Bridge/Twig/Form/TwigRenderer.php b/src/Symfony/Bridge/Twig/Form/TwigRenderer.php index 2f526100f58c3..9718c29cdb689 100644 --- a/src/Symfony/Bridge/Twig/Form/TwigRenderer.php +++ b/src/Symfony/Bridge/Twig/Form/TwigRenderer.php @@ -13,6 +13,7 @@ use Symfony\Component\Form\FormRenderer; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; +use Twig\Environment; /** * @author Bernhard Schussek @@ -34,7 +35,7 @@ public function __construct(TwigRendererEngineInterface $engine, CsrfTokenManage /** * {@inheritdoc} */ - public function setEnvironment(\Twig_Environment $environment) + public function setEnvironment(Environment $environment) { $this->engine->setEnvironment($environment); } diff --git a/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php b/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php index 406726ccdcba0..7e375f45e2996 100644 --- a/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php +++ b/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php @@ -13,6 +13,8 @@ use Symfony\Component\Form\AbstractRendererEngine; use Symfony\Component\Form\FormView; +use Twig\Environment; +use Twig\Template; /** * @author Bernhard Schussek @@ -20,16 +22,16 @@ class TwigRendererEngine extends AbstractRendererEngine implements TwigRendererEngineInterface { /** - * @var \Twig_Environment + * @var Environment */ private $environment; /** - * @var \Twig_Template + * @var Template */ private $template; - public function __construct(array $defaultThemes = array(), \Twig_Environment $environment = null) + public function __construct(array $defaultThemes = array(), Environment $environment = null) { if (null === $environment) { @trigger_error(sprintf('Not passing a Twig Environment as the second argument for "%s" constructor is deprecated since version 3.2 and won\'t be possible in 4.0.', static::class), E_USER_DEPRECATED); @@ -44,7 +46,7 @@ public function __construct(array $defaultThemes = array(), \Twig_Environment $e * * @deprecated since version 3.3, to be removed in 4.0 */ - public function setEnvironment(\Twig_Environment $environment) + public function setEnvironment(Environment $environment) { if ($this->environment) { @trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Pass the Twig Environment as second argument of the constructor instead.', __METHOD__), E_USER_DEPRECATED); @@ -166,13 +168,13 @@ protected function loadResourceForBlockName($cacheKey, FormView $view, $blockNam */ protected function loadResourcesFromTheme($cacheKey, &$theme) { - if (!$theme instanceof \Twig_Template) { - /* @var \Twig_Template $theme */ + if (!$theme instanceof Template) { + /* @var Template $theme */ $theme = $this->environment->loadTemplate($theme); } if (null === $this->template) { - // Store the first \Twig_Template instance that we find so that + // Store the first Template instance that we find so that // we can call displayBlock() later on. It doesn't matter *which* // template we use for that, since we pass the used blocks manually // anyway. diff --git a/src/Symfony/Bridge/Twig/Form/TwigRendererEngineInterface.php b/src/Symfony/Bridge/Twig/Form/TwigRendererEngineInterface.php index 2fd0cbda79a99..a58f491f1c8a0 100644 --- a/src/Symfony/Bridge/Twig/Form/TwigRendererEngineInterface.php +++ b/src/Symfony/Bridge/Twig/Form/TwigRendererEngineInterface.php @@ -12,6 +12,10 @@ namespace Symfony\Bridge\Twig\Form; use Symfony\Component\Form\FormRendererEngineInterface; +use Twig\Environment; + +// BC/FC with namespaced Twig +class_exists('Twig\Environment'); /** * @author Bernhard Schussek @@ -20,10 +24,5 @@ */ interface TwigRendererEngineInterface extends FormRendererEngineInterface { - /** - * Sets Twig's environment. - * - * @param \Twig_Environment $environment - */ - public function setEnvironment(\Twig_Environment $environment); + public function setEnvironment(Environment $environment); } diff --git a/src/Symfony/Bridge/Twig/Form/TwigRendererInterface.php b/src/Symfony/Bridge/Twig/Form/TwigRendererInterface.php index 85133248f3850..3bcbf5992d76f 100644 --- a/src/Symfony/Bridge/Twig/Form/TwigRendererInterface.php +++ b/src/Symfony/Bridge/Twig/Form/TwigRendererInterface.php @@ -12,6 +12,10 @@ namespace Symfony\Bridge\Twig\Form; use Symfony\Component\Form\FormRendererInterface; +use Twig\Environment; + +// BC/FC with namespaced Twig +class_exists('Twig\Environment'); /** * @author Bernhard Schussek @@ -20,10 +24,5 @@ */ interface TwigRendererInterface extends FormRendererInterface { - /** - * Sets Twig's environment. - * - * @param \Twig_Environment $environment - */ - public function setEnvironment(\Twig_Environment $environment); + public function setEnvironment(Environment $environment); } diff --git a/src/Symfony/Bridge/Twig/Node/DumpNode.php b/src/Symfony/Bridge/Twig/Node/DumpNode.php index a66781e36550a..d820d75cc7db9 100644 --- a/src/Symfony/Bridge/Twig/Node/DumpNode.php +++ b/src/Symfony/Bridge/Twig/Node/DumpNode.php @@ -11,14 +11,17 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Node; + /** * @author Julien Galenski */ -class DumpNode extends \Twig_Node +class DumpNode extends Node { private $varPrefix; - public function __construct($varPrefix, \Twig_Node $values = null, $lineno, $tag = null) + public function __construct($varPrefix, Node $values = null, $lineno, $tag = null) { $nodes = array(); if (null !== $values) { @@ -32,7 +35,7 @@ public function __construct($varPrefix, \Twig_Node $values = null, $lineno, $tag /** * {@inheritdoc} */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler ->write("if (\$this->env->isDebug()) {\n") @@ -44,7 +47,7 @@ public function compile(\Twig_Compiler $compiler) ->write(sprintf('$%svars = array();'."\n", $this->varPrefix)) ->write(sprintf('foreach ($context as $%1$skey => $%1$sval) {'."\n", $this->varPrefix)) ->indent() - ->write(sprintf('if (!$%sval instanceof \Twig_Template) {'."\n", $this->varPrefix)) + ->write(sprintf('if (!$%sval instanceof \Twig\Template) {'."\n", $this->varPrefix)) ->indent() ->write(sprintf('$%1$svars[$%1$skey] = $%1$sval;'."\n", $this->varPrefix)) ->outdent() diff --git a/src/Symfony/Bridge/Twig/Node/FormThemeNode.php b/src/Symfony/Bridge/Twig/Node/FormThemeNode.php index a1330413e7225..06d2400c4eb8f 100644 --- a/src/Symfony/Bridge/Twig/Node/FormThemeNode.php +++ b/src/Symfony/Bridge/Twig/Node/FormThemeNode.php @@ -11,22 +11,20 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Node; + /** * @author Fabien Potencier */ -class FormThemeNode extends \Twig_Node +class FormThemeNode extends Node { - public function __construct(\Twig_Node $form, \Twig_Node $resources, $lineno, $tag = null) + public function __construct(Node $form, Node $resources, $lineno, $tag = null) { parent::__construct(array('form' => $form, 'resources' => $resources), array(), $lineno, $tag); } - /** - * Compiles the node to PHP. - * - * @param \Twig_Compiler $compiler A Twig_Compiler instance - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) diff --git a/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php b/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php index 6c046c380192e..0698fd9001628 100644 --- a/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php +++ b/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php @@ -11,6 +11,9 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Expression\FunctionExpression; + /** * Compiles a call to {@link \Symfony\Component\Form\FormRendererInterface::renderBlock()}. * @@ -19,9 +22,9 @@ * * @author Bernhard Schussek */ -class RenderBlockNode extends \Twig_Node_Expression_Function +class RenderBlockNode extends FunctionExpression { - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); $arguments = iterator_to_array($this->getNode('arguments')); diff --git a/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php b/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php index 47457e2dc53ae..dcdba5c4db4bf 100644 --- a/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php +++ b/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php @@ -11,12 +11,17 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\FunctionExpression; + /** * @author Bernhard Schussek */ -class SearchAndRenderBlockNode extends \Twig_Node_Expression_Function +class SearchAndRenderBlockNode extends FunctionExpression { - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); $compiler->raw('$this->env->getRuntime(\'Symfony\Bridge\Twig\Form\TwigRenderer\')->searchAndRenderBlock('); @@ -39,7 +44,7 @@ public function compile(\Twig_Compiler $compiler) $variables = isset($arguments[2]) ? $arguments[2] : null; $lineno = $label->getTemplateLine(); - if ($label instanceof \Twig_Node_Expression_Constant) { + if ($label instanceof ConstantExpression) { // If the label argument is given as a constant, we can either // strip it away if it is empty, or integrate it into the array // of variables at compile time. @@ -48,8 +53,8 @@ public function compile(\Twig_Compiler $compiler) // Only insert the label into the array if it is not empty if (!twig_test_empty($label->getAttribute('value'))) { $originalVariables = $variables; - $variables = new \Twig_Node_Expression_Array(array(), $lineno); - $labelKey = new \Twig_Node_Expression_Constant('label', $lineno); + $variables = new ArrayExpression(array(), $lineno); + $labelKey = new ConstantExpression('label', $lineno); if (null !== $originalVariables) { foreach ($originalVariables->getKeyValuePairs() as $pair) { diff --git a/src/Symfony/Bridge/Twig/Node/StopwatchNode.php b/src/Symfony/Bridge/Twig/Node/StopwatchNode.php index 95d755a78cdb0..fac770c2499ba 100644 --- a/src/Symfony/Bridge/Twig/Node/StopwatchNode.php +++ b/src/Symfony/Bridge/Twig/Node/StopwatchNode.php @@ -11,19 +11,23 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Expression\AssignNameExpression; +use Twig\Node\Node; + /** * Represents a stopwatch node. * * @author Wouter J */ -class StopwatchNode extends \Twig_Node +class StopwatchNode extends Node { - public function __construct(\Twig_Node $name, \Twig_Node $body, \Twig_Node_Expression_AssignName $var, $lineno = 0, $tag = null) + public function __construct(Node $name, Node $body, AssignNameExpression $var, $lineno = 0, $tag = null) { parent::__construct(array('body' => $body, 'name' => $name, 'var' => $var), array(), $lineno, $tag); } - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) diff --git a/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php b/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php index adee71ffc5dc4..c9c82b33e541c 100644 --- a/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php +++ b/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php @@ -11,22 +11,21 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Expression\AbstractExpression; +use Twig\Node\Node; + /** * @author Fabien Potencier */ -class TransDefaultDomainNode extends \Twig_Node +class TransDefaultDomainNode extends Node { - public function __construct(\Twig_Node_Expression $expr, $lineno = 0, $tag = null) + public function __construct(AbstractExpression $expr, $lineno = 0, $tag = null) { parent::__construct(array('expr' => $expr), array(), $lineno, $tag); } - /** - * Compiles the node to PHP. - * - * @param \Twig_Compiler $compiler A Twig_Compiler instance - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { // noop as this node is just a marker for TranslationDefaultDomainNodeVisitor } diff --git a/src/Symfony/Bridge/Twig/Node/TransNode.php b/src/Symfony/Bridge/Twig/Node/TransNode.php index 7b2f9c090405f..020810f7b7c55 100644 --- a/src/Symfony/Bridge/Twig/Node/TransNode.php +++ b/src/Symfony/Bridge/Twig/Node/TransNode.php @@ -11,12 +11,23 @@ namespace Symfony\Bridge\Twig\Node; +use Twig\Compiler; +use Twig\Node\Expression\AbstractExpression; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Node\Node; +use Twig\Node\TextNode; + +// BC/FC with namespaced Twig +class_exists('Twig\Node\Expression\ArrayExpression'); + /** * @author Fabien Potencier */ -class TransNode extends \Twig_Node +class TransNode extends Node { - public function __construct(\Twig_Node $body, \Twig_Node $domain = null, \Twig_Node_Expression $count = null, \Twig_Node_Expression $vars = null, \Twig_Node_Expression $locale = null, $lineno = 0, $tag = null) + public function __construct(Node $body, Node $domain = null, AbstractExpression $count = null, AbstractExpression $vars = null, AbstractExpression $locale = null, $lineno = 0, $tag = null) { $nodes = array('body' => $body); if (null !== $domain) { @@ -35,17 +46,12 @@ public function __construct(\Twig_Node $body, \Twig_Node $domain = null, \Twig_N parent::__construct($nodes, array(), $lineno, $tag); } - /** - * Compiles the node to PHP. - * - * @param \Twig_Compiler $compiler A Twig_Compiler instance - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); - $defaults = new \Twig_Node_Expression_Array(array(), -1); - if ($this->hasNode('vars') && ($vars = $this->getNode('vars')) instanceof \Twig_Node_Expression_Array) { + $defaults = new ArrayExpression(array(), -1); + if ($this->hasNode('vars') && ($vars = $this->getNode('vars')) instanceof ArrayExpression) { $defaults = $this->getNode('vars'); $vars = null; } @@ -96,11 +102,11 @@ public function compile(\Twig_Compiler $compiler) $compiler->raw(");\n"); } - protected function compileString(\Twig_Node $body, \Twig_Node_Expression_Array $vars, $ignoreStrictCheck = false) + protected function compileString(Node $body, ArrayExpression $vars, $ignoreStrictCheck = false) { - if ($body instanceof \Twig_Node_Expression_Constant) { + if ($body instanceof ConstantExpression) { $msg = $body->getAttribute('value'); - } elseif ($body instanceof \Twig_Node_Text) { + } elseif ($body instanceof TextNode) { $msg = $body->getAttribute('data'); } else { return array($body, $vars); @@ -109,18 +115,18 @@ protected function compileString(\Twig_Node $body, \Twig_Node_Expression_Array $ preg_match_all('/(?getTemplateLine()); + $key = new ConstantExpression('%'.$var.'%', $body->getTemplateLine()); if (!$vars->hasElement($key)) { if ('count' === $var && $this->hasNode('count')) { $vars->addElement($this->getNode('count'), $key); } else { - $varExpr = new \Twig_Node_Expression_Name($var, $body->getTemplateLine()); + $varExpr = new NameExpression($var, $body->getTemplateLine()); $varExpr->setAttribute('ignore_strict_check', $ignoreStrictCheck); $vars->addElement($varExpr, $key); } } } - return array(new \Twig_Node_Expression_Constant(str_replace('%%', '%', trim($msg)), $body->getTemplateLine()), $vars); + return array(new ConstantExpression(str_replace('%%', '%', trim($msg)), $body->getTemplateLine()), $vars); } } diff --git a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php index e64d6eae2347d..c69ca843e83ea 100644 --- a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php +++ b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php @@ -13,13 +13,22 @@ use Symfony\Bridge\Twig\Node\TransNode; use Symfony\Bridge\Twig\Node\TransDefaultDomainNode; +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\AssignNameExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\FilterExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Node\ModuleNode; +use Twig\Node\Node; +use Twig\NodeVisitor\AbstractNodeVisitor; /** * TranslationDefaultDomainNodeVisitor. * * @author Fabien Potencier */ -class TranslationDefaultDomainNodeVisitor extends \Twig_BaseNodeVisitor +class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor { /** * @var Scope @@ -37,23 +46,23 @@ public function __construct() /** * {@inheritdoc} */ - protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) + protected function doEnterNode(Node $node, Environment $env) { - if ($node instanceof \Twig_Node_Block || $node instanceof \Twig_Node_Module) { + if ($node instanceof Node_Block || $node instanceof ModuleNode) { $this->scope = $this->scope->enter(); } if ($node instanceof TransDefaultDomainNode) { - if ($node->getNode('expr') instanceof \Twig_Node_Expression_Constant) { + if ($node->getNode('expr') instanceof ConstantExpression) { $this->scope->set('domain', $node->getNode('expr')); return $node; } else { $var = $this->getVarName(); - $name = new \Twig_Node_Expression_AssignName($var, $node->getTemplateLine()); - $this->scope->set('domain', new \Twig_Node_Expression_Name($var, $node->getTemplateLine())); + $name = new AssignNameExpression($var, $node->getTemplateLine()); + $this->scope->set('domain', new NameExpression($var, $node->getTemplateLine())); - return new \Twig_Node_Set(false, new \Twig_Node(array($name)), new \Twig_Node(array($node->getNode('expr'))), $node->getTemplateLine()); + return new Node_Set(false, new Node(array($name)), new Node(array($node->getNode('expr'))), $node->getTemplateLine()); } } @@ -61,7 +70,7 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) return $node; } - if ($node instanceof \Twig_Node_Expression_Filter && in_array($node->getNode('filter')->getAttribute('value'), array('trans', 'transchoice'))) { + if ($node instanceof FilterExpression && in_array($node->getNode('filter')->getAttribute('value'), array('trans', 'transchoice'))) { $arguments = $node->getNode('arguments'); $ind = 'trans' === $node->getNode('filter')->getAttribute('value') ? 1 : 2; if ($this->isNamedArguments($arguments)) { @@ -71,7 +80,7 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) } else { if (!$arguments->hasNode($ind)) { if (!$arguments->hasNode($ind - 1)) { - $arguments->setNode($ind - 1, new \Twig_Node_Expression_Array(array(), $node->getTemplateLine())); + $arguments->setNode($ind - 1, new ArrayExpression(array(), $node->getTemplateLine())); } $arguments->setNode($ind, $this->scope->get('domain')); @@ -89,13 +98,13 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) /** * {@inheritdoc} */ - protected function doLeaveNode(\Twig_Node $node, \Twig_Environment $env) + protected function doLeaveNode(Node $node, Environment $env) { if ($node instanceof TransDefaultDomainNode) { return false; } - if ($node instanceof \Twig_Node_Block || $node instanceof \Twig_Node_Module) { + if ($node instanceof Node_Block || $node instanceof ModuleNode) { $this->scope = $this->scope->leave(); } diff --git a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php index 6e3880d09ed98..01f230b9efdff 100644 --- a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php +++ b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php @@ -12,13 +12,18 @@ namespace Symfony\Bridge\Twig\NodeVisitor; use Symfony\Bridge\Twig\Node\TransNode; +use Twig\Environment; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\FilterExpression; +use Twig\Node\Node; +use Twig\NodeVisitor\AbstractNodeVisitor; /** * TranslationNodeVisitor extracts translation messages. * * @author Fabien Potencier */ -class TranslationNodeVisitor extends \Twig_BaseNodeVisitor +class TranslationNodeVisitor extends AbstractNodeVisitor { const UNDEFINED_DOMAIN = '_undefined'; @@ -45,16 +50,16 @@ public function getMessages() /** * {@inheritdoc} */ - protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) + protected function doEnterNode(Node $node, Environment $env) { if (!$this->enabled) { return $node; } if ( - $node instanceof \Twig_Node_Expression_Filter && + $node instanceof FilterExpression && 'trans' === $node->getNode('filter')->getAttribute('value') && - $node->getNode('node') instanceof \Twig_Node_Expression_Constant + $node->getNode('node') instanceof ConstantExpression ) { // extract constant nodes with a trans filter $this->messages[] = array( @@ -62,9 +67,9 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) $this->getReadDomainFromArguments($node->getNode('arguments'), 1), ); } elseif ( - $node instanceof \Twig_Node_Expression_Filter && + $node instanceof FilterExpression && 'transchoice' === $node->getNode('filter')->getAttribute('value') && - $node->getNode('node') instanceof \Twig_Node_Expression_Constant + $node->getNode('node') instanceof ConstantExpression ) { // extract constant nodes with a trans filter $this->messages[] = array( @@ -85,7 +90,7 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) /** * {@inheritdoc} */ - protected function doLeaveNode(\Twig_Node $node, \Twig_Environment $env) + protected function doLeaveNode(Node $node, Environment $env) { return $node; } @@ -99,12 +104,12 @@ public function getPriority() } /** - * @param \Twig_Node $arguments - * @param int $index + * @param Node $arguments + * @param int $index * * @return string|null */ - private function getReadDomainFromArguments(\Twig_Node $arguments, $index) + private function getReadDomainFromArguments(Node $arguments, $index) { if ($arguments->hasNode('domain')) { $argument = $arguments->getNode('domain'); @@ -118,13 +123,13 @@ private function getReadDomainFromArguments(\Twig_Node $arguments, $index) } /** - * @param \Twig_Node $node + * @param Node $node * * @return string|null */ - private function getReadDomainFromNode(\Twig_Node $node) + private function getReadDomainFromNode(Node $node) { - if ($node instanceof \Twig_Node_Expression_Constant) { + if ($node instanceof ConstantExpression) { return $node->getAttribute('value'); } diff --git a/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php index 1b63cdd1b8daf..ef7698c39c83e 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php @@ -16,6 +16,8 @@ use Symfony\Component\Console\Application; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; +use Twig\Loader\FilesystemLoader; +use Twig\Environment; class LintCommandTest extends TestCase { @@ -71,7 +73,7 @@ public function testLintFileCompileTimeException() */ private function createCommandTester() { - $twig = new \Twig_Environment(new \Twig_Loader_Filesystem()); + $twig = new Environment(new FilesystemLoader()); $command = new LintCommand(); $command->setTwigEnvironment($twig); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php index df95e4b450b45..ce80418c83ba7 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php @@ -16,6 +16,8 @@ use Symfony\Component\VarDumper\Dumper\HtmlDumper; use Symfony\Component\VarDumper\VarDumper; use Symfony\Component\VarDumper\Cloner\VarCloner; +use Twig\Environment; +use Twig\Loader\ArrayLoader; class DumpExtensionTest extends TestCase { @@ -25,7 +27,7 @@ class DumpExtensionTest extends TestCase public function testDumpTag($template, $debug, $expectedOutput, $expectedDumped) { $extension = new DumpExtension(new VarCloner()); - $twig = new \Twig_Environment(new \Twig_Loader_Array(array('template' => $template)), array( + $twig = new Environment(new ArrayLoader(array('template' => $template)), array( 'debug' => $debug, 'cache' => false, 'optimizations' => 0, @@ -65,7 +67,7 @@ public function getDumpTags() public function testDump($context, $args, $expectedOutput, $debug = true) { $extension = new DumpExtension(new VarCloner()); - $twig = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array( + $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array( 'debug' => $debug, 'cache' => false, 'optimizations' => 0, @@ -121,7 +123,7 @@ public function testCustomDumper() '' ); $extension = new DumpExtension(new VarCloner(), $dumper); - $twig = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array( + $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array( 'debug' => true, 'cache' => false, 'optimizations' => 0, diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.php index d689bad20b118..b2ee22c6a969b 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.php @@ -13,13 +13,15 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\ExpressionExtension; +use Twig\Environment; +use Twig\Loader\ArrayLoader; class ExpressionExtensionTest extends TestCase { public function testExpressionCreation() { $template = "{{ expression('1 == 1') }}"; - $twig = new \Twig_Environment(new \Twig_Loader_Array(array('template' => $template)), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); + $twig = new Environment(new ArrayLoader(array('template' => $template)), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); $twig->addExtension(new ExpressionExtension()); $output = $twig->render('template'); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php b/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php index 1c8e5dcd490f7..4cbc55b46a66c 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php @@ -11,7 +11,9 @@ namespace Symfony\Bridge\Twig\Tests\Extension\Fixtures; -class StubFilesystemLoader extends \Twig_Loader_Filesystem +use Twig\Loader\FilesystemLoader; + +class StubFilesystemLoader extends FilesystemLoader { protected function findTemplate($name, $throw = true) { diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php index 614b59f5823ec..f82a5d2e33ea4 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php @@ -19,6 +19,7 @@ use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractBootstrap3HorizontalLayoutTest; +use Twig\Environment; class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3HorizontalLayoutTest { @@ -39,7 +40,7 @@ protected function setUp() __DIR__.'/Fixtures/templates/form', )); - $environment = new \Twig_Environment($loader, array('strict_variables' => true)); + $environment = new Environment($loader, array('strict_variables' => true)); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addExtension(new FormExtension()); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php index aceda8153d434..93f08ed252bbe 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php @@ -19,6 +19,7 @@ use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractBootstrap3LayoutTest; +use Twig\Environment; class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest { @@ -35,7 +36,7 @@ protected function setUp() __DIR__.'/Fixtures/templates/form', )); - $environment = new \Twig_Environment($loader, array('strict_variables' => true)); + $environment = new Environment($loader, array('strict_variables' => true)); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addExtension(new FormExtension()); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php index 99672997441be..5367650e9dcc6 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php @@ -20,6 +20,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractDivLayoutTest; +use Twig\Environment; class FormExtensionDivLayoutTest extends AbstractDivLayoutTest { @@ -36,7 +37,7 @@ protected function setUp() __DIR__.'/Fixtures/templates/form', )); - $environment = new \Twig_Environment($loader, array('strict_variables' => true)); + $environment = new Environment($loader, array('strict_variables' => true)); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addGlobal('global', ''); // the value can be any template that exists diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php index 8d4396a54c4dd..5868e42ca5395 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php @@ -19,6 +19,7 @@ use Symfony\Component\Form\Tests\AbstractTableLayoutTest; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; +use Twig\Environment; class FormExtensionTableLayoutTest extends AbstractTableLayoutTest { @@ -35,7 +36,7 @@ protected function setUp() __DIR__.'/Fixtures/templates/form', )); - $environment = new \Twig_Environment($loader, array('strict_variables' => true)); + $environment = new Environment($loader, array('strict_variables' => true)); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addGlobal('global', ''); $environment->addExtension(new FormExtension()); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php index 8909b3e4e43b4..9f19847eb8824 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.php @@ -17,11 +17,13 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Fragment\FragmentHandler; +use Twig\Environment; +use Twig\Loader\ArrayLoader; class HttpKernelExtensionTest extends TestCase { /** - * @expectedException \Twig_Error_Runtime + * @expectedException \Twig\Error\RuntimeError */ public function testFragmentWithError() { @@ -75,11 +77,11 @@ protected function getFragmentHandler($return) protected function renderTemplate(FragmentHandler $renderer, $template = '{{ render("foo") }}') { - $loader = new \Twig_Loader_Array(array('index' => $template)); - $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false)); + $loader = new ArrayLoader(array('index' => $template)); + $twig = new Environment($loader, array('debug' => true, 'cache' => false)); $twig->addExtension(new HttpKernelExtension()); - $loader = $this->getMockBuilder('Twig_RuntimeLoaderInterface')->getMock(); + $loader = $this->getMockBuilder('Twig\RuntimeLoader\RuntimeLoaderInterface')->getMock(); $loader->expects($this->any())->method('load')->will($this->returnValueMap(array( array('Symfony\Bridge\Twig\Extension\HttpKernelRuntime', new HttpKernelRuntime($renderer)), ))); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php index 5fa4e9cd36b1c..fdff039851228 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.php @@ -13,6 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\RoutingExtension; +use Twig\Environment; +use Twig\Node\Expression\FilterExpression; +use Twig\Source; class RoutingExtensionTest extends TestCase { @@ -21,12 +24,12 @@ class RoutingExtensionTest extends TestCase */ public function testEscaping($template, $mustBeEscaped) { - $twig = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); + $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); $twig->addExtension(new RoutingExtension($this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock())); - $nodes = $twig->parse($twig->tokenize(new \Twig_Source($template, ''))); + $nodes = $twig->parse($twig->tokenize(new Source($template, ''))); - $this->assertSame($mustBeEscaped, $nodes->getNode('body')->getNode(0)->getNode('expr') instanceof \Twig_Node_Expression_Filter); + $this->assertSame($mustBeEscaped, $nodes->getNode('body')->getNode(0)->getNode('expr') instanceof FilterExpression); } public function getEscapingTemplates() diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php b/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php index a6c397ffd4d90..90db2c5d6bd44 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/RuntimeLoaderProvider.php @@ -12,12 +12,13 @@ namespace Symfony\Bridge\Twig\Tests\Extension; use Symfony\Bridge\Twig\Form\TwigRenderer; +use Twig\Environment; trait RuntimeLoaderProvider { - protected function registerTwigRuntimeLoader(\Twig_Environment $environment, TwigRenderer $renderer) + protected function registerTwigRuntimeLoader(Environment $environment, TwigRenderer $renderer) { - $loader = $this->getMockBuilder('Twig_RuntimeLoaderInterface')->getMock(); + $loader = $this->getMockBuilder('Twig\RuntimeLoader\RuntimeLoaderInterface')->getMock(); $loader->expects($this->any())->method('load')->will($this->returnValueMap(array( array('Symfony\Bridge\Twig\Form\TwigRenderer', $renderer), ))); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php index c50252eaafcca..25b2e029ee75c 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.php @@ -13,11 +13,14 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\StopwatchExtension; +use Twig\Environment; +use Twig\Error\RuntimeError; +use Twig\Loader\ArrayLoader; class StopwatchExtensionTest extends TestCase { /** - * @expectedException \Twig_Error_Syntax + * @expectedException \Twig\Error\SyntaxError */ public function testFailIfStoppingWrongEvent() { @@ -29,12 +32,12 @@ public function testFailIfStoppingWrongEvent() */ public function testTiming($template, $events) { - $twig = new \Twig_Environment(new \Twig_Loader_Array(array('template' => $template)), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); + $twig = new Environment(new ArrayLoader(array('template' => $template)), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0)); $twig->addExtension(new StopwatchExtension($this->getStopwatch($events))); try { $nodes = $twig->render('template'); - } catch (\Twig_Error_Runtime $e) { + } catch (RuntimeError $e) { throw $e->getPrevious(); } } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php index 446697d3dd8b2..36016d7f49bca 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php @@ -16,6 +16,8 @@ use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\MessageSelector; use Symfony\Component\Translation\Loader\ArrayLoader; +use Twig\Environment; +use Twig\Loader\ArrayLoader as TwigArrayLoader; class TranslationExtensionTest extends TestCase { @@ -33,8 +35,8 @@ public function testTrans($template, $expected, array $variables = array()) { if ($expected != $this->getTemplate($template)->render($variables)) { echo $template."\n"; - $loader = new \Twig_Loader_Array(array('index' => $template)); - $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false)); + $loader = new TwigArrayLoader(array('index' => $template)); + $twig = new Environment($loader, array('debug' => true, 'cache' => false)); $twig->addExtension(new TranslationExtension(new Translator('en', new MessageSelector()))); echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSourceContext('index'))))."\n\n"; @@ -45,7 +47,7 @@ public function testTrans($template, $expected, array $variables = array()) } /** - * @expectedException \Twig_Error_Syntax + * @expectedException \Twig\Error\SyntaxError * @expectedExceptionMessage Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3. */ public function testTransUnknownKeyword() @@ -54,7 +56,7 @@ public function testTransUnknownKeyword() } /** - * @expectedException \Twig_Error_Syntax + * @expectedException \Twig\Error\SyntaxError * @expectedExceptionMessage A message inside a trans tag must be a simple text in "index" at line 2. */ public function testTransComplexBody() @@ -63,7 +65,7 @@ public function testTransComplexBody() } /** - * @expectedException \Twig_Error_Syntax + * @expectedException \Twig\Error\SyntaxError * @expectedExceptionMessage A message inside a transchoice tag must be a simple text in "index" at line 2. */ public function testTransChoiceComplexBody() @@ -189,11 +191,11 @@ protected function getTemplate($template, $translator = null) } if (is_array($template)) { - $loader = new \Twig_Loader_Array($template); + $loader = new TwigArrayLoader($template); } else { - $loader = new \Twig_Loader_Array(array('index' => $template)); + $loader = new TwigArrayLoader(array('index' => $template)); } - $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false)); + $twig = new Environment($loader, array('debug' => true, 'cache' => false)); $twig->addExtension(new TranslationExtension($translator)); return $twig->loadTemplate('index'); diff --git a/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php index 5e589c2db11db..7f8737a3af6ef 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/DumpNodeTest.php @@ -13,6 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Node\DumpNode; +use Twig\Compiler; +use Twig\Environment; +use Twig\Node\Expression\NameExpression; +use Twig\Node\Node; class DumpNodeTest extends TestCase { @@ -20,14 +24,14 @@ public function testNoVar() { $node = new DumpNode('bar', null, 7); - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); - $compiler = new \Twig_Compiler($env); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); + $compiler = new Compiler($env); $expected = <<<'EOTXT' if ($this->env->isDebug()) { $barvars = array(); foreach ($context as $barkey => $barval) { - if (!$barval instanceof \Twig_Template) { + if (!$barval instanceof \Twig\Template) { $barvars[$barkey] = $barval; } } @@ -44,14 +48,14 @@ public function testIndented() { $node = new DumpNode('bar', null, 7); - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); - $compiler = new \Twig_Compiler($env); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); + $compiler = new Compiler($env); $expected = <<<'EOTXT' if ($this->env->isDebug()) { $barvars = array(); foreach ($context as $barkey => $barval) { - if (!$barval instanceof \Twig_Template) { + if (!$barval instanceof \Twig\Template) { $barvars[$barkey] = $barval; } } @@ -66,13 +70,13 @@ public function testIndented() public function testOneVar() { - $vars = new \Twig_Node(array( - new \Twig_Node_Expression_Name('foo', 7), + $vars = new Node(array( + new NameExpression('foo', 7), )); $node = new DumpNode('bar', $vars, 7); - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); - $compiler = new \Twig_Compiler($env); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); + $compiler = new Compiler($env); $expected = <<<'EOTXT' if ($this->env->isDebug()) { @@ -82,7 +86,7 @@ public function testOneVar() EOTXT; - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $expected = preg_replace('/%(.*?)%/', '($context["$1"] ?? null)', $expected); } else { $expected = preg_replace('/%(.*?)%/', '(isset($context["$1"]) ? $context["$1"] : null)', $expected); @@ -93,14 +97,14 @@ public function testOneVar() public function testMultiVars() { - $vars = new \Twig_Node(array( - new \Twig_Node_Expression_Name('foo', 7), - new \Twig_Node_Expression_Name('bar', 7), + $vars = new Node(array( + new NameExpression('foo', 7), + new NameExpression('bar', 7), )); $node = new DumpNode('bar', $vars, 7); - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); - $compiler = new \Twig_Compiler($env); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); + $compiler = new Compiler($env); $expected = <<<'EOTXT' if ($this->env->isDebug()) { @@ -113,7 +117,7 @@ public function testMultiVars() EOTXT; - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $expected = preg_replace('/%(.*?)%/', '($context["$1"] ?? null)', $expected); } else { $expected = preg_replace('/%(.*?)%/', '(isset($context["$1"]) ? $context["$1"] : null)', $expected); diff --git a/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php index 9d3576e0b4430..c40fcbdc90b3e 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.php @@ -13,15 +13,21 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Node\FormThemeNode; +use Twig\Compiler; +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Node\Node; class FormThemeTest extends TestCase { public function testConstructor() { - $form = new \Twig_Node_Expression_Name('form', 0); - $resources = new \Twig_Node(array( - new \Twig_Node_Expression_Constant('tpl1', 0), - new \Twig_Node_Expression_Constant('tpl2', 0), + $form = new NameExpression('form', 0); + $resources = new Node(array( + new ConstantExpression('tpl1', 0), + new ConstantExpression('tpl2', 0), )); $node = new FormThemeNode($form, $resources, 0); @@ -32,17 +38,17 @@ public function testConstructor() public function testCompile() { - $form = new \Twig_Node_Expression_Name('form', 0); - $resources = new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant(0, 0), - new \Twig_Node_Expression_Constant('tpl1', 0), - new \Twig_Node_Expression_Constant(1, 0), - new \Twig_Node_Expression_Constant('tpl2', 0), + $form = new NameExpression('form', 0); + $resources = new ArrayExpression(array( + new ConstantExpression(0, 0), + new ConstantExpression('tpl1', 0), + new ConstantExpression(1, 0), + new ConstantExpression('tpl2', 0), ), 0); $node = new FormThemeNode($form, $resources, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); $this->assertEquals( sprintf( @@ -52,7 +58,7 @@ public function testCompile() trim($compiler->compile($node)->getSource()) ); - $resources = new \Twig_Node_Expression_Constant('tpl1', 0); + $resources = new ConstantExpression('tpl1', 0); $node = new FormThemeNode($form, $resources, 0); @@ -67,7 +73,7 @@ public function testCompile() protected function getVariableGetter($name) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { return sprintf('($context["%s"] ?? null)', $name, $name); } diff --git a/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php index b292ef63f8555..fe91422a3535f 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.php @@ -13,18 +13,25 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode; +use Twig\Compiler; +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConditionalExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Node\Node; class SearchAndRenderBlockNodeTest extends TestCase { public function testCompileWidget() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), + $arguments = new Node(array( + new NameExpression('form', 0), )); $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); $this->assertEquals( sprintf( @@ -37,17 +44,17 @@ public function testCompileWidget() public function testCompileWidgetWithVariables() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant('foo', 0), - new \Twig_Node_Expression_Constant('bar', 0), + $arguments = new Node(array( + new NameExpression('form', 0), + new ArrayExpression(array( + new ConstantExpression('foo', 0), + new ConstantExpression('bar', 0), ), 0), )); $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); $this->assertEquals( sprintf( @@ -60,14 +67,14 @@ public function testCompileWidgetWithVariables() public function testCompileLabelWithLabel() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Constant('my label', 0), + $arguments = new Node(array( + new NameExpression('form', 0), + new ConstantExpression('my label', 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); $this->assertEquals( sprintf( @@ -80,14 +87,14 @@ public function testCompileLabelWithLabel() public function testCompileLabelWithNullLabel() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Constant(null, 0), + $arguments = new Node(array( + new NameExpression('form', 0), + new ConstantExpression(null, 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -102,14 +109,14 @@ public function testCompileLabelWithNullLabel() public function testCompileLabelWithEmptyStringLabel() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Constant('', 0), + $arguments = new Node(array( + new NameExpression('form', 0), + new ConstantExpression('', 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -124,13 +131,13 @@ public function testCompileLabelWithEmptyStringLabel() public function testCompileLabelWithDefaultLabel() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), + $arguments = new Node(array( + new NameExpression('form', 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); $this->assertEquals( sprintf( @@ -143,18 +150,18 @@ public function testCompileLabelWithDefaultLabel() public function testCompileLabelWithAttributes() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Constant(null, 0), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant('foo', 0), - new \Twig_Node_Expression_Constant('bar', 0), + $arguments = new Node(array( + new NameExpression('form', 0), + new ConstantExpression(null, 0), + new ArrayExpression(array( + new ConstantExpression('foo', 0), + new ConstantExpression('bar', 0), ), 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -170,20 +177,20 @@ public function testCompileLabelWithAttributes() public function testCompileLabelWithLabelAndAttributes() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Constant('value in argument', 0), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant('foo', 0), - new \Twig_Node_Expression_Constant('bar', 0), - new \Twig_Node_Expression_Constant('label', 0), - new \Twig_Node_Expression_Constant('value in attributes', 0), + $arguments = new Node(array( + new NameExpression('form', 0), + new ConstantExpression('value in argument', 0), + new ArrayExpression(array( + new ConstantExpression('foo', 0), + new ConstantExpression('bar', 0), + new ConstantExpression('label', 0), + new ConstantExpression('value in attributes', 0), ), 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); $this->assertEquals( sprintf( @@ -196,22 +203,22 @@ public function testCompileLabelWithLabelAndAttributes() public function testCompileLabelWithLabelThatEvaluatesToNull() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Conditional( + $arguments = new Node(array( + new NameExpression('form', 0), + new ConditionalExpression( // if - new \Twig_Node_Expression_Constant(true, 0), + new ConstantExpression(true, 0), // then - new \Twig_Node_Expression_Constant(null, 0), + new ConstantExpression(null, 0), // else - new \Twig_Node_Expression_Constant(null, 0), + new ConstantExpression(null, 0), 0 ), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -227,28 +234,28 @@ public function testCompileLabelWithLabelThatEvaluatesToNull() public function testCompileLabelWithLabelThatEvaluatesToNullAndAttributes() { - $arguments = new \Twig_Node(array( - new \Twig_Node_Expression_Name('form', 0), - new \Twig_Node_Expression_Conditional( + $arguments = new Node(array( + new NameExpression('form', 0), + new ConditionalExpression( // if - new \Twig_Node_Expression_Constant(true, 0), + new ConstantExpression(true, 0), // then - new \Twig_Node_Expression_Constant(null, 0), + new ConstantExpression(null, 0), // else - new \Twig_Node_Expression_Constant(null, 0), + new ConstantExpression(null, 0), 0 ), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant('foo', 0), - new \Twig_Node_Expression_Constant('bar', 0), - new \Twig_Node_Expression_Constant('label', 0), - new \Twig_Node_Expression_Constant('value in attributes', 0), + new ArrayExpression(array( + new ConstantExpression('foo', 0), + new ConstantExpression('bar', 0), + new ConstantExpression('label', 0), + new ConstantExpression('value in attributes', 0), ), 0), )); $node = new SearchAndRenderBlockNode('form_label', $arguments, 0); - $compiler = new \Twig_Compiler(new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $compiler = new Compiler(new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock())); // "label" => null must not be included in the output! // Otherwise the default label is overwritten with null. @@ -264,7 +271,7 @@ public function testCompileLabelWithLabelThatEvaluatesToNullAndAttributes() protected function getVariableGetter($name) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { return sprintf('($context["%s"] ?? null)', $name, $name); } diff --git a/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php b/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php index 5862006f3826a..56b2770d357f6 100644 --- a/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Node/TransNodeTest.php @@ -13,6 +13,10 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Node\TransNode; +use Twig\Compiler; +use Twig\Environment; +use Twig\Node\Expression\NameExpression; +use Twig\Node\TextNode; /** * @author Asmir Mustafic @@ -21,12 +25,12 @@ class TransNodeTest extends TestCase { public function testCompileStrict() { - $body = new \Twig_Node_Text('trans %var%', 0); - $vars = new \Twig_Node_Expression_Name('foo', 0); + $body = new TextNode('trans %var%', 0); + $vars = new NameExpression('foo', 0); $node = new TransNode($body, null, null, $vars); - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true)); - $compiler = new \Twig_Compiler($env); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('strict_variables' => true)); + $compiler = new Compiler($env); $this->assertEquals( sprintf( @@ -40,7 +44,7 @@ public function testCompileStrict() protected function getVariableGetterWithoutStrictCheck($name) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { return sprintf('($context["%s"] ?? null)', $name, $name); } @@ -49,11 +53,11 @@ protected function getVariableGetterWithoutStrictCheck($name) protected function getVariableGetterWithStrictCheck($name) { - if (\Twig_Environment::MAJOR_VERSION >= 2) { + if (Environment::MAJOR_VERSION >= 2) { return sprintf('(isset($context["%s"]) || array_key_exists("%s", $context) ? $context["%s"] : (function () { throw new Twig_Error_Runtime(\'Variable "%s" does not exist.\', 0, $this->getSourceContext()); })())', $name, $name, $name, $name); } - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { return sprintf('($context["%s"] ?? $this->getContext($context, "%s"))', $name, $name, $name); } diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php index da9f43a6c4e0e..eb4c9a83e86d7 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php @@ -14,6 +14,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor; use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor; +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Node; class TranslationDefaultDomainNodeVisitorTest extends TestCase { @@ -21,9 +24,9 @@ class TranslationDefaultDomainNodeVisitorTest extends TestCase private static $domain = 'domain'; /** @dataProvider getDefaultDomainAssignmentTestData */ - public function testDefaultDomainAssignment(\Twig_Node $node) + public function testDefaultDomainAssignment(Node $node) { - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); $visitor = new TranslationDefaultDomainNodeVisitor(); // visit trans_default_domain tag @@ -47,9 +50,9 @@ public function testDefaultDomainAssignment(\Twig_Node $node) } /** @dataProvider getDefaultDomainAssignmentTestData */ - public function testNewModuleWithoutDefaultDomainTag(\Twig_Node $node) + public function testNewModuleWithoutDefaultDomainTag(Node $node) { - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); $visitor = new TranslationDefaultDomainNodeVisitor(); // visit trans_default_domain tag @@ -80,10 +83,10 @@ public function getDefaultDomainAssignmentTestData() array(TwigNodeProvider::getTransTag(self::$message)), // with named arguments array(TwigNodeProvider::getTransFilter(self::$message, null, array( - 'arguments' => new \Twig_Node_Expression_Array(array(), 0), + 'arguments' => new ArrayExpression(array(), 0), ))), array(TwigNodeProvider::getTransChoiceFilter(self::$message), null, array( - 'arguments' => new \Twig_Node_Expression_Array(array(), 0), + 'arguments' => new ArrayExpression(array(), 0), )), ); } diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php index d12fff532aaa1..9c2d0ab9e40e5 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php @@ -13,13 +13,19 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor; +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\FilterExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Node\Node; class TranslationNodeVisitorTest extends TestCase { /** @dataProvider getMessagesExtractionTestData */ - public function testMessagesExtraction(\Twig_Node $node, array $expectedMessages) + public function testMessagesExtraction(Node $node, array $expectedMessages) { - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); $visitor = new TranslationNodeVisitor(); $visitor->enable(); $visitor->enterNode($node, $env); @@ -31,12 +37,12 @@ public function testMessageExtractionWithInvalidDomainNode() { $message = 'new key'; - $node = new \Twig_Node_Expression_Filter( - new \Twig_Node_Expression_Constant($message, 0), - new \Twig_Node_Expression_Constant('trans', 0), - new \Twig_Node(array( - new \Twig_Node_Expression_Array(array(), 0), - new \Twig_Node_Expression_Name('variable', 0), + $node = new FilterExpression( + new ConstantExpression($message, 0), + new ConstantExpression('trans', 0), + new Node(array( + new ArrayExpression(array(), 0), + new NameExpression('variable', 0), )), 0 ); diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php index 502cad38dec0b..49eac23e8aeda 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php @@ -13,19 +13,26 @@ use Symfony\Bridge\Twig\Node\TransDefaultDomainNode; use Symfony\Bridge\Twig\Node\TransNode; +use Twig\Node\BodyNode; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\FilterExpression; +use Twig\Node\ModuleNode; +use Twig\Node\Node; +use Twig\Source; class TwigNodeProvider { public static function getModule($content) { - return new \Twig_Node_Module( - new \Twig_Node_Expression_Constant($content, 0), + return new ModuleNode( + new ConstantExpression($content, 0), null, - new \Twig_Node_Expression_Array(array(), 0), - new \Twig_Node_Expression_Array(array(), 0), - new \Twig_Node_Expression_Array(array(), 0), + new ArrayExpression(array(), 0), + new ArrayExpression(array(), 0), + new ArrayExpression(array(), 0), null, - new \Twig_Source('', '') + new Source('', '') ); } @@ -33,15 +40,15 @@ public static function getTransFilter($message, $domain = null, $arguments = nul { if (!$arguments) { $arguments = $domain ? array( - new \Twig_Node_Expression_Array(array(), 0), - new \Twig_Node_Expression_Constant($domain, 0), + new ArrayExpression(array(), 0), + new ConstantExpression($domain, 0), ) : array(); } - return new \Twig_Node_Expression_Filter( - new \Twig_Node_Expression_Constant($message, 0), - new \Twig_Node_Expression_Constant('trans', 0), - new \Twig_Node($arguments), + return new FilterExpression( + new ConstantExpression($message, 0), + new ConstantExpression('trans', 0), + new Node($arguments), 0 ); } @@ -50,16 +57,16 @@ public static function getTransChoiceFilter($message, $domain = null, $arguments { if (!$arguments) { $arguments = $domain ? array( - new \Twig_Node_Expression_Constant(0, 0), - new \Twig_Node_Expression_Array(array(), 0), - new \Twig_Node_Expression_Constant($domain, 0), + new ConstantExpression(0, 0), + new ArrayExpression(array(), 0), + new ConstantExpression($domain, 0), ) : array(); } - return new \Twig_Node_Expression_Filter( - new \Twig_Node_Expression_Constant($message, 0), - new \Twig_Node_Expression_Constant('transchoice', 0), - new \Twig_Node($arguments), + return new FilterExpression( + new ConstantExpression($message, 0), + new ConstantExpression('transchoice', 0), + new Node($arguments), 0 ); } @@ -67,15 +74,15 @@ public static function getTransChoiceFilter($message, $domain = null, $arguments public static function getTransTag($message, $domain = null) { return new TransNode( - new \Twig_Node_Body(array(), array('data' => $message)), - $domain ? new \Twig_Node_Expression_Constant($domain, 0) : null + new BodyNode(array(), array('data' => $message)), + $domain ? new ConstantExpression($domain, 0) : null ); } public static function getTransDefaultDomainTag($domain) { return new TransDefaultDomainNode( - new \Twig_Node_Expression_Constant($domain, 0) + new ConstantExpression($domain, 0) ); } } diff --git a/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php b/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php index 8931be061f9d2..0972b15e23fdc 100644 --- a/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php +++ b/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php @@ -14,6 +14,12 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\TokenParser\FormThemeTokenParser; use Symfony\Bridge\Twig\Node\FormThemeNode; +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Parser; +use Twig\Source; class FormThemeTokenParserTest extends TestCase { @@ -22,10 +28,10 @@ class FormThemeTokenParserTest extends TestCase */ public function testCompile($source, $expected) { - $env = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); + $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); $env->addTokenParser(new FormThemeTokenParser()); - $stream = $env->tokenize(new \Twig_Source($source, '')); - $parser = new \Twig_Parser($env); + $stream = $env->tokenize(new Source($source, '')); + $parser = new Parser($env); $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0)); } @@ -36,10 +42,10 @@ public function getTestsForFormTheme() array( '{% form_theme form "tpl1" %}', new FormThemeNode( - new \Twig_Node_Expression_Name('form', 1), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant(0, 1), - new \Twig_Node_Expression_Constant('tpl1', 1), + new NameExpression('form', 1), + new ArrayExpression(array( + new ConstantExpression(0, 1), + new ConstantExpression('tpl1', 1), ), 1), 1, 'form_theme' @@ -48,12 +54,12 @@ public function getTestsForFormTheme() array( '{% form_theme form "tpl1" "tpl2" %}', new FormThemeNode( - new \Twig_Node_Expression_Name('form', 1), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant(0, 1), - new \Twig_Node_Expression_Constant('tpl1', 1), - new \Twig_Node_Expression_Constant(1, 1), - new \Twig_Node_Expression_Constant('tpl2', 1), + new NameExpression('form', 1), + new ArrayExpression(array( + new ConstantExpression(0, 1), + new ConstantExpression('tpl1', 1), + new ConstantExpression(1, 1), + new ConstantExpression('tpl2', 1), ), 1), 1, 'form_theme' @@ -62,8 +68,8 @@ public function getTestsForFormTheme() array( '{% form_theme form with "tpl1" %}', new FormThemeNode( - new \Twig_Node_Expression_Name('form', 1), - new \Twig_Node_Expression_Constant('tpl1', 1), + new NameExpression('form', 1), + new ConstantExpression('tpl1', 1), 1, 'form_theme' ), @@ -71,10 +77,10 @@ public function getTestsForFormTheme() array( '{% form_theme form with ["tpl1"] %}', new FormThemeNode( - new \Twig_Node_Expression_Name('form', 1), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant(0, 1), - new \Twig_Node_Expression_Constant('tpl1', 1), + new NameExpression('form', 1), + new ArrayExpression(array( + new ConstantExpression(0, 1), + new ConstantExpression('tpl1', 1), ), 1), 1, 'form_theme' @@ -83,12 +89,12 @@ public function getTestsForFormTheme() array( '{% form_theme form with ["tpl1", "tpl2"] %}', new FormThemeNode( - new \Twig_Node_Expression_Name('form', 1), - new \Twig_Node_Expression_Array(array( - new \Twig_Node_Expression_Constant(0, 1), - new \Twig_Node_Expression_Constant('tpl1', 1), - new \Twig_Node_Expression_Constant(1, 1), - new \Twig_Node_Expression_Constant('tpl2', 1), + new NameExpression('form', 1), + new ArrayExpression(array( + new ConstantExpression(0, 1), + new ConstantExpression('tpl1', 1), + new ConstantExpression(1, 1), + new ConstantExpression('tpl2', 1), ), 1), 1, 'form_theme' diff --git a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php index 0b1fb28b0e10c..013598a40b17f 100644 --- a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php @@ -15,6 +15,9 @@ use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Translation\TwigExtractor; use Symfony\Component\Translation\MessageCatalogue; +use Twig\Environment; +use Twig\Error\Error; +use Twig\Loader\ArrayLoader; class TwigExtractorTest extends TestCase { @@ -23,8 +26,8 @@ class TwigExtractorTest extends TestCase */ public function testExtract($template, $messages) { - $loader = $this->getMockBuilder('Twig_LoaderInterface')->getMock(); - $twig = new \Twig_Environment($loader, array( + $loader = $this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(); + $twig = new Environment($loader, array( 'strict_variables' => true, 'debug' => true, 'cache' => false, @@ -73,19 +76,19 @@ public function getExtractData() } /** - * @expectedException \Twig_Error + * @expectedException \Twig\Error\Error * @dataProvider resourcesWithSyntaxErrorsProvider */ public function testExtractSyntaxError($resources) { - $twig = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); $twig->addExtension(new TranslationExtension($this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock())); $extractor = new TwigExtractor($twig); try { $extractor->extract($resources, new MessageCatalogue('en')); - } catch (\Twig_Error $e) { + } catch (Error $e) { if (method_exists($e, 'getSourceContext')) { $this->assertSame(dirname(__DIR__).strtr('/Fixtures/extractor/syntax_error.twig', '/', DIRECTORY_SEPARATOR), $e->getFile()); $this->assertSame(1, $e->getLine()); @@ -114,8 +117,8 @@ public function resourcesWithSyntaxErrorsProvider() */ public function testExtractWithFiles($resource) { - $loader = new \Twig_Loader_Array(array()); - $twig = new \Twig_Environment($loader, array( + $loader = new ArrayLoader(array()); + $twig = new Environment($loader, array( 'strict_variables' => true, 'debug' => true, 'cache' => false, diff --git a/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php b/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php index e2082df3dd75b..a74c59e8d28c9 100644 --- a/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php +++ b/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\TwigEngine; use Symfony\Component\Templating\TemplateReference; +use Twig\Environment; +use Twig\Loader\ArrayLoader; class TwigEngineTest extends TestCase { @@ -21,7 +23,7 @@ public function testExistsWithTemplateInstances() { $engine = $this->getTwig(); - $this->assertTrue($engine->exists($this->getMockForAbstractClass('Twig_Template', array(), '', false))); + $this->assertTrue($engine->exists($this->getMockForAbstractClass('Twig\Template', array(), '', false))); } public function testExistsWithNonExistentTemplates() @@ -57,7 +59,7 @@ public function testRender() } /** - * @expectedException \Twig_Error_Syntax + * @expectedException \Twig\Error\SyntaxError */ public function testRenderWithError() { @@ -68,7 +70,7 @@ public function testRenderWithError() protected function getTwig() { - $twig = new \Twig_Environment(new \Twig_Loader_Array(array( + $twig = new Environment(new ArrayLoader(array( 'index' => 'foo', 'error' => '{{ foo }', ))); diff --git a/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php index 269ead64f5d40..7cdbb77b4349b 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php @@ -12,6 +12,8 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\DumpNode; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the 'dump' tag. @@ -25,18 +27,18 @@ * * @author Julien Galenski */ -class DumpTokenParser extends \Twig_TokenParser +class DumpTokenParser extends AbstractTokenParser { /** * {@inheritdoc} */ - public function parse(\Twig_Token $token) + public function parse(Token $token) { $values = null; - if (!$this->parser->getStream()->test(\Twig_Token::BLOCK_END_TYPE)) { + if (!$this->parser->getStream()->test(Token::BLOCK_END_TYPE)) { $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); } - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new DumpNode($this->parser->getVarName(), $values, $token->getLine(), $this->getTag()); } diff --git a/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php index daf87824e7b21..12c2541851e63 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php @@ -12,39 +12,43 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\FormThemeNode; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Node; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the 'form_theme' tag. * * @author Fabien Potencier */ -class FormThemeTokenParser extends \Twig_TokenParser +class FormThemeTokenParser extends AbstractTokenParser { /** * Parses a token and returns a node. * - * @param \Twig_Token $token A Twig_Token instance + * @param Token $token * - * @return \Twig_Node A Twig_Node instance + * @return Node */ - public function parse(\Twig_Token $token) + public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $form = $this->parser->getExpressionParser()->parseExpression(); - if ($this->parser->getStream()->test(\Twig_Token::NAME_TYPE, 'with')) { + if ($this->parser->getStream()->test(Token::NAME_TYPE, 'with')) { $this->parser->getStream()->next(); $resources = $this->parser->getExpressionParser()->parseExpression(); } else { - $resources = new \Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine()); + $resources = new ArrayExpression(array(), $stream->getCurrent()->getLine()); do { $resources->addElement($this->parser->getExpressionParser()->parseExpression()); - } while (!$stream->test(\Twig_Token::BLOCK_END_TYPE)); + } while (!$stream->test(Token::BLOCK_END_TYPE)); } - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); return new FormThemeNode($form, $resources, $lineno, $this->getTag()); } diff --git a/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php index 2983e4cb6b03b..82c58d40bbf8d 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php @@ -12,13 +12,16 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\StopwatchNode; +use Twig\Node\Expression\AssignNameExpression; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the stopwatch tag. * * @author Wouter J */ -class StopwatchTokenParser extends \Twig_TokenParser +class StopwatchTokenParser extends AbstractTokenParser { protected $stopwatchIsAvailable; @@ -27,7 +30,7 @@ public function __construct($stopwatchIsAvailable) $this->stopwatchIsAvailable = $stopwatchIsAvailable; } - public function parse(\Twig_Token $token) + public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); @@ -35,20 +38,20 @@ public function parse(\Twig_Token $token) // {% stopwatch 'bar' %} $name = $this->parser->getExpressionParser()->parseExpression(); - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); // {% endstopwatch %} $body = $this->parser->subparse(array($this, 'decideStopwatchEnd'), true); - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); if ($this->stopwatchIsAvailable) { - return new StopwatchNode($name, $body, new \Twig_Node_Expression_AssignName($this->parser->getVarName(), $token->getLine()), $lineno, $this->getTag()); + return new StopwatchNode($name, $body, new AssignNameExpression($this->parser->getVarName(), $token->getLine()), $lineno, $this->getTag()); } return $body; } - public function decideStopwatchEnd(\Twig_Token $token) + public function decideStopwatchEnd(Token $token) { return $token->test('endstopwatch'); } diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php index fa61a2f1486c5..2b4a9f3fc4636 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php @@ -12,6 +12,12 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\TransNode; +use Twig\Error\SyntaxError; +use Twig\Node\Expression\AbstractExpression; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Node; +use Twig\Node\TextNode; +use Twig\Token; /** * Token Parser for the 'transchoice' tag. @@ -23,18 +29,18 @@ class TransChoiceTokenParser extends TransTokenParser /** * Parses a token and returns a node. * - * @param \Twig_Token $token A Twig_Token instance + * @param Token $token * - * @return \Twig_Node A Twig_Node instance + * @return Node * - * @throws \Twig_Error_Syntax + * @throws SyntaxError */ - public function parse(\Twig_Token $token) + public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); - $vars = new \Twig_Node_Expression_Array(array(), $lineno); + $vars = new ArrayExpression(array(), $lineno); $count = $this->parser->getExpressionParser()->parseExpression(); @@ -59,15 +65,15 @@ public function parse(\Twig_Token $token) $locale = $this->parser->getExpressionParser()->parseExpression(); } - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); $body = $this->parser->subparse(array($this, 'decideTransChoiceFork'), true); - if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) { - throw new \Twig_Error_Syntax('A message inside a transchoice tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()->getName()); + if (!$body instanceof TextNode && !$body instanceof AbstractExpression) { + throw new SyntaxError('A message inside a transchoice tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()->getName()); } - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag()); } diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php index 09832ea972d91..4096a011a300d 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php @@ -12,26 +12,29 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\TransDefaultDomainNode; +use Twig\Node\Node; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the 'trans_default_domain' tag. * * @author Fabien Potencier */ -class TransDefaultDomainTokenParser extends \Twig_TokenParser +class TransDefaultDomainTokenParser extends AbstractTokenParser { /** * Parses a token and returns a node. * - * @param \Twig_Token $token A Twig_Token instance + * @param Token $token * - * @return \Twig_Node A Twig_Node instance + * @return Node */ - public function parse(\Twig_Token $token) + public function parse(Token $token) { $expr = $this->parser->getExpressionParser()->parseExpression(); - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new TransDefaultDomainNode($expr, $token->getLine(), $this->getTag()); } diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php index 4c8e7d3eeea38..848a080710fa1 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php @@ -12,32 +12,39 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\TransNode; +use Twig\Error\SyntaxError; +use Twig\Node\Expression\AbstractExpression; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Node; +use Twig\Node\TextNode; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; /** * Token Parser for the 'trans' tag. * * @author Fabien Potencier */ -class TransTokenParser extends \Twig_TokenParser +class TransTokenParser extends AbstractTokenParser { /** * Parses a token and returns a node. * - * @param \Twig_Token $token A Twig_Token instance + * @param Token $token * - * @return \Twig_Node A Twig_Node instance + * @return Node * - * @throws \Twig_Error_Syntax + * @throws SyntaxError */ - public function parse(\Twig_Token $token) + public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); - $vars = new \Twig_Node_Expression_Array(array(), $lineno); + $vars = new ArrayExpression(array(), $lineno); $domain = null; $locale = null; - if (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) { + if (!$stream->test(Token::BLOCK_END_TYPE)) { if ($stream->test('with')) { // {% trans with vars %} $stream->next(); @@ -54,20 +61,20 @@ public function parse(\Twig_Token $token) // {% trans into "fr" %} $stream->next(); $locale = $this->parser->getExpressionParser()->parseExpression(); - } elseif (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) { - throw new \Twig_Error_Syntax('Unexpected token. Twig was looking for the "with", "from", or "into" keyword.', $stream->getCurrent()->getLine(), $stream->getSourceContext()->getName()); + } elseif (!$stream->test(Token::BLOCK_END_TYPE)) { + throw new SyntaxError('Unexpected token. Twig was looking for the "with", "from", or "into" keyword.', $stream->getCurrent()->getLine(), $stream->getSourceContext()->getName()); } } // {% trans %}message{% endtrans %} - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); $body = $this->parser->subparse(array($this, 'decideTransFork'), true); - if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) { - throw new \Twig_Error_Syntax('A message inside a trans tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()->getName()); + if (!$body instanceof TextNode && !$body instanceof AbstractExpression) { + throw new SyntaxError('A message inside a trans tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()->getName()); } - $stream->expect(\Twig_Token::BLOCK_END_TYPE); + $stream->expect(Token::BLOCK_END_TYPE); return new TransNode($body, $domain, null, $vars, $locale, $lineno, $this->getTag()); } diff --git a/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php b/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php index 35995dbd64518..bd35fe5a8b1eb 100644 --- a/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php +++ b/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php @@ -16,6 +16,9 @@ use Symfony\Component\Translation\Extractor\AbstractFileExtractor; use Symfony\Component\Translation\Extractor\ExtractorInterface; use Symfony\Component\Translation\MessageCatalogue; +use Twig\Environment; +use Twig\Error\Error; +use Twig\Source; /** * TwigExtractor extracts translation messages from a twig template. @@ -42,11 +45,11 @@ class TwigExtractor extends AbstractFileExtractor implements ExtractorInterface /** * The twig environment. * - * @var \Twig_Environment + * @var Environment */ private $twig; - public function __construct(\Twig_Environment $twig) + public function __construct(Environment $twig) { $this->twig = $twig; } @@ -60,12 +63,12 @@ public function extract($resource, MessageCatalogue $catalogue) foreach ($files as $file) { try { $this->extractTemplate(file_get_contents($file->getPathname()), $catalogue); - } catch (\Twig_Error $e) { + } catch (Error $e) { if ($file instanceof \SplFileInfo) { $path = $file->getRealPath() ?: $file->getPathname(); $name = $file instanceof SplFileInfo ? $file->getRelativePathname() : $path; if (method_exists($e, 'setSourceContext')) { - $e->setSourceContext(new \Twig_Source('', $name, $path)); + $e->setSourceContext(new Source('', $name, $path)); } else { $e->setTemplateName($name); } @@ -89,7 +92,7 @@ protected function extractTemplate($template, MessageCatalogue $catalogue) $visitor = $this->twig->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->getTranslationNodeVisitor(); $visitor->enable(); - $this->twig->parse($this->twig->tokenize(new \Twig_Source($template, ''))); + $this->twig->parse($this->twig->tokenize(new Source($template, ''))); foreach ($visitor->getMessages() as $message) { $catalogue->set(trim($message[0]), $this->prefix.trim($message[0]), $message[1] ?: $this->defaultDomain); diff --git a/src/Symfony/Bridge/Twig/TwigEngine.php b/src/Symfony/Bridge/Twig/TwigEngine.php index 760461b5be578..bc0a4fecc9af5 100644 --- a/src/Symfony/Bridge/Twig/TwigEngine.php +++ b/src/Symfony/Bridge/Twig/TwigEngine.php @@ -15,6 +15,11 @@ use Symfony\Component\Templating\StreamingEngineInterface; use Symfony\Component\Templating\TemplateNameParserInterface; use Symfony\Component\Templating\TemplateReferenceInterface; +use Twig\Environment; +use Twig\Error\Error; +use Twig\Error\LoaderError; +use Twig\Loader\ExistsLoaderInterface; +use Twig\Template; /** * This engine knows how to render Twig templates. @@ -26,13 +31,7 @@ class TwigEngine implements EngineInterface, StreamingEngineInterface protected $environment; protected $parser; - /** - * Constructor. - * - * @param \Twig_Environment $environment A \Twig_Environment instance - * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance - */ - public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser) + public function __construct(Environment $environment, TemplateNameParserInterface $parser) { $this->environment = $environment; $this->parser = $parser; @@ -41,9 +40,9 @@ public function __construct(\Twig_Environment $environment, TemplateNameParserIn /** * {@inheritdoc} * - * It also supports \Twig_Template as name parameter. + * It also supports Template as name parameter. * - * @throws \Twig_Error if something went wrong like a thrown exception while rendering the template + * @throws Error if something went wrong like a thrown exception while rendering the template */ public function render($name, array $parameters = array()) { @@ -53,9 +52,9 @@ public function render($name, array $parameters = array()) /** * {@inheritdoc} * - * It also supports \Twig_Template as name parameter. + * It also supports Template as name parameter. * - * @throws \Twig_Error if something went wrong like a thrown exception while rendering the template + * @throws Error if something went wrong like a thrown exception while rendering the template */ public function stream($name, array $parameters = array()) { @@ -65,25 +64,25 @@ public function stream($name, array $parameters = array()) /** * {@inheritdoc} * - * It also supports \Twig_Template as name parameter. + * It also supports Template as name parameter. */ public function exists($name) { - if ($name instanceof \Twig_Template) { + if ($name instanceof Template) { return true; } $loader = $this->environment->getLoader(); - if ($loader instanceof \Twig_ExistsLoaderInterface || method_exists($loader, 'exists')) { + if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { return $loader->exists((string) $name); } try { // cast possible TemplateReferenceInterface to string because the - // EngineInterface supports them but Twig_LoaderInterface does not + // EngineInterface supports them but LoaderInterface does not $loader->getSourceContext((string) $name)->getCode(); - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { return false; } @@ -93,11 +92,11 @@ public function exists($name) /** * {@inheritdoc} * - * It also supports \Twig_Template as name parameter. + * It also supports Template as name parameter. */ public function supports($name) { - if ($name instanceof \Twig_Template) { + if ($name instanceof Template) { return true; } @@ -109,22 +108,22 @@ public function supports($name) /** * Loads the given template. * - * @param string|TemplateReferenceInterface|\Twig_Template $name A template name or an instance of - * TemplateReferenceInterface or \Twig_Template + * @param string|TemplateReferenceInterface|Template $name A template name or an instance of + * TemplateReferenceInterface or Template * - * @return \Twig_Template A \Twig_Template instance + * @return Template * * @throws \InvalidArgumentException if the template does not exist */ protected function load($name) { - if ($name instanceof \Twig_Template) { + if ($name instanceof Template) { return $name; } try { return $this->environment->loadTemplate((string) $name); - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } } diff --git a/src/Symfony/Bridge/Twig/composer.json b/src/Symfony/Bridge/Twig/composer.json index 38949fad20792..a7f1e23747536 100644 --- a/src/Symfony/Bridge/Twig/composer.json +++ b/src/Symfony/Bridge/Twig/composer.json @@ -17,7 +17,7 @@ ], "require": { "php": ">=5.5.9", - "twig/twig": "~1.28|~2.0" + "twig/twig": "~1.34|~2.4" }, "require-dev": { "fig/link-util": "^1.0", diff --git a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md index d25f4547d3123..b760d28997611 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md +++ b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md @@ -7,7 +7,7 @@ CHANGELOG * Not defining the `type` option of the `framework.workflows.*` configuration entries is deprecated. The default value will be `state_machine` in Symfony 4.0. * Deprecated the `CompilerDebugDumpPass` class - * [BC BREAK] Removed the "framework.trusted_proxies" configuration option and the corresponding "kernel.trusted_proxies" parameter + * Deprecated the "framework.trusted_proxies" configuration option and the corresponding "kernel.trusted_proxies" parameter * Added a new new version strategy option called json_manifest_path that allows you to use the `JsonManifestVersionStrategy`. * Added `Symfony\Bundle\FrameworkBundle\Controller\AbstractController`. It provides diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ClassCacheCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ClassCacheCacheWarmer.php index 1240f14c5b749..381f12d82bd65 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ClassCacheCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ClassCacheCacheWarmer.php @@ -27,7 +27,7 @@ class ClassCacheCacheWarmer implements CacheWarmerInterface public function __construct(array $declaredClasses = null) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { @trigger_error('The '.__CLASS__.' class is deprecated since version 3.3 and will be removed in 4.0.', E_USER_DEPRECATED); } diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TranslationsCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TranslationsCacheWarmer.php index 223f0216ba9ad..33f94650449fb 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TranslationsCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TranslationsCacheWarmer.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface; use Symfony\Component\Translation\TranslatorInterface; @@ -22,11 +23,24 @@ */ class TranslationsCacheWarmer implements CacheWarmerInterface { + private $container; private $translator; - public function __construct(TranslatorInterface $translator) + /** + * TranslationsCacheWarmer constructor. + * + * @param ContainerInterface|TranslatorInterface $container + */ + public function __construct($container) { - $this->translator = $translator; + // As this cache warmer is optional, dependencies should be lazy-loaded, that's why a container should be injected. + if ($container instanceof ContainerInterface) { + $this->container = $container; + } elseif ($container instanceof TranslatorInterface) { + $this->translator = $container; + } else { + throw new \InvalidArgumentException(sprintf('%s only accepts instance of Symfony\Component\DependencyInjection\ContainerInterface or Symfony\Component\Translation\TranslatorInterface as first argument.', __CLASS__)); + } } /** @@ -34,6 +48,10 @@ public function __construct(TranslatorInterface $translator) */ public function warmUp($cacheDir) { + if (null === $this->translator) { + $this->translator = $this->container->get('translator'); + } + if ($this->translator instanceof WarmableInterface) { $this->translator->warmUp($cacheDir); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php index 268a7818979cb..206b01e4f056e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/Descriptor.php @@ -307,15 +307,4 @@ protected function sortServiceIds(array $serviceIds) return $serviceIds; } - - protected function formatClosure(\Closure $closure) - { - $r = new \ReflectionFunction($closure); - - if (preg_match('#^/\*\* @closure-proxy ([^: ]++)::([^: ]++) \*/$#', $r->getDocComment(), $m)) { - return sprintf('%s::%s', $m[1], $m[2]); - } - - return 'closure'; - } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php index d49c57adfec2e..6755369c06252 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php @@ -370,7 +370,7 @@ private function getCallableData($callable, array $options = array()) } if ($callable instanceof \Closure) { - $data['type'] = $this->formatClosure($callable); + $data['type'] = 'closure'; return $data; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php index 59e382d3a9cad..81c6c4a69a2f6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php @@ -349,8 +349,7 @@ protected function describeCallable($callable, array $options = array()) } if ($callable instanceof \Closure) { - $formatted = $this->formatClosure($callable); - $string .= "\n- Type: `$formatted`"; + $string .= "\n- Type: `closure`"; return $this->write($string."\n"); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php index 64c38cdff759f..861f3c21c4dd5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php @@ -14,7 +14,6 @@ use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -343,9 +342,6 @@ protected function describeContainerDefinition(Definition $definition, array $op $argumentsInformation[] = sprintf('Service(%s)', (string) $argument); } elseif ($argument instanceof IteratorArgument) { $argumentsInformation[] = sprintf('Iterator (%d element(s))', count($argument->getValues())); - } elseif ($argument instanceof ClosureProxyArgument) { - list($reference, $method) = $argument->getValues(); - $argumentsInformation[] = sprintf('ClosureProxy(Service(%s)::%s())', $reference, $method); } elseif ($argument instanceof Definition) { $argumentsInformation[] = 'Inlined Service'; } else { @@ -478,13 +474,7 @@ private function formatCallable($callable) } if ($callable instanceof \Closure) { - $formatted = $this->formatClosure($callable); - - if ('closure' === $formatted) { - return '\Closure()'; - } - - return $formatted.'()'; + return '\Closure()'; } if (method_exists($callable, '__invoke')) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php index c1e586cf927f5..5baa8de11c730 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\Console\Descriptor; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -444,11 +443,6 @@ private function getArgumentNodes(array $arguments, \DOMDocument $dom) foreach ($this->getArgumentNodes($argument->getValues(), $dom) as $childArgumentXML) { $argumentXML->appendChild($childArgumentXML); } - } elseif ($argument instanceof ClosureProxyArgument) { - list($reference, $method) = $argument->getValues(); - $argumentXML->setAttribute('type', 'closure-proxy'); - $argumentXML->setAttribute('id', (string) $reference); - $argumentXML->setAttribute('method', $method); } elseif ($argument instanceof Definition) { $argumentXML->appendChild($dom->importNode($this->getContainerDefinitionDocument($argument, null, false, true)->childNodes->item(0), true)); } elseif (is_array($argument)) { @@ -599,7 +593,7 @@ private function getCallableDocument($callable) } if ($callable instanceof \Closure) { - $callableXML->setAttribute('type', $this->formatClosure($callable)); + $callableXML->setAttribute('type', 'closure'); return $dom; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php index 1055b00e3b1b2..6d0cee247da77 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php @@ -25,6 +25,7 @@ use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Templating\EngineInterface; +use Twig\Environment; /** * Provides common features needed in controllers. @@ -59,7 +60,7 @@ public static function getSubscribedServices() 'session' => '?'.SessionInterface::class, 'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class, 'templating' => '?'.EngineInterface::class, - 'twig' => '?'.\Twig_Environment::class, + 'twig' => '?'.Environment::class, 'doctrine' => '?'.ManagerRegistry::class, 'form.factory' => '?'.FormFactoryInterface::class, 'security.token_storage' => '?'.TokenStorageInterface::class, diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php index 3d1908bf9bc92..05e8a00a7925a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php @@ -11,9 +11,12 @@ namespace Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler; +use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface; use Symfony\Component\Cache\Adapter\TraceableAdapter; +use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; /** @@ -34,17 +37,30 @@ public function process(ContainerBuilder $container) $collectorDefinition = $container->getDefinition('data_collector.cache'); foreach ($container->findTaggedServiceIds('cache.pool') as $id => $attributes) { - if ($container->getDefinition($id)->isAbstract()) { + $definition = $container->getDefinition($id); + if ($definition->isAbstract()) { continue; } - $container->register($id.'.recorder', TraceableAdapter::class) - ->setDecoratedService($id) - ->addArgument(new Reference($id.'.recorder.inner')) - ->setPublic(false); + $recorder = new Definition(is_subclass_of($definition->getClass(), TagAwareAdapterInterface::class) ? TraceableTagAwareAdapter::class : TraceableAdapter::class); + $recorder->setTags($definition->getTags()); + $recorder->setPublic($definition->isPublic()); + $recorder->setArguments(array(new Reference($innerId = $id.'.recorder_inner'))); + + $definition->setTags(array()); + $definition->setPublic(false); + + if ($types = $definition->getAutowiringTypes(false)) { + $recorder->setAutowiringTypes($types); + $definition->setAutowiringTypes(array()); + } + + $container->setDefinition($innerId, $definition); + $container->setDefinition($id, $recorder); // Tell the collector to add the new instance $collectorDefinition->addMethodCall('addInstance', array($id, new Reference($id))); + $collectorDefinition->setPublic(false); } } } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index 87d722b91e4d6..611bfad97db82 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -65,10 +65,38 @@ public function getConfigTreeBuilder() ->info("Set true to enable support for the '_method' request parameter to determine the intended HTTP method on POST requests. Note: When using the HttpCache, you need to call the method in your front controller instead") ->defaultTrue() ->end() - ->arrayNode('trusted_proxies') // @deprecated in version 3.3, to be removed in 4.0 + ->arrayNode('trusted_proxies') ->beforeNormalization() - ->always() - ->thenInvalid('The "framework.trusted_proxies" configuration key has been removed in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead.') + ->ifTrue(function ($v) { + @trigger_error('The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead.', E_USER_DEPRECATED); + + return !is_array($v) && null !== $v; + }) + ->then(function ($v) { return is_bool($v) ? array() : preg_split('/\s*,\s*/', $v); }) + ->end() + ->prototype('scalar') + ->validate() + ->ifTrue(function ($v) { + if (empty($v)) { + return false; + } + + if (false !== strpos($v, '/')) { + if ('0.0.0.0/0' === $v) { + return false; + } + + list($v, $mask) = explode('/', $v, 2); + + if (strcmp($mask, (int) $mask) || $mask < 1 || $mask > (false !== strpos($v, ':') ? 128 : 32)) { + return true; + } + } + + return !filter_var($v, FILTER_VALIDATE_IP); + }) + ->thenInvalid('Invalid proxy IP "%s"') + ->end() ->end() ->end() ->scalarNode('ide')->defaultNull()->end() diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index e72a02d24480e..b607cdd2bf563 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -96,7 +96,7 @@ public function load(array $configs, ContainerBuilder $container) $loader->load('web.xml'); $loader->load('services.xml'); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $definition = $container->getDefinition('kernel.class_cache.cache_warmer'); $definition->addTag('kernel.cache_warmer'); // Ignore deprecation for PHP versions below 7.0 @@ -146,6 +146,9 @@ public function load(array $configs, ContainerBuilder $container) $container->setParameter('kernel.http_method_override', $config['http_method_override']); $container->setParameter('kernel.trusted_hosts', $config['trusted_hosts']); + if ($config['trusted_proxies']) { + $container->setParameter('kernel.trusted_proxies', $config['trusted_proxies']); + } $container->setParameter('kernel.default_locale', $config['default_locale']); if (!$container->hasParameter('debug.file_link_format')) { @@ -289,7 +292,7 @@ public function load(array $configs, ContainerBuilder $container) $container->registerForAutoconfiguration(ObjectInitializerInterface::class) ->addTag('validator.initializer'); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\\Component\\Config\\ConfigCache', 'Symfony\\Component\\Config\\FileLocator', @@ -674,7 +677,7 @@ private function registerRouterConfiguration(array $config, ContainerBuilder $co $container->setParameter('request_listener.http_port', $config['http_port']); $container->setParameter('request_listener.https_port', $config['https_port']); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\\Component\\Routing\\Generator\\UrlGenerator', 'Symfony\\Component\\Routing\\RequestContext', @@ -725,7 +728,7 @@ private function registerSessionConfiguration(array $config, ContainerBuilder $c $container->setParameter('session.save_path', $config['save_path']); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\\Component\\HttpKernel\\EventListener\\SessionListener', 'Symfony\\Component\\HttpFoundation\\Session\\Storage\\NativeSessionStorage', @@ -810,7 +813,7 @@ private function registerTemplatingConfiguration(array $config, ContainerBuilder $container->setDefinition('templating.loader', $loaderCache); } - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\\Bundle\\FrameworkBundle\\Templating\\GlobalVariables', 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateReference', @@ -850,7 +853,7 @@ private function registerTemplatingConfiguration(array $config, ContainerBuilder $container->setAlias('debug.templating.engine.php', 'templating.engine.php'); } - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\\Component\\Templating\\Storage\\FileStorage', 'Symfony\\Bundle\\FrameworkBundle\\Templating\\PhpEngine', @@ -1191,7 +1194,7 @@ private function registerAnnotationsConfiguration(array $config, ContainerBuilde $definition = $container->findDefinition('annotations.cache_warmer'); $definition->addTag('kernel.cache_warmer'); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\Component\Cache\Adapter\PhpArrayAdapter', 'Symfony\Component\Cache\DoctrineProvider', @@ -1448,7 +1451,7 @@ private function registerCacheConfiguration(array $config, ContainerBuilder $con } } - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\Component\Cache\Adapter\ApcuAdapter', 'Symfony\Component\Cache\Adapter\FilesystemAdapter', diff --git a/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php b/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php new file mode 100644 index 0000000000000..b083bb7ba8723 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\EventListener; + +use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Guarantees that the _controller key is parsed into its final format. + * + * @author Ryan Weaver + */ +class ResolveControllerNameSubscriber implements EventSubscriberInterface +{ + private $parser; + + public function __construct(ControllerNameParser $parser) + { + $this->parser = $parser; + } + + public function onKernelRequest(GetResponseEvent $event) + { + $controller = $event->getRequest()->attributes->get('_controller'); + if ($controller && false === strpos($controller, '::') && 2 === substr_count($controller, ':')) { + // controller in the a:b:c notation then + $event->getRequest()->attributes->set('_controller', $this->parser->parse($controller)); + } + } + + public static function getSubscribedEvents() + { + return array( + KernelEvents::REQUEST => array('onKernelRequest', 24), + ); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php index 1844f9b4a4391..99ab06b337772 100644 --- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php @@ -115,7 +115,7 @@ public function build(ContainerBuilder $container) $container->addCompilerPass(new UnusedTagsPass(), PassConfig::TYPE_AFTER_REMOVING); $container->addCompilerPass(new ContainerBuilderDebugDumpPass(), PassConfig::TYPE_BEFORE_REMOVING, -255); $this->addCompilerPassIfExists($container, ConfigCachePass::class); - $container->addCompilerPass(new CacheCollectorPass()); + $container->addCompilerPass(new CacheCollectorPass(), PassConfig::TYPE_BEFORE_REMOVING); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache_debug.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache_debug.xml index 9356d66769c1e..1b9b4077c0dd8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache_debug.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache_debug.xml @@ -7,8 +7,8 @@ - - + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml index d7e4803f5cf5d..8990f7c6cddc7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml @@ -26,7 +26,6 @@ - false diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml index ab1f9223a5b89..5f98febda6304 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml @@ -123,7 +123,7 @@ - + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml index 0203bf048bc2f..1eed0e92f6c21 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml @@ -70,5 +70,10 @@ + + + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php index a0cac9a908b24..6d32a37fd0ec9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php @@ -72,8 +72,8 @@ private function getContainer() ; $loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php index db533c09742ba..cd15b8c5e82fc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php @@ -76,8 +76,8 @@ private function getContainer() ; $loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php index 0c0363c482bab..9eb2e874d63d5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Console\Descriptor; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; @@ -119,7 +118,6 @@ public static function getContainerDefinitions() new Reference('definition_1'), new Reference('definition_2'), ))) - ->addArgument(new ClosureProxyArgument('definition1', 'get')) ->setFactory(array('Full\\Qualified\\FactoryClass', 'get')), 'definition_2' => $definition2 ->setPublic(false) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php index 2bd18aa441451..3feabfd12e273 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php @@ -317,7 +317,7 @@ public function testdenyAccessUnlessGranted() public function testRenderViewTwig() { - $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->once())->method('render')->willReturn('bar'); $container = new Container(); @@ -331,7 +331,7 @@ public function testRenderViewTwig() public function testRenderTwig() { - $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->once())->method('render')->willReturn('bar'); $container = new Container(); @@ -345,7 +345,7 @@ public function testRenderTwig() public function testStreamTwig() { - $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $container = new Container(); $container->set('twig', $twig); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php index 04e6447ee93ea..6afb5e3203f28 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php @@ -22,7 +22,7 @@ class TemplateControllerTest extends TestCase { public function testTwig() { - $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->once())->method('render')->willReturn('bar'); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CacheCollectorPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CacheCollectorPassTest.php new file mode 100644 index 0000000000000..6a9438ecbd7c8 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CacheCollectorPassTest.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler; + +use PHPUnit\Framework\TestCase; +use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CacheCollectorPass; +use Symfony\Component\Cache\Adapter\FilesystemAdapter; +use Symfony\Component\Cache\Adapter\TagAwareAdapter; +use Symfony\Component\Cache\Adapter\TraceableAdapter; +use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter; +use Symfony\Component\Cache\DataCollector\CacheDataCollector; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +class CacheCollectorPassTest extends TestCase +{ + public function testProcess() + { + $container = new ContainerBuilder(); + $container + ->register('fs', FilesystemAdapter::class) + ->addTag('cache.pool'); + $container + ->register('tagged_fs', TagAwareAdapter::class) + ->addArgument(new Reference('fs')) + ->addTag('cache.pool'); + + $collector = $container->register('data_collector.cache', CacheDataCollector::class); + (new CacheCollectorPass())->process($container); + + $this->assertEquals(array( + array('addInstance', array('fs', new Reference('fs'))), + array('addInstance', array('tagged_fs', new Reference('tagged_fs'))), + ), $collector->getMethodCalls()); + + $this->assertSame(TraceableAdapter::class, $container->findDefinition('fs')->getClass()); + $this->assertSame(TraceableTagAwareAdapter::class, $container->getDefinition('tagged_fs')->getClass()); + $this->assertFalse($collector->isPublic(), 'The "data_collector.cache" should be private after processing'); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php index 353e959c68ebf..0d2578db040af 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php @@ -43,6 +43,103 @@ public function testDoNoDuplicateDefaultFormResources() $this->assertEquals(array('FrameworkBundle:Form'), $config['templating']['form']['resources']); } + /** + * @group legacy + * @expectedDeprecation The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead. + */ + public function testTrustedProxiesSetToNullIsDeprecated() + { + $processor = new Processor(); + $configuration = new Configuration(true); + $processor->processConfiguration($configuration, array(array('trusted_proxies' => null))); + } + + /** + * @group legacy + * @expectedDeprecation The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead. + */ + public function testTrustedProxiesSetToEmptyArrayIsDeprecated() + { + $processor = new Processor(); + $configuration = new Configuration(true); + $processor->processConfiguration($configuration, array(array('trusted_proxies' => array()))); + } + + /** + * @group legacy + * @expectedDeprecation The "framework.trusted_proxies" configuration key has been deprecated in Symfony 3.3. Use the Request::setTrustedProxies() method in your front controller instead. + */ + public function testTrustedProxiesSetToNonEmptyArrayIsInvalid() + { + $processor = new Processor(); + $configuration = new Configuration(true); + $processor->processConfiguration($configuration, array(array('trusted_proxies' => array('127.0.0.1')))); + } + + /** + * @group legacy + * @dataProvider getTestValidTrustedProxiesData + */ + public function testValidTrustedProxies($trustedProxies, $processedProxies) + { + $processor = new Processor(); + $configuration = new Configuration(true); + $config = $processor->processConfiguration($configuration, array(array( + 'secret' => 's3cr3t', + 'trusted_proxies' => $trustedProxies, + ))); + + $this->assertEquals($processedProxies, $config['trusted_proxies']); + } + + public function getTestValidTrustedProxiesData() + { + return array( + array(array('127.0.0.1'), array('127.0.0.1')), + array(array('::1'), array('::1')), + array(array('127.0.0.1', '::1'), array('127.0.0.1', '::1')), + array(null, array()), + array(false, array()), + array(array(), array()), + array(array('10.0.0.0/8'), array('10.0.0.0/8')), + array(array('::ffff:0:0/96'), array('::ffff:0:0/96')), + array(array('0.0.0.0/0'), array('0.0.0.0/0')), + ); + } + + /** + * @group legacy + * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException + */ + public function testInvalidTypeTrustedProxies() + { + $processor = new Processor(); + $configuration = new Configuration(true); + $processor->processConfiguration($configuration, array( + array( + 'secret' => 's3cr3t', + 'trusted_proxies' => 'Not an IP address', + ), + )); + } + + /** + * @group legacy + * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException + */ + public function testInvalidValueTrustedProxies() + { + $processor = new Processor(); + $configuration = new Configuration(true); + + $processor->processConfiguration($configuration, array( + array( + 'secret' => 's3cr3t', + 'trusted_proxies' => array('Not an IP address'), + ), + )); + } + public function testAssetsCanBeEnabled() { $processor = new Processor(); @@ -124,6 +221,7 @@ protected static function getBundleDefaultConfig() { return array( 'http_method_override' => true, + 'trusted_proxies' => array(), 'ide' => null, 'default_locale' => 'en', 'csrf_protection' => array( diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php new file mode 100644 index 0000000000000..e5cc6d28a4e9d --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\EventListener; + +use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; +use Symfony\Bundle\FrameworkBundle\EventListener\ResolveControllerNameSubscriber; +use Symfony\Bundle\FrameworkBundle\Tests\TestCase; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +class ResolveControllerNameSubscriberTest extends TestCase +{ + public function testReplacesControllerAttribute() + { + $parser = $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); + $parser->expects($this->any()) + ->method('parse') + ->with('AppBundle:Starting:format') + ->willReturn('App\\Final\\Format::methodName'); + $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + + $request = new Request(); + $request->attributes->set('_controller', 'AppBundle:Starting:format'); + + $subscriber = new ResolveControllerNameSubscriber($parser); + $subscriber->onKernelRequest(new GetResponseEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST)); + $this->assertEquals('App\\Final\\Format::methodName', $request->attributes->get('_controller')); + } + + public function testSkipsOtherControllerFormats() + { + $parser = $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); + $parser->expects($this->never()) + ->method('parse'); + $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); + + $request = new Request(); + $request->attributes->set('_controller', 'Other:format'); + + $subscriber = new ResolveControllerNameSubscriber($parser); + $subscriber->onKernelRequest(new GetResponseEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST)); + $this->assertEquals('Other:format', $request->attributes->get('_controller')); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.json b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.json index dd3f81f1768e4..e2ab628937760 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.json +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.json @@ -60,13 +60,6 @@ "type": "service", "id": "definition_2" } - ], - [ - { - "type": "service", - "id": "definition1" - }, - "get" ] ], "file": null, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.xml index 91b292da50248..b016ae382a908 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_arguments.xml @@ -22,7 +22,6 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.json b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.json index 0590d3f76a611..5074d4fba6170 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.json +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.json @@ -58,13 +58,6 @@ "type": "service", "id": "definition_2" } - ], - [ - { - "type": "service", - "id": "definition1" - }, - "get" ] ], "file": null, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.txt b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.txt index 0bb95302f8315..989f96ee1369f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.txt +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.txt @@ -1,23 +1,22 @@ - ---------------- ------------------------------------------- -  Option   Value  - ---------------- ------------------------------------------- - Service ID - - Class Full\Qualified\Class1 - Tags - - Public yes - Synthetic no - Lazy yes - Shared yes - Abstract yes - Autowired no - Autoconfigured no - Factory Class Full\Qualified\FactoryClass - Factory Method get - Arguments Service(definition2)  - %parameter%  - Inlined Service  - Array (3 element(s))  - Iterator (2 element(s))  - ClosureProxy(Service(definition1)::get()) - ---------------- ------------------------------------------- + ---------------- ----------------------------- +  Option   Value  + ---------------- ----------------------------- + Service ID - + Class Full\Qualified\Class1 + Tags - + Public yes + Synthetic no + Lazy yes + Shared yes + Abstract yes + Autowired no + Autoconfigured no + Factory Class Full\Qualified\FactoryClass + Factory Method get + Arguments Service(definition2)  + %parameter%  + Inlined Service  + Array (3 element(s))  + Iterator (2 element(s)) + ---------------- ----------------------------- diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.xml index 6d3cb8eea40be..732f99f7839a1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_arguments_1.xml @@ -20,5 +20,4 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Controller/SubRequestServiceResolutionController.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Controller/SubRequestServiceResolutionController.php new file mode 100644 index 0000000000000..ae17f605a40f1 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Controller/SubRequestServiceResolutionController.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\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller; + +use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\ContainerAwareInterface; +use Symfony\Component\DependencyInjection\ContainerAwareTrait; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelInterface; + +class SubRequestServiceResolutionController implements ContainerAwareInterface +{ + use ContainerAwareTrait; + + public function indexAction() + { + $request = $this->container->get('request_stack')->getCurrentRequest(); + $path['_forwarded'] = $request->attributes; + $path['_controller'] = 'TestBundle:SubRequestServiceResolution:fragment'; + $subRequest = $request->duplicate(array(), null, $path); + + return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); + } + + public function fragmentAction(LoggerInterface $logger) + { + return new Response('---'); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SubRequestsTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SubRequestsTest.php index 2aaeb220f7189..1a87ff928a6e4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SubRequestsTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SubRequestsTest.php @@ -20,4 +20,12 @@ public function testStateAfterSubRequest() $this->assertEquals('--fr/json--en/html--fr/json--http://localhost/subrequest/fragment/en', $client->getResponse()->getContent()); } + + public function testSubRequestControllerServicesAreResolved() + { + $client = $this->createClient(array('test_case' => 'ControllerServiceResolution', 'root_config' => 'config.yml')); + $client->request('GET', 'https://localhost/subrequest'); + + $this->assertEquals('---', $client->getResponse()->getContent()); + } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/bundles.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/bundles.php new file mode 100644 index 0000000000000..a73987bcc986a --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/bundles.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\TestBundle; +use Symfony\Bundle\FrameworkBundle\FrameworkBundle; + +return array( + new FrameworkBundle(), + new TestBundle(), +); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/config.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/config.yml new file mode 100644 index 0000000000000..d196ce950921a --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/config.yml @@ -0,0 +1,10 @@ +imports: + - { resource: ../config/default.yml } + +services: + Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\SubRequestServiceResolutionController: + public: true + tags: [controller.service_arguments] + + logger: { class: Psr\Log\NullLogger } + Psr\Log\LoggerInterface: '@logger' diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/routing.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/routing.yml new file mode 100644 index 0000000000000..ffd9471525a6c --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/ControllerServiceResolution/routing.yml @@ -0,0 +1,4 @@ +sub_request_page: + path: /subrequest + defaults: + _controller: 'TestBundle:SubRequestServiceResolution:index' diff --git a/src/Symfony/Bundle/FrameworkBundle/Translation/PhpExtractor.php b/src/Symfony/Bundle/FrameworkBundle/Translation/PhpExtractor.php index 97c94fdd14bf9..70658f67232d3 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Translation/PhpExtractor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Translation/PhpExtractor.php @@ -85,7 +85,7 @@ public function extract($resource, MessageCatalogue $catalog) foreach ($files as $file) { $this->parseTokens(token_get_all(file_get_contents($file)), $catalog); - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098 gc_mem_caches(); } diff --git a/src/Symfony/Bundle/FrameworkBundle/composer.json b/src/Symfony/Bundle/FrameworkBundle/composer.json index 70b922c1fcc1f..6db169024f67e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/composer.json +++ b/src/Symfony/Bundle/FrameworkBundle/composer.json @@ -20,9 +20,9 @@ "ext-xml": "*", "symfony/cache": "~3.3", "symfony/class-loader": "~3.2", - "symfony/dependency-injection": "~3.3-beta2", + "symfony/dependency-injection": "~3.3", "symfony/config": "~3.3", - "symfony/event-dispatcher": "~3.3", + "symfony/event-dispatcher": "^3.3.1", "symfony/http-foundation": "~3.3", "symfony/http-kernel": "~3.3", "symfony/polyfill-mbstring": "~1.0", @@ -49,14 +49,14 @@ "symfony/serializer": "~3.3", "symfony/translation": "~3.2", "symfony/templating": "~2.8|~3.0", - "symfony/validator": "~3.3-rc2", + "symfony/validator": "~3.3", "symfony/workflow": "~3.3", "symfony/yaml": "~3.2", "symfony/property-info": "~3.3", "symfony/web-link": "~3.3", "doctrine/annotations": "~1.0", "phpdocumentor/reflection-docblock": "^3.0", - "twig/twig": "~1.26|~2.0", + "twig/twig": "~1.34|~2.4", "sensio/framework-extra-bundle": "^3.0.2" }, "conflict": { @@ -69,7 +69,7 @@ "symfony/property-info": "<3.3", "symfony/serializer": "<3.3", "symfony/translation": "<3.2", - "symfony/validator": "<3.3-rc2", + "symfony/validator": "<3.3", "symfony/workflow": "<3.3" }, "suggest": { diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 4191506f1ece3..5fd31ec4fdab6 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -113,7 +113,7 @@ public function load(array $configs, ContainerBuilder $container) $container->registerForAutoconfiguration(VoterInterface::class) ->addTag('security.voter'); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { // add some required classes for compilation $this->addClassesToCompile(array( 'Symfony\Component\Security\Http\Firewall', @@ -204,7 +204,7 @@ private function createAuthorization($config, ContainerBuilder $container) return; } - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Symfony\\Component\\Security\\Http\\AccessMap', )); diff --git a/src/Symfony/Bundle/SecurityBundle/composer.json b/src/Symfony/Bundle/SecurityBundle/composer.json index df6049b059964..d0cd5fc6c953d 100644 --- a/src/Symfony/Bundle/SecurityBundle/composer.json +++ b/src/Symfony/Bundle/SecurityBundle/composer.json @@ -18,7 +18,7 @@ "require": { "php": ">=5.5.9", "symfony/security": "~3.3", - "symfony/dependency-injection": "~3.3-beta2", + "symfony/dependency-injection": "~3.3", "symfony/http-kernel": "~3.3", "symfony/polyfill-php70": "~1.0" }, @@ -41,7 +41,7 @@ "symfony/yaml": "~2.8|~3.0", "symfony/expression-language": "~2.8|~3.0", "doctrine/doctrine-bundle": "~1.4", - "twig/twig": "~1.28|~2.0" + "twig/twig": "~1.34|~2.4" }, "conflict": { "symfony/var-dumper": "<3.3" diff --git a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php index 22184833f0eae..fa666dccf8d76 100644 --- a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php +++ b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php @@ -17,6 +17,8 @@ use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinderInterface; use Symfony\Component\Templating\TemplateReference; +use Twig\Environment; +use Twig\Error\Error; /** * Generates the Twig cache for all templates. @@ -77,7 +79,7 @@ public function warmUp($cacheDir) try { $twig->loadTemplate($template); - } catch (\Twig_Error $e) { + } catch (Error $e) { // problem during compilation, give up } } @@ -99,7 +101,7 @@ public function isOptional() public static function getSubscribedServices() { return array( - 'twig' => \Twig_Environment::class, + 'twig' => Environment::class, ); } diff --git a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php index aefb5c7296b97..9a60a92e85375 100644 --- a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php +++ b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php @@ -11,7 +11,10 @@ namespace Symfony\Bundle\TwigBundle\CacheWarmer; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; +use Twig\Environment; +use Twig\Error\Error; /** * Generates the Twig cache for all templates. @@ -20,12 +23,27 @@ */ class TemplateCacheWarmer implements CacheWarmerInterface { + private $container; private $twig; private $iterator; - public function __construct(\Twig_Environment $twig, \Traversable $iterator) + /** + * TemplateCacheWarmer constructor. + * + * @param ContainerInterface|Environment $container + * @param \Traversable $iterator + */ + public function __construct($container, \Traversable $iterator) { - $this->twig = $twig; + // As this cache warmer is optional, dependencies should be lazy-loaded, that's why a container should be injected. + if ($container instanceof ContainerInterface) { + $this->container = $container; + } elseif ($container instanceof Environment) { + $this->twig = $container; + } else { + throw new \InvalidArgumentException(sprintf('%s only accepts instance of Symfony\Component\DependencyInjection\ContainerInterface or Environment as first argument.', __CLASS__)); + } + $this->iterator = $iterator; } @@ -34,10 +52,14 @@ public function __construct(\Twig_Environment $twig, \Traversable $iterator) */ public function warmUp($cacheDir) { + if (null === $this->twig) { + $this->twig = $this->container->get('twig'); + } + foreach ($this->iterator as $template) { try { $this->twig->loadTemplate($template); - } catch (\Twig_Error $e) { + } catch (Error $e) { // problem during compilation, give up // might be a syntax error or a non-Twig template } diff --git a/src/Symfony/Bundle/TwigBundle/ContainerAwareRuntimeLoader.php b/src/Symfony/Bundle/TwigBundle/ContainerAwareRuntimeLoader.php index e2988f3aae5e0..377649602dc42 100644 --- a/src/Symfony/Bundle/TwigBundle/ContainerAwareRuntimeLoader.php +++ b/src/Symfony/Bundle/TwigBundle/ContainerAwareRuntimeLoader.php @@ -11,19 +11,20 @@ namespace Symfony\Bundle\TwigBundle; -@trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use the Twig_ContainerRuntimeLoader class instead.', ContainerAwareRuntimeLoader::class), E_USER_DEPRECATED); +@trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use the Twig\RuntimeLoader\ContainerRuntimeLoader class instead.', ContainerAwareRuntimeLoader::class), E_USER_DEPRECATED); use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +use Twig\RuntimeLoader\RuntimeLoaderInterface; /** * Loads Twig extension runtimes via the service container. * * @author Fabien Potencier * - * @deprecated since version 3.3, will be removed in 4.0. Use \Twig_ContainerRuntimeLoader instead. + * @deprecated since version 3.3, will be removed in 4.0. Use \Twig\Loader\ContainerRuntimeLoader instead. */ -class ContainerAwareRuntimeLoader implements \Twig_RuntimeLoaderInterface +class ContainerAwareRuntimeLoader implements RuntimeLoaderInterface { private $container; private $mapping; diff --git a/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php b/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php index f9e86c4daa21d..d648d63dd5688 100644 --- a/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php +++ b/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php @@ -15,6 +15,9 @@ use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Loader\ExistsLoaderInterface; /** * ExceptionController renders error or exception pages for a given @@ -32,7 +35,7 @@ class ExceptionController */ protected $debug; - public function __construct(\Twig_Environment $twig, $debug) + public function __construct(Environment $twig, $debug) { $this->twig = $twig; $this->debug = $debug; @@ -129,7 +132,7 @@ protected function templateExists($template) $template = (string) $template; $loader = $this->twig->getLoader(); - if ($loader instanceof \Twig_ExistsLoaderInterface || method_exists($loader, 'exists')) { + if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { return $loader->exists($template); } @@ -137,7 +140,7 @@ protected function templateExists($template) $loader->getSourceContext($template)->getCode(); return true; - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { } return false; diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php index c0661d9e70b67..4880d2534d8f5 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php @@ -123,7 +123,7 @@ private function addTwigOptions(ArrayNodeDefinition $rootNode) ->variableNode('autoescape')->defaultValue('name')->end() ->scalarNode('autoescape_service')->defaultNull()->end() ->scalarNode('autoescape_service_method')->defaultNull()->end() - ->scalarNode('base_template_class')->example('Twig_Template')->cannotBeEmpty()->end() + ->scalarNode('base_template_class')->example('Twig\Template')->cannotBeEmpty()->end() ->scalarNode('cache')->defaultValue('%kernel.cache_dir%/twig')->end() ->scalarNode('charset')->defaultValue('%kernel.charset%')->end() ->booleanNode('debug')->defaultValue('%kernel.debug%')->end() diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configurator/EnvironmentConfigurator.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configurator/EnvironmentConfigurator.php index bf37559b9920c..1612b6eb5fec2 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configurator/EnvironmentConfigurator.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configurator/EnvironmentConfigurator.php @@ -11,6 +11,11 @@ namespace Symfony\Bundle\TwigBundle\DependencyInjection\Configurator; +use Twig\Environment; + +// BC/FC with namespaced Twig +class_exists('Twig\Environment'); + /** * Twig environment configurator. * @@ -35,14 +40,14 @@ public function __construct($dateFormat, $intervalFormat, $timezone, $decimals, $this->thousandsSeparator = $thousandsSeparator; } - public function configure(\Twig_Environment $environment) + public function configure(Environment $environment) { - $environment->getExtension('Twig_Extension_Core')->setDateFormat($this->dateFormat, $this->intervalFormat); + $environment->getExtension('Twig\Extension\CoreExtension')->setDateFormat($this->dateFormat, $this->intervalFormat); if (null !== $this->timezone) { - $environment->getExtension('Twig_Extension_Core')->setTimezone($this->timezone); + $environment->getExtension('Twig\Extension\CoreExtension')->setTimezone($this->timezone); } - $environment->getExtension('Twig_Extension_Core')->setNumberFormat($this->decimals, $this->decimalPoint, $this->thousandsSeparator); + $environment->getExtension('Twig\Extension\CoreExtension')->setNumberFormat($this->decimals, $this->decimalPoint, $this->thousandsSeparator); } } diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php index 916ca53c74da5..e8c10786c457d 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php @@ -18,6 +18,8 @@ use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\WebLink\HttpHeaderSerializer; +use Twig\Extension\ExtensionInterface; +use Twig\Loader\LoaderInterface; /** * TwigExtension. @@ -144,12 +146,12 @@ public function load(array $configs, ContainerBuilder $container) $container->getDefinition('twig')->replaceArgument(1, $config); - $container->registerForAutoconfiguration(\Twig_ExtensionInterface::class) - ->addTag('twig.extension'); - $container->registerForAutoconfiguration(\Twig_LoaderInterface::class) - ->addTag('twig.loader'); + $container->registerForAutoconfiguration(\Twig_ExtensionInterface::class)->addTag('twig.extension'); + $container->registerForAutoconfiguration(\Twig_LoaderInterface::class)->addTag('twig.loader'); + $container->registerForAutoconfiguration(ExtensionInterface::class)->addTag('twig.extension'); + $container->registerForAutoconfiguration(LoaderInterface::class)->addTag('twig.loader'); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->addClassesToCompile(array( 'Twig_Environment', 'Twig_Extension', diff --git a/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php b/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php index 0a9ac7a3ca19a..2b9b2502ae83d 100644 --- a/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php +++ b/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php @@ -14,6 +14,8 @@ use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\Templating\TemplateNameParserInterface; use Symfony\Component\Templating\TemplateReferenceInterface; +use Twig\Error\LoaderError; +use Twig\Loader\FilesystemLoader as BaseFilesystemLoader; /** * FilesystemLoader extends the default Twig filesystem loader @@ -21,7 +23,7 @@ * * @author Fabien Potencier */ -class FilesystemLoader extends \Twig_Loader_Filesystem +class FilesystemLoader extends BaseFilesystemLoader { protected $locator; protected $parser; @@ -59,11 +61,11 @@ public function exists($name) * Otherwise the template is located using the locator from the twig library. * * @param string|TemplateReferenceInterface $template The template - * @param bool $throw When true, a \Twig_Error_Loader exception will be thrown if a template could not be found + * @param bool $throw When true, a LoaderError exception will be thrown if a template could not be found * * @return string The path to the template file * - * @throws \Twig_Error_Loader if the template could not be found + * @throws LoaderError if the template could not be found */ protected function findTemplate($template, $throw = true) { @@ -77,7 +79,7 @@ protected function findTemplate($template, $throw = true) $previous = null; try { $file = parent::findTemplate($logicalName); - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { $twigLoaderException = $e; // for BC diff --git a/src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml b/src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml index ca427869a9330..310ab14063a0b 100644 --- a/src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml +++ b/src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml @@ -7,7 +7,7 @@ - + @@ -20,6 +20,7 @@ + %kernel.environment% @@ -44,24 +45,24 @@ - + - + %kernel.project_dir% - + - + @@ -108,7 +109,7 @@ - + @@ -145,7 +146,7 @@ - + diff --git a/src/Symfony/Bundle/TwigBundle/Resources/views/base_js.html.twig b/src/Symfony/Bundle/TwigBundle/Resources/views/base_js.html.twig index d85d2e0ea32ae..4ce8013c4463a 100644 --- a/src/Symfony/Bundle/TwigBundle/Resources/views/base_js.html.twig +++ b/src/Symfony/Bundle/TwigBundle/Resources/views/base_js.html.twig @@ -478,6 +478,11 @@ addEventListener(toggles[i], 'click', function(e) { e.preventDefault(); + if ('' !== window.getSelection().toString()) { + /* Don't do anything on text selection */ + return; + } + var toggle = e.target || e.srcElement; /* needed because when the toggle contains HTML contents, user can click */ @@ -507,6 +512,14 @@ var altContent = toggle.getAttribute('data-toggle-alt-content'); toggle.innerHTML = currentContent !== altContent ? altContent : originalContent; }); + + /* Prevents from disallowing clicks on links inside toggles */ + var toggleLinks = document.querySelectorAll('.sf-toggle a'); + for (var i = 0; i < toggleLinks.length; i++) { + addEventListener(toggleLinks[i], 'click', function(e) { + e.stopPropagation(); + }); + } } } }; diff --git a/src/Symfony/Bundle/TwigBundle/Resources/views/exception.css.twig b/src/Symfony/Bundle/TwigBundle/Resources/views/exception.css.twig index 4f553f20df5e9..cb455274eecf9 100644 --- a/src/Symfony/Bundle/TwigBundle/Resources/views/exception.css.twig +++ b/src/Symfony/Bundle/TwigBundle/Resources/views/exception.css.twig @@ -89,14 +89,13 @@ header .container { display: flex; justify-content: space-between; } .exception-illustration { flex-basis: 111px; flex-shrink: 0; height: 66px; margin-left: 15px; opacity: .7; } .trace + .trace { margin-top: 30px; } -.trace-head { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .trace-head .trace-class { color: #222; font-size: 18px; font-weight: bold; line-height: 1.3; margin: 0; position: relative; } .trace-head .trace-namespace { color: #999; display: block; font-size: 13px; } .trace-head .icon { position: absolute; right: 0; top: 0; } .trace-head .icon svg { height: 24px; width: 24px; } .trace-message { font-size: 14px; font-weight: normal; margin: .5em 0 0; } - +.trace-details { table-layout: fixed; } .trace-line { position: relative; padding-left: 36px; } .trace-line.sf-toggle:hover { background: #F5F5F5; } .trace-line a { color: #222; } @@ -109,12 +108,12 @@ header .container { display: flex; justify-content: space-between; } .trace-method { color: #B0413E; color: #222; font-weight: bold; color: #B0413E; } .trace-arguments { color: #222; color: #999; font-weight: normal; color: #795da3; color: #777; padding-left: 2px; } -.trace-code { background: #FFF; font-size: 12px; margin: 10px 0 2px; padding: 10px; } -.trace-code ol { margin: 0; } -.trace-code li { color: #969896; margin: 0; padding-left: 10px; } -.trace-code li + li { margin-top: 10px; } -.trace-code li.selected { background: #F8EEC7; padding: 3px 0 3px 10px; } -.trace-code li code { color: #222; } +.trace-code { background: #FFF; font-size: 12px; margin: 10px 0 2px; padding: 10px; overflow-x: auto; } +.trace-code ol { margin: 0; float: left; } +.trace-code li { color: #969896; margin: 0; padding-left: 10px; float: left; width: 100%; } +.trace-code li + li { margin-top: 5px; } +.trace-code li.selected { background: #F8EEC7; padding: 3px 0 3px 10px; margin-top: 2px; } +.trace-code li code { color: #222; white-space: nowrap; } .trace-as-text .stacktrace { line-height: 1.8; margin: 0 0 15px; white-space: pre-wrap; } diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php index 920a833c6bf03..cf5722727beb7 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php @@ -15,13 +15,15 @@ use Symfony\Bundle\TwigBundle\Controller\ExceptionController; use Symfony\Component\Debug\Exception\FlattenException; use Symfony\Component\HttpFoundation\Request; +use Twig\Environment; +use Twig\Loader\ArrayLoader; class ExceptionControllerTest extends TestCase { public function testShowActionCanBeForcedToShowErrorPage() { - $twig = new \Twig_Environment( - new \Twig_Loader_Array(array( + $twig = new Environment( + new ArrayLoader(array( '@Twig/Exception/error404.html.twig' => 'ok', )) ); @@ -40,8 +42,8 @@ public function testShowActionCanBeForcedToShowErrorPage() public function testFallbackToHtmlIfNoTemplateForRequestedFormat() { - $twig = new \Twig_Environment( - new \Twig_Loader_Array(array( + $twig = new Environment( + new ArrayLoader(array( '@Twig/Exception/error.html.twig' => 'html', )) ); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/ExtensionPassTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/ExtensionPassTest.php index 94c00c2cabcef..6ce77c54970c0 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/ExtensionPassTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/Compiler/ExtensionPassTest.php @@ -30,7 +30,7 @@ public function testProcessDoesNotDropExistingFileLoaderMethodCalls() $container->register('twig.extension.debug.stopwatch'); $container->register('twig.extension.expression'); - $nativeTwigLoader = new Definition('\Twig_Loader_Filesystem'); + $nativeTwigLoader = new Definition('\Twig\Loader\FilesystemLoader'); $nativeTwigLoader->addMethodCall('addPath', array()); $container->setDefinition('twig.loader.native_filesystem', $nativeTwigLoader); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php index 4d78b772655e8..25c3886379cf7 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php @@ -32,7 +32,7 @@ public function testLoadEmptyConfiguration() $container->loadFromExtension('twig', array()); $this->compileContainer($container); - $this->assertEquals('Twig_Environment', $container->getDefinition('twig')->getClass(), '->load() loads the twig.xml file'); + $this->assertEquals('Twig\Environment', $container->getDefinition('twig')->getClass(), '->load() loads the twig.xml file'); $this->assertContains('form_div_layout.html.twig', $container->getParameter('twig.form.resources'), '->load() includes default template for form resources'); @@ -53,7 +53,7 @@ public function testLoadFullConfiguration($format) $this->loadFromFile($container, 'full', $format); $this->compileContainer($container); - $this->assertEquals('Twig_Environment', $container->getDefinition('twig')->getClass(), '->load() loads the twig.xml file'); + $this->assertEquals('Twig\Environment', $container->getDefinition('twig')->getClass(), '->load() loads the twig.xml file'); // Form resources $resources = $container->getParameter('twig.form.resources'); diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php index a7abdecb87896..b9294e35b3c46 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Loader/FilesystemLoaderTest.php @@ -52,7 +52,7 @@ public function testExists() } /** - * @expectedException \Twig_Error_Loader + * @expectedException \Twig\Error\LoaderError */ public function testTwigErrorIfLocatorThrowsInvalid() { @@ -76,7 +76,7 @@ public function testTwigErrorIfLocatorThrowsInvalid() } /** - * @expectedException \Twig_Error_Loader + * @expectedException \Twig\Error\LoaderError */ public function testTwigErrorIfLocatorReturnsFalse() { @@ -100,7 +100,7 @@ public function testTwigErrorIfLocatorReturnsFalse() } /** - * @expectedException \Twig_Error_Loader + * @expectedException \Twig\Error\LoaderError * @expectedExceptionMessageRegExp /Unable to find template "name\.format\.engine" \(looked into: .*Tests.Loader.\.\..DependencyInjection.Fixtures.Resources.views\)/ */ public function testTwigErrorIfTemplateDoesNotExist() diff --git a/src/Symfony/Bundle/TwigBundle/TwigEngine.php b/src/Symfony/Bundle/TwigBundle/TwigEngine.php index 503c55f6af7cb..cc13c280b10ff 100644 --- a/src/Symfony/Bundle/TwigBundle/TwigEngine.php +++ b/src/Symfony/Bundle/TwigBundle/TwigEngine.php @@ -17,6 +17,8 @@ use Symfony\Component\Templating\TemplateNameParserInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Config\FileLocatorInterface; +use Twig\Environment; +use Twig\Error\Error; /** * This engine renders Twig templates. @@ -27,14 +29,7 @@ class TwigEngine extends BaseEngine implements EngineInterface { protected $locator; - /** - * Constructor. - * - * @param \Twig_Environment $environment A \Twig_Environment instance - * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance - * @param FileLocatorInterface $locator A FileLocatorInterface instance - */ - public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator) + public function __construct(Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator) { parent::__construct($environment, $parser); @@ -48,7 +43,7 @@ public function render($name, array $parameters = array()) { try { return parent::render($name, $parameters); - } catch (\Twig_Error $e) { + } catch (Error $e) { if ($name instanceof TemplateReference && !method_exists($e, 'setSourceContext')) { try { // try to get the real name of the template where the error occurred @@ -66,7 +61,7 @@ public function render($name, array $parameters = array()) /** * {@inheritdoc} * - * @throws \Twig_Error if something went wrong like a thrown exception while rendering the template + * @throws Error if something went wrong like a thrown exception while rendering the template */ public function renderResponse($view, array $parameters = array(), Response $response = null) { diff --git a/src/Symfony/Bundle/TwigBundle/composer.json b/src/Symfony/Bundle/TwigBundle/composer.json index 454349b0f0890..11f071b19c32b 100644 --- a/src/Symfony/Bundle/TwigBundle/composer.json +++ b/src/Symfony/Bundle/TwigBundle/composer.json @@ -21,7 +21,7 @@ "symfony/twig-bridge": "^3.3", "symfony/http-foundation": "~2.8|~3.0", "symfony/http-kernel": "^3.3", - "twig/twig": "^1.32|^2.2" + "twig/twig": "~1.34|~2.4" }, "require-dev": { "symfony/asset": "~2.8|~3.0", diff --git a/src/Symfony/Bundle/WebProfilerBundle/Controller/ExceptionController.php b/src/Symfony/Bundle/WebProfilerBundle/Controller/ExceptionController.php index fd0dbecd2bbec..3f9d873e1d40f 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Controller/ExceptionController.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Controller/ExceptionController.php @@ -15,6 +15,9 @@ use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpFoundation\Response; +use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Loader\ExistsLoaderInterface; /** * ExceptionController. @@ -27,7 +30,7 @@ class ExceptionController protected $debug; protected $profiler; - public function __construct(Profiler $profiler = null, \Twig_Environment $twig, $debug) + public function __construct(Profiler $profiler = null, Environment $twig, $debug) { $this->profiler = $profiler; $this->twig = $twig; @@ -112,7 +115,7 @@ protected function getTemplate() protected function templateExists($template) { $loader = $this->twig->getLoader(); - if ($loader instanceof \Twig_ExistsLoaderInterface) { + if ($loader instanceof ExistsLoaderInterface) { return $loader->exists($template); } @@ -120,7 +123,7 @@ protected function templateExists($template) $loader->getSource($template); return true; - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { } return false; diff --git a/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php b/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php index 33092d36466cd..37f47df6a6e40 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php @@ -20,6 +20,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Profiler\Profiler; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Twig\Environment; /** * ProfilerController. @@ -42,13 +43,13 @@ class ProfilerController * * @param UrlGeneratorInterface $generator The URL Generator * @param Profiler $profiler The profiler - * @param \Twig_Environment $twig The twig environment + * @param Environment $twig The twig environment * @param array $templates The templates * @param string $toolbarPosition The toolbar position (top, bottom, normal, or null -- use the configuration) * @param ContentSecurityPolicyHandler $cspHandler The Content-Security-Policy handler * @param string $baseDir The project root directory */ - public function __construct(UrlGeneratorInterface $generator, Profiler $profiler = null, \Twig_Environment $twig, array $templates, $toolbarPosition = 'bottom', ContentSecurityPolicyHandler $cspHandler = null, $baseDir = null) + public function __construct(UrlGeneratorInterface $generator, Profiler $profiler = null, Environment $twig, array $templates, $toolbarPosition = 'bottom', ContentSecurityPolicyHandler $cspHandler = null, $baseDir = null) { $this->generator = $generator; $this->profiler = $profiler; diff --git a/src/Symfony/Bundle/WebProfilerBundle/Controller/RouterController.php b/src/Symfony/Bundle/WebProfilerBundle/Controller/RouterController.php index 3ea170d7ea3ea..80946ac428c02 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Controller/RouterController.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Controller/RouterController.php @@ -20,6 +20,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Profiler\Profiler; use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector; +use Twig\Environment; /** * RouterController. @@ -33,7 +34,7 @@ class RouterController private $matcher; private $routes; - public function __construct(Profiler $profiler = null, \Twig_Environment $twig, UrlMatcherInterface $matcher = null, RouteCollection $routes = null) + public function __construct(Profiler $profiler = null, Environment $twig, UrlMatcherInterface $matcher = null, RouteCollection $routes = null) { $this->profiler = $profiler; $this->twig = $twig; diff --git a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php index a40c42c88e73a..6ffdbc7ad0764 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php +++ b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php @@ -19,6 +19,7 @@ use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Twig\Environment; /** * WebDebugToolbarListener injects the Web Debug Toolbar. @@ -43,7 +44,7 @@ class WebDebugToolbarListener implements EventSubscriberInterface protected $excludedAjaxPaths; private $cspHandler; - public function __construct(\Twig_Environment $twig, $interceptRedirects = false, $mode = self::ENABLED, $position = 'bottom', UrlGeneratorInterface $urlGenerator = null, $excludedAjaxPaths = '^/bundles|^/_wdt', ContentSecurityPolicyHandler $cspHandler = null) + public function __construct(Environment $twig, $interceptRedirects = false, $mode = self::ENABLED, $position = 'bottom', UrlGeneratorInterface $urlGenerator = null, $excludedAjaxPaths = '^/bundles|^/_wdt', ContentSecurityPolicyHandler $cspHandler = null) { $this->twig = $twig; $this->urlGenerator = $urlGenerator; diff --git a/src/Symfony/Bundle/WebProfilerBundle/Profiler/TemplateManager.php b/src/Symfony/Bundle/WebProfilerBundle/Profiler/TemplateManager.php index 999604b7effb1..29fe3a31c85d6 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Profiler/TemplateManager.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Profiler/TemplateManager.php @@ -14,6 +14,11 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Profiler\Profiler; use Symfony\Component\HttpKernel\Profiler\Profile; +use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Loader\ExistsLoaderInterface; +use Twig\Loader\SourceContextLoaderInterface; +use Twig\Template; /** * Profiler Templates Manager. @@ -27,14 +32,7 @@ class TemplateManager protected $templates; protected $profiler; - /** - * Constructor. - * - * @param Profiler $profiler - * @param \Twig_Environment $twig - * @param array $templates - */ - public function __construct(Profiler $profiler, \Twig_Environment $twig, array $templates) + public function __construct(Profiler $profiler, Environment $twig, array $templates) { $this->profiler = $profiler; $this->twig = $twig; @@ -67,7 +65,7 @@ public function getName(Profile $profile, $panel) * * @param Profile $profile * - * @return \Twig_Template[] + * @return Template[] * * @deprecated not used anymore internally */ @@ -124,19 +122,19 @@ public function getNames(Profile $profile) protected function templateExists($template) { $loader = $this->twig->getLoader(); - if ($loader instanceof \Twig_ExistsLoaderInterface) { + if ($loader instanceof ExistsLoaderInterface) { return $loader->exists($template); } try { - if ($loader instanceof \Twig_SourceContextLoaderInterface) { + if ($loader instanceof SourceContextLoaderInterface) { $loader->getSourceContext($template); } else { $loader->getSource($template); } return true; - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { } return false; diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/form.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/form.html.twig index 2f8b83049d158..02b77319ac249 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/form.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/form.html.twig @@ -525,7 +525,7 @@ Model Format {% if data.default_data.model is defined %} - {{ profiler_dump(data.default_data.model) }} + {{ profiler_dump(data.default_data.seek('model')) }} {% else %} same as normalized format {% endif %} @@ -533,13 +533,13 @@ Normalized Format - {{ profiler_dump(data.default_data.norm) }} + {{ profiler_dump(data.default_data.seek('norm')) }} View Format {% if data.default_data.view is defined %} - {{ profiler_dump(data.default_data.view) }} + {{ profiler_dump(data.default_data.seek('view')) }} {% else %} same as normalized format {% endif %} @@ -571,7 +571,7 @@ View Format {% if data.submitted_data.view is defined %} - {{ profiler_dump(data.submitted_data.view) }} + {{ profiler_dump(data.submitted_data.seek('view')) }} {% else %} same as normalized format {% endif %} @@ -579,13 +579,13 @@ Normalized Format - {{ profiler_dump(data.submitted_data.norm) }} + {{ profiler_dump(data.submitted_data.seek('norm')) }} Model Format {% if data.submitted_data.model is defined %} - {{ profiler_dump(data.submitted_data.model) }} + {{ profiler_dump(data.submitted_data.seek('model')) }} {% else %} same as normalized format {% endif %} @@ -630,7 +630,7 @@ {% if resolved_option_value == option_value %} same as passed value {% else %} - {{ profiler_dump(data.resolved_options[option]) }} + {{ profiler_dump(data.resolved_options.seek(option)) }} {% endif %} 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 79da38a230f01..b5f08f869168d 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 @@ -478,6 +478,11 @@ addEventListener(toggles[i], 'click', function(e) { e.preventDefault(); + if ('' !== window.getSelection().toString()) { + /* Don't do anything on text selection */ + return; + } + var toggle = e.target || e.srcElement; /* needed because when the toggle contains HTML contents, user can click */ @@ -508,6 +513,14 @@ toggle.innerHTML = currentContent !== altContent ? altContent : originalContent; }); } + + /* Prevents from disallowing clicks on links inside toggles */ + var toggleLinks = document.querySelectorAll('.sf-toggle a'); + for (var i = 0; i < toggleLinks.length; i++) { + addEventListener(toggleLinks[i], 'click', function(e) { + e.stopPropagation(); + }); + } } }; })(); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php index 060313f875cef..839c9f21d9fe9 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php @@ -25,7 +25,7 @@ class ProfilerControllerTest extends TestCase public function testEmptyToken($token) { $urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock(); - $twig = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $profiler = $this ->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler') ->disableOriginalConstructor() @@ -51,7 +51,7 @@ public function getEmptyTokenCases() */ public function testReturns404onTokenNotFound($withCsp) { - $twig = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $profiler = $this ->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler') ->disableOriginalConstructor() @@ -81,7 +81,7 @@ public function testReturns404onTokenNotFound($withCsp) */ public function testSearchResult($withCsp) { - $twig = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $profiler = $this ->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler') ->disableOriginalConstructor() diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php index 28dbb976d3fbb..af0573e5a362d 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/DependencyInjection/WebProfilerExtensionTest.php @@ -52,9 +52,9 @@ protected function setUp() $this->container = new ContainerBuilder(); $this->container->register('router', $this->getMockClass('Symfony\\Component\\Routing\\RouterInterface')); - $this->container->register('twig', 'Twig_Environment'); - $this->container->register('twig_loader', 'Twig_Loader_Array')->addArgument(array()); - $this->container->register('twig', 'Twig_Environment')->addArgument(new Reference('twig_loader')); + $this->container->register('twig', 'Twig\Environment'); + $this->container->register('twig_loader', 'Twig\Loader\ArrayLoader')->addArgument(array()); + $this->container->register('twig', 'Twig\Environment')->addArgument(new Reference('twig_loader')); $this->container->setParameter('kernel.bundles', array()); $this->container->setParameter('kernel.cache_dir', __DIR__); $this->container->setParameter('kernel.debug', false); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php index dff05c182c037..5e5e7a21fe76b 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/EventListener/WebDebugToolbarListenerTest.php @@ -291,7 +291,7 @@ protected function getRequestMock($isXmlHttpRequest = false, $requestFormat = 'h protected function getTwigMock($render = 'WDT') { - $templating = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock(); + $templating = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $templating->expects($this->any()) ->method('render') ->will($this->returnValue($render)); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php index 4ac2c7de5f0a2..7b8f9a8df51c0 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php @@ -13,6 +13,7 @@ use Symfony\Bundle\WebProfilerBundle\Tests\TestCase; use Symfony\Bundle\WebProfilerBundle\Profiler\TemplateManager; +use Twig\Environment; /** * Test for TemplateManager class. @@ -22,7 +23,7 @@ class TemplateManagerTest extends TestCase { /** - * @var \Twig_Environment + * @var Environment */ protected $twigEnvironment; @@ -46,7 +47,7 @@ protected function setUp() 'data_collector.foo' => array('foo', 'FooBundle:Collector:foo'), 'data_collector.bar' => array('bar', 'FooBundle:Collector:bar'), 'data_collector.baz' => array('baz', 'FooBundle:Collector:baz'), - ); + ); $this->templateManager = new TemplateManager($profiler, $twigEnvironment, $templates); } @@ -129,16 +130,16 @@ protected function mockProfile() protected function mockTwigEnvironment() { - $this->twigEnvironment = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock(); + $this->twigEnvironment = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $this->twigEnvironment->expects($this->any()) ->method('loadTemplate') ->will($this->returnValue('loadedTemplate')); - if (interface_exists('\Twig_SourceContextLoaderInterface')) { - $loader = $this->getMockBuilder('\Twig_SourceContextLoaderInterface')->getMock(); + if (interface_exists('Twig\Loader\SourceContextLoaderInterface')) { + $loader = $this->getMockBuilder('Twig\Loader\SourceContextLoaderInterface')->getMock(); } else { - $loader = $this->getMockBuilder('\Twig_LoaderInterface')->getMock(); + $loader = $this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(); } $this->twigEnvironment->expects($this->any())->method('getLoader')->will($this->returnValue($loader)); diff --git a/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php b/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php index 4662cbf56b82e..f552e5f206cfa 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php @@ -14,13 +14,17 @@ use Symfony\Component\HttpKernel\DataCollector\Util\ValueExporter; use Symfony\Component\VarDumper\Cloner\Data; use Symfony\Component\VarDumper\Dumper\HtmlDumper; +use Twig\Environment; +use Twig\Extension\ProfilerExtension; +use Twig\Profiler\Profile; +use Twig\TwigFunction; /** * Twig extension for the profiler. * * @author Fabien Potencier */ -class WebProfilerExtension extends \Twig_Extension_Profiler +class WebProfilerExtension extends ProfilerExtension { /** * @var ValueExporter @@ -48,12 +52,12 @@ public function __construct(HtmlDumper $dumper = null) $this->dumper->setOutput($this->output = fopen('php://memory', 'r+b')); } - public function enter(\Twig_Profiler_Profile $profile) + public function enter(Profile $profile) { ++$this->stackLevel; } - public function leave(\Twig_Profiler_Profile $profile) + public function leave(Profile $profile) { if (0 === --$this->stackLevel) { $this->dumper->setOutput($this->output = fopen('php://memory', 'r+b')); @@ -65,17 +69,17 @@ public function leave(\Twig_Profiler_Profile $profile) */ public function getFunctions() { - $profilerDump = function (\Twig_Environment $env, $value, $maxDepth = 0) { + $profilerDump = function (Environment $env, $value, $maxDepth = 0) { return $value instanceof Data ? $this->dumpData($env, $value, $maxDepth) : twig_escape_filter($env, $this->dumpValue($value)); }; return array( - new \Twig_SimpleFunction('profiler_dump', $profilerDump, array('is_safe' => array('html'), 'needs_environment' => true)), - new \Twig_SimpleFunction('profiler_dump_log', array($this, 'dumpLog'), array('is_safe' => array('html'), 'needs_environment' => true)), + new TwigFunction('profiler_dump', $profilerDump, array('is_safe' => array('html'), 'needs_environment' => true)), + new TwigFunction('profiler_dump_log', array($this, 'dumpLog'), array('is_safe' => array('html'), 'needs_environment' => true)), ); } - public function dumpData(\Twig_Environment $env, Data $data, $maxDepth = 0) + public function dumpData(Environment $env, Data $data, $maxDepth = 0) { $this->dumper->setCharset($env->getCharset()); $this->dumper->dump($data, null, array( @@ -89,7 +93,7 @@ public function dumpData(\Twig_Environment $env, Data $data, $maxDepth = 0) return str_replace("\n$1"', $message); diff --git a/src/Symfony/Bundle/WebProfilerBundle/composer.json b/src/Symfony/Bundle/WebProfilerBundle/composer.json index 276f8f68cc4ee..626ac4d307d51 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/composer.json +++ b/src/Symfony/Bundle/WebProfilerBundle/composer.json @@ -21,8 +21,8 @@ "symfony/polyfill-php70": "~1.0", "symfony/routing": "~2.8|~3.0", "symfony/twig-bridge": "~2.8|~3.0", - "twig/twig": "~1.28|~2.0", - "symfony/var-dumper": "~3.3" + "symfony/var-dumper": "~3.3", + "twig/twig": "~1.34|~2.4" }, "require-dev": { "symfony/config": "~2.8|~3.0", diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php index c761b9a2010bf..e4fa4c97b7ba9 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php @@ -266,6 +266,9 @@ private function generateItems($items, &$keys) try { foreach ($items as $id => $value) { + if (!isset($keys[$id])) { + $id = key($keys); + } $key = $keys[$id]; unset($keys[$id]); yield $key => $f($key, $value, true); diff --git a/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php b/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php index 5c8784e69cf44..3acf8bdb86c6a 100644 --- a/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php @@ -19,6 +19,18 @@ class MemcachedAdapter extends AbstractAdapter protected $maxIdLength = 250; + /** + * Constructor. + * + * Using a MemcachedAdapter with a TagAwareAdapter for storing tags is discouraged. + * Using a RedisAdapter is recommended instead. If you cannot do otherwise, be aware that: + * - the Memcached::OPT_BINARY_PROTOCOL must be enabled + * (that's the default when using MemcachedAdapter::createConnection()); + * - tags eviction by Memcached's LRU algorithm will break by-tags invalidation; + * your Memcached memory should be large enough to never trigger LRU. + * + * Using a MemcachedAdapter as a pure items store is fine. + */ public function __construct(\Memcached $client, $namespace = '', $defaultLifetime = 0) { $this->init($client, $namespace, $defaultLifetime); diff --git a/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php b/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php index 8ddfa27f3868f..ea102ddbf75fb 100644 --- a/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php @@ -65,7 +65,7 @@ function ($key, $value, $isHit) { public static function create($file, CacheItemPoolInterface $fallbackPool) { // Shared memory is available in PHP 7.0+ with OPCache enabled and in HHVM - if ((PHP_VERSION_ID >= 70000 && ini_get('opcache.enable')) || defined('HHVM_VERSION')) { + if ((\PHP_VERSION_ID >= 70000 && ini_get('opcache.enable')) || defined('HHVM_VERSION')) { if (!$fallbackPool instanceof AdapterInterface) { $fallbackPool = new ProxyAdapter($fallbackPool); } diff --git a/src/Symfony/Component/Cache/Adapter/TraceableAdapter.php b/src/Symfony/Component/Cache/Adapter/TraceableAdapter.php index d813c61ad9038..9959199f67ccc 100644 --- a/src/Symfony/Component/Cache/Adapter/TraceableAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/TraceableAdapter.php @@ -22,7 +22,7 @@ */ class TraceableAdapter implements AdapterInterface { - private $pool; + protected $pool; private $calls = array(); public function __construct(AdapterInterface $pool) @@ -107,7 +107,7 @@ public function saveDeferred(CacheItemInterface $item) */ public function getItems(array $keys = array()) { - $event = $this->start(__FUNCTION__, $keys); + $event = $this->start(__FUNCTION__); try { $result = $this->pool->getItems($keys); } finally { @@ -177,7 +177,7 @@ public function getCalls() } } - private function start($name) + protected function start($name) { $this->calls[] = $event = new TraceableAdapterEvent(); $event->name = $name; diff --git a/src/Symfony/Component/Cache/Adapter/TraceableTagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/TraceableTagAwareAdapter.php new file mode 100644 index 0000000000000..de68955d8e56d --- /dev/null +++ b/src/Symfony/Component/Cache/Adapter/TraceableTagAwareAdapter.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Adapter; + +/** + * @author Robin Chalas + */ +class TraceableTagAwareAdapter extends TraceableAdapter implements TagAwareAdapterInterface +{ + public function __construct(TagAwareAdapterInterface $pool) + { + parent::__construct($pool); + } + + /** + * {@inheritdoc} + */ + public function invalidateTags(array $tags) + { + $event = $this->start(__FUNCTION__); + try { + return $event->result = $this->pool->invalidateTags($tags); + } finally { + $event->end = microtime(true); + } + } +} diff --git a/src/Symfony/Component/Cache/Simple/AbstractCache.php b/src/Symfony/Component/Cache/Simple/AbstractCache.php index 4c44b9b323bb0..bbd35780fd5c4 100644 --- a/src/Symfony/Component/Cache/Simple/AbstractCache.php +++ b/src/Symfony/Component/Cache/Simple/AbstractCache.php @@ -162,6 +162,9 @@ private function generateValues($values, &$keys, $default) { try { foreach ($values as $id => $value) { + if (!isset($keys[$id])) { + $id = key($keys); + } $key = $keys[$id]; unset($keys[$id]); yield $key => $value; diff --git a/src/Symfony/Component/Cache/Simple/PhpArrayCache.php b/src/Symfony/Component/Cache/Simple/PhpArrayCache.php index 3c61f5e8f645e..c65b8fffaac41 100644 --- a/src/Symfony/Component/Cache/Simple/PhpArrayCache.php +++ b/src/Symfony/Component/Cache/Simple/PhpArrayCache.php @@ -48,7 +48,7 @@ public function __construct($file, CacheInterface $fallbackPool) public static function create($file, CacheInterface $fallbackPool) { // Shared memory is available in PHP 7.0+ with OPCache enabled and in HHVM - if ((PHP_VERSION_ID >= 70000 && ini_get('opcache.enable')) || defined('HHVM_VERSION')) { + if ((\PHP_VERSION_ID >= 70000 && ini_get('opcache.enable')) || defined('HHVM_VERSION')) { return new static($file, $fallbackPool); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TraceableTagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TraceableTagAwareAdapterTest.php new file mode 100644 index 0000000000000..9b50bfabe65b7 --- /dev/null +++ b/src/Symfony/Component/Cache/Tests/Adapter/TraceableTagAwareAdapterTest.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Tests\Adapter; + +use Symfony\Component\Cache\Adapter\FilesystemAdapter; +use Symfony\Component\Cache\Adapter\TagAwareAdapter; +use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter; + +/** + * @group time-sensitive + */ +class TraceableTagAwareAdapterTest extends TraceableAdapterTest +{ + public function testInvalidateTags() + { + $pool = new TraceableTagAwareAdapter(new TagAwareAdapter(new FilesystemAdapter())); + $pool->invalidateTags(array('foo')); + $calls = $pool->getCalls(); + $this->assertCount(1, $calls); + + $call = $calls[0]; + $this->assertSame('invalidateTags', $call->name); + $this->assertSame(0, $call->hits); + $this->assertSame(0, $call->misses); + $this->assertNotEmpty($call->start); + $this->assertNotEmpty($call->end); + } +} diff --git a/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php b/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php index 81d412bd66354..b3799ebcda24c 100644 --- a/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php +++ b/src/Symfony/Component/Cache/Tests/Simple/CacheTestCase.php @@ -15,6 +15,15 @@ abstract class CacheTestCase extends SimpleCacheTest { + public static function validKeys() + { + if (defined('HHVM_VERSION')) { + return parent::validKeys(); + } + + return array_merge(parent::validKeys(), array(array("a\0b"))); + } + public function testDefaultLifeTime() { if (isset($this->skippedTests[__FUNCTION__])) { diff --git a/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php b/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php index 2b0ae50f6a1ac..2d2c7db3d014f 100644 --- a/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php +++ b/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php @@ -126,6 +126,6 @@ public function clear() */ private function initialize() { - $this->values = @(include $this->file) ?: array(); + $this->values = file_exists($this->file) ? (include $this->file ?: array()) : array(); } } diff --git a/src/Symfony/Component/Cache/Traits/RedisTrait.php b/src/Symfony/Component/Cache/Traits/RedisTrait.php index 8877b0911a76b..f28da39346627 100644 --- a/src/Symfony/Component/Cache/Traits/RedisTrait.php +++ b/src/Symfony/Component/Cache/Traits/RedisTrait.php @@ -90,6 +90,11 @@ public static function createConnection($dsn, array $options = array()) $params['dbindex'] = $m[1]; $params['path'] = substr($params['path'], 0, -strlen($m[0])); } + if (isset($params['host'])) { + $scheme = 'tcp'; + } else { + $scheme = 'unix'; + } $params += array( 'host' => isset($params['host']) ? $params['host'] : $params['path'], 'port' => isset($params['host']) ? 6379 : null, @@ -120,7 +125,7 @@ public static function createConnection($dsn, array $options = array()) throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e, $dsn)); } } elseif (is_a($class, \Predis\Client::class, true)) { - $params['scheme'] = isset($params['host']) ? 'tcp' : 'unix'; + $params['scheme'] = $scheme; $params['database'] = $params['dbindex'] ?: null; $params['password'] = $auth; $redis = new $class((new Factory())->create($params)); diff --git a/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php b/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php index 0079e8a7981a7..2be210be8c430 100644 --- a/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php +++ b/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php @@ -11,7 +11,7 @@ namespace Symfony\Component\ClassLoader; -if (PHP_VERSION_ID >= 70000) { +if (\PHP_VERSION_ID >= 70000) { @trigger_error('The '.__NAMESPACE__.'\ClassCollectionLoader class is deprecated since version 3.3 and will be removed in 4.0.', E_USER_DEPRECATED); } @@ -262,7 +262,7 @@ public static function fixNamespaceDeclarations($source) $output .= self::compressCode($rawChunk); - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098 unset($tokens, $rawChunk); gc_mem_caches(); diff --git a/src/Symfony/Component/ClassLoader/ClassMapGenerator.php b/src/Symfony/Component/ClassLoader/ClassMapGenerator.php index 69df0e1f41672..12f06ac4b9a85 100644 --- a/src/Symfony/Component/ClassLoader/ClassMapGenerator.php +++ b/src/Symfony/Component/ClassLoader/ClassMapGenerator.php @@ -68,7 +68,7 @@ public static function createMap($dir) $classes = self::findClasses($path); - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098 gc_mem_caches(); } diff --git a/src/Symfony/Component/Config/Loader/FileLoader.php b/src/Symfony/Component/Config/Loader/FileLoader.php index d3fe0eacfc0d9..02aa811fc5497 100644 --- a/src/Symfony/Component/Config/Loader/FileLoader.php +++ b/src/Symfony/Component/Config/Loader/FileLoader.php @@ -83,13 +83,18 @@ public function getLocator() */ public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null) { - if (is_string($resource) && false !== strpbrk($resource, '*?{[')) { + if (is_string($resource) && strlen($resource) !== $i = strcspn($resource, '*?{[')) { $ret = array(); - foreach ($this->glob($resource, false, $_, true) as $path => $info) { - $ret[] = $this->doImport($path, $type, $ignoreErrors, $sourceResource); + $isSubpath = 0 !== $i && false !== strpos(substr($resource, 0, $i), '/'); + foreach ($this->glob($resource, false, $_, $ignoreErrors || !$isSubpath) as $path => $info) { + if (null !== $res = $this->doImport($path, $type, $ignoreErrors, $sourceResource)) { + $ret[] = $res; + } + $isSubpath = true; } - if ($ret) { - return count($ret) > 1 ? $ret : $ret[0]; + + if ($isSubpath) { + return isset($ret[1]) ? $ret : (isset($ret[0]) ? $ret[0] : null); } } @@ -104,7 +109,7 @@ protected function glob($pattern, $recursive, &$resource = null, $ignoreErrors = if (strlen($pattern) === $i = strcspn($pattern, '*?{[')) { $prefix = $pattern; $pattern = ''; - } elseif (0 === $i) { + } elseif (0 === $i || false === strpos(substr($pattern, 0, $i), '/')) { $prefix = '.'; $pattern = '/'.$pattern; } else { diff --git a/src/Symfony/Component/Config/Resource/ClassExistenceResource.php b/src/Symfony/Component/Config/Resource/ClassExistenceResource.php index 040cfc510eb9b..8a86a4209961b 100644 --- a/src/Symfony/Component/Config/Resource/ClassExistenceResource.php +++ b/src/Symfony/Component/Config/Resource/ClassExistenceResource.php @@ -21,25 +21,21 @@ */ class ClassExistenceResource implements SelfCheckingResourceInterface, \Serializable { - const EXISTS_OK = 1; - const EXISTS_KO = 0; - const EXISTS_KO_WITH_THROWING_AUTOLOADER = -1; - private $resource; - private $existsStatus; + private $exists; private static $autoloadLevel = 0; private static $existsCache = array(); /** - * @param string $resource The fully-qualified class name - * @param int|null $existsStatus One of the self::EXISTS_* const if the existency check has already been done + * @param string $resource The fully-qualified class name + * @param bool|null $exists Boolean when the existency check has already been done */ - public function __construct($resource, $existsStatus = null) + public function __construct($resource, $exists = null) { $this->resource = $resource; - if (null !== $existsStatus) { - $this->existsStatus = (int) $existsStatus; + if (null !== $exists) { + $this->exists = (bool) $exists; } } @@ -64,11 +60,13 @@ public function getResource() */ public function isFresh($timestamp) { + $loaded = class_exists($this->resource, false) || interface_exists($this->resource, false) || trait_exists($this->resource, false); + if (null !== $exists = &self::$existsCache[$this->resource]) { - $exists = $exists || class_exists($this->resource, false) || interface_exists($this->resource, false) || trait_exists($this->resource, false); - } elseif (self::EXISTS_KO_WITH_THROWING_AUTOLOADER === $this->existsStatus) { + $exists = $exists || $loaded; + } elseif (!$exists = $loaded) { if (!self::$autoloadLevel++) { - spl_autoload_register('Symfony\Component\Config\Resource\ClassExistenceResource::throwOnRequiredClass'); + spl_autoload_register(__CLASS__.'::throwOnRequiredClass'); } try { @@ -77,18 +75,16 @@ public function isFresh($timestamp) $exists = false; } finally { if (!--self::$autoloadLevel) { - spl_autoload_unregister('Symfony\Component\Config\Resource\ClassExistenceResource::throwOnRequiredClass'); + spl_autoload_unregister(__CLASS__.'::throwOnRequiredClass'); } } - } else { - $exists = class_exists($this->resource) || interface_exists($this->resource, false) || trait_exists($this->resource, false); } - if (null === $this->existsStatus) { - $this->existsStatus = $exists ? self::EXISTS_OK : self::EXISTS_KO; + if (null === $this->exists) { + $this->exists = $exists; } - return self::EXISTS_OK === $this->existsStatus xor !$exists; + return $this->exists xor !$exists; } /** @@ -96,11 +92,11 @@ public function isFresh($timestamp) */ public function serialize() { - if (null === $this->existsStatus) { + if (null === $this->exists) { $this->isFresh(0); } - return serialize(array($this->resource, $this->existsStatus)); + return serialize(array($this->resource, $this->exists)); } /** @@ -108,7 +104,7 @@ public function serialize() */ public function unserialize($serialized) { - list($this->resource, $this->existsStatus) = unserialize($serialized); + list($this->resource, $this->exists) = unserialize($serialized); } /** diff --git a/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php b/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php index 59b625525bff1..c6e283c74919b 100644 --- a/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php +++ b/src/Symfony/Component/Config/Tests/Loader/FileLoaderTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Loader; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\FileLoader; use Symfony\Component\Config\Loader\LoaderResolver; @@ -74,6 +75,21 @@ public function testImportWithGlobLikeResource() $this->assertSame('[foo]', $loader->import('[foo]')); } + + public function testImportWithNoGlobMatch() + { + $locatorMock = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock(); + $loader = new TestFileLoader($locatorMock); + + $this->assertNull($loader->import('./*.abc')); + } + + public function testImportWithSimpleGlob() + { + $loader = new TestFileLoader(new FileLocator(__DIR__)); + + $this->assertSame(__FILE__, strtr($loader->import('FileLoaderTest.*'), '/', DIRECTORY_SEPARATOR)); + } } class TestFileLoader extends FileLoader diff --git a/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php index f429a33626564..3daef17ee1300 100644 --- a/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/ClassExistenceResourceTest.php @@ -66,7 +66,7 @@ public function testExistsKo() $loadedClass = 123; - $res = new ClassExistenceResource('MissingFooClass', ClassExistenceResource::EXISTS_KO); + $res = new ClassExistenceResource('MissingFooClass', false); $this->assertSame(123, $loadedClass); } finally { @@ -76,7 +76,7 @@ public function testExistsKo() public function testConditionalClass() { - $res = new ClassExistenceResource(ConditionalClass::class, ClassExistenceResource::EXISTS_KO_WITH_THROWING_AUTOLOADER); + $res = new ClassExistenceResource(ConditionalClass::class, false); $this->assertFalse($res->isFresh(0)); } diff --git a/src/Symfony/Component/Config/Tests/Resource/ReflectionClassResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/ReflectionClassResourceTest.php index 8fd0adc592abd..4eca3d50e4a8b 100644 --- a/src/Symfony/Component/Config/Tests/Resource/ReflectionClassResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/ReflectionClassResourceTest.php @@ -124,10 +124,10 @@ public function provideHashedSignature() yield array(0, 8, '/** priv docblock */'); yield array(0, 9, 'private $priv = 123;'); yield array(1, 10, '/** pub docblock */'); - if (PHP_VERSION_ID >= 50600) { + if (\PHP_VERSION_ID >= 50600) { yield array(1, 11, 'public function pub(...$arg) {}'); } - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { yield array(1, 11, 'public function pub($arg = null): Foo {}'); } yield array(0, 11, "public function pub(\$arg = null) {\nreturn 123;\n}"); diff --git a/src/Symfony/Component/Console/Command/Command.php b/src/Symfony/Component/Console/Command/Command.php index 2359677515659..08a74c3b69a9a 100644 --- a/src/Symfony/Component/Console/Command/Command.php +++ b/src/Symfony/Component/Console/Command/Command.php @@ -286,7 +286,7 @@ public function setCode(callable $code) if ($code instanceof \Closure) { $r = new \ReflectionFunction($code); if (null === $r->getClosureThis()) { - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { // Bug in PHP5: https://bugs.php.net/bug.php?id=64761 // This means that we cannot bind static closures and therefore we must // ignore any errors here. There is no way to test if the closure is diff --git a/src/Symfony/Component/Console/Input/ArgvInput.php b/src/Symfony/Component/Console/Input/ArgvInput.php index 85cd779849b73..9264daab8709c 100644 --- a/src/Symfony/Component/Console/Input/ArgvInput.php +++ b/src/Symfony/Component/Console/Input/ArgvInput.php @@ -150,7 +150,7 @@ private function parseLongOption($token) if (0 === strlen($value = substr($name, $pos + 1))) { // if no value after "=" then substr() returns "" since php7 only, false before // see http://php.net/manual/fr/migration70.incompatible.php#119151 - if (PHP_VERSION_ID < 70000 && false === $value) { + if (\PHP_VERSION_ID < 70000 && false === $value) { $value = ''; } array_unshift($this->parsed, $value); diff --git a/src/Symfony/Component/Console/Tests/Command/CommandTest.php b/src/Symfony/Component/Console/Tests/Command/CommandTest.php index a8048aeaf813b..93b4721c393dd 100644 --- a/src/Symfony/Component/Console/Tests/Command/CommandTest.php +++ b/src/Symfony/Component/Console/Tests/Command/CommandTest.php @@ -392,7 +392,7 @@ public function testSetCodeWithStaticClosure() $tester = new CommandTester($command); $tester->execute(array()); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { // Cannot bind static closures in PHP 5 $this->assertEquals('interact called'.PHP_EOL.'not bound'.PHP_EOL, $tester->getDisplay()); } else { diff --git a/src/Symfony/Component/Console/composer.json b/src/Symfony/Component/Console/composer.json index 362d55d1af8e9..db76bf3b2c7a7 100644 --- a/src/Symfony/Component/Console/composer.json +++ b/src/Symfony/Component/Console/composer.json @@ -21,6 +21,7 @@ "symfony/debug": "~2.8|~3.0" }, "require-dev": { + "symfony/config": "~3.3", "symfony/http-kernel": "~2.8|~3.0", "symfony/event-dispatcher": "~2.8|~3.0", "symfony/dependency-injection": "~3.3", diff --git a/src/Symfony/Component/Debug/ExceptionHandler.php b/src/Symfony/Component/Debug/ExceptionHandler.php index 1fe60d9f31e69..5c399ef089e3b 100644 --- a/src/Symfony/Component/Debug/ExceptionHandler.php +++ b/src/Symfony/Component/Debug/ExceptionHandler.php @@ -316,7 +316,6 @@ public function getStylesheet(FlattenException $exception) .exception-illustration { flex-basis: 111px; flex-shrink: 0; height: 66px; margin-left: 15px; opacity: .7; } .trace + .trace { margin-top: 30px; } - .trace-head { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .trace-head .trace-class { color: #222; font-size: 18px; font-weight: bold; line-height: 1.3; margin: 0; position: relative; } .trace-message { font-size: 14px; font-weight: normal; margin: .5em 0 0; } diff --git a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php index 765e8d9b86bfd..f1e3fb7c611b5 100644 --- a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php +++ b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php @@ -61,7 +61,7 @@ public function testIdempotence() public function testUnsilencing() { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $this->markTestSkipped('PHP7 throws exceptions, unsilencing is not required anymore.'); } if (defined('HHVM_VERSION')) { @@ -109,7 +109,7 @@ class ChildTestingStacking extends TestingStacking { function foo($bar) {} } } catch (\ErrorException $exception) { // if an exception is thrown, the test passed $this->assertStringStartsWith(__FILE__, $exception->getFile()); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $this->assertRegExp('/^Runtime Notice: Declaration/', $exception->getMessage()); $this->assertEquals(E_STRICT, $exception->getSeverity()); } else { @@ -245,7 +245,7 @@ class_exists('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent', true public function testReservedForPhp7() { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $this->markTestSkipped('PHP7 already prevents using reserved names.'); } diff --git a/src/Symfony/Component/DependencyInjection/Argument/ClosureProxyArgument.php b/src/Symfony/Component/DependencyInjection/Argument/ClosureProxyArgument.php deleted file mode 100644 index 94ba13241a108..0000000000000 --- a/src/Symfony/Component/DependencyInjection/Argument/ClosureProxyArgument.php +++ /dev/null @@ -1,50 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\DependencyInjection\Argument; - -use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @author Nicolas Grekas - */ -class ClosureProxyArgument implements ArgumentInterface -{ - private $reference; - private $method; - - public function __construct($id, $method, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) - { - $this->reference = new Reference($id, $invalidBehavior); - $this->method = $method; - } - - /** - * {@inheritdoc} - */ - public function getValues() - { - return array($this->reference, $this->method); - } - - /** - * {@inheritdoc} - */ - public function setValues(array $values) - { - if (!$values[0] instanceof Reference) { - throw new InvalidArgumentException(sprintf('A ClosureProxyArgument must hold a Reference, "%s" given.', is_object($values[0]) ? get_class($values[0]) : gettype($values[0]))); - } - list($this->reference, $this->method) = $values; - } -} diff --git a/src/Symfony/Component/DependencyInjection/CHANGELOG.md b/src/Symfony/Component/DependencyInjection/CHANGELOG.md index b591c5958dae7..457e22413ea5f 100644 --- a/src/Symfony/Component/DependencyInjection/CHANGELOG.md +++ b/src/Symfony/Component/DependencyInjection/CHANGELOG.md @@ -20,7 +20,6 @@ CHANGELOG * added support for omitting the factory class name in a service definition if the definition class is set * deprecated case insensitivity of service identifiers * added "iterator" argument type for lazy iteration over a set of values and services - * added "closure-proxy" argument type for turning services' methods into lazy callables * added file-wide configurable defaults for service attributes "public", "tags", "autowire" and "autoconfigure" * made the "class" attribute optional, using the "id" as fallback diff --git a/src/Symfony/Component/DependencyInjection/ChildDefinition.php b/src/Symfony/Component/DependencyInjection/ChildDefinition.php index dd02f860677f8..5701caa474e57 100644 --- a/src/Symfony/Component/DependencyInjection/ChildDefinition.php +++ b/src/Symfony/Component/DependencyInjection/ChildDefinition.php @@ -62,7 +62,7 @@ public function setParent($parent) * If replaceArgument() has been used to replace an argument, this method * will return the replacement value. * - * @param int $index + * @param int|string $index * * @return mixed The argument value * @@ -74,13 +74,7 @@ public function getArgument($index) return $this->arguments['index_'.$index]; } - $lastIndex = count(array_filter(array_keys($this->arguments), 'is_int')) - 1; - - if ($index < 0 || $index > $lastIndex) { - throw new OutOfBoundsException(sprintf('The index "%d" is not in the range [0, %d].', $index, $lastIndex)); - } - - return $this->arguments[$index]; + return parent::getArgument($index); } /** @@ -91,8 +85,8 @@ public function getArgument($index) * certain conventions when you want to overwrite the arguments of the * parent definition, otherwise your arguments will only be appended. * - * @param int $index - * @param mixed $value + * @param int|string $index + * @param mixed $value * * @return self the current instance * @@ -105,7 +99,7 @@ public function replaceArgument($index, $value) } elseif (0 === strpos($index, '$')) { $this->arguments[$index] = $value; } else { - throw new InvalidArgumentException('$index must be an integer.'); + throw new InvalidArgumentException('The argument must be an existing index or the name of a constructor\'s parameter.'); } return $this; diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AutowireExceptionPass.php b/src/Symfony/Component/DependencyInjection/Compiler/AutowireExceptionPass.php index 2ee9427a15098..12be3d915fd10 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AutowireExceptionPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AutowireExceptionPass.php @@ -44,9 +44,27 @@ public function process(ContainerBuilder $container) $this->inlineServicePass = null; foreach ($exceptions as $exception) { - if ($container->hasDefinition($exception->getServiceId()) || in_array($exception->getServiceId(), $inlinedIds)) { + if ($this->doesServiceExistInTheContainer($exception->getServiceId(), $container, $inlinedIds)) { throw $exception; } } } + + private function doesServiceExistInTheContainer($serviceId, ContainerBuilder $container, array $inlinedIds) + { + if ($container->hasDefinition($serviceId)) { + return true; + } + + // was the service inlined? Of so, does its parent service exist? + if (isset($inlinedIds[$serviceId])) { + foreach ($inlinedIds[$serviceId] as $parentId) { + if ($this->doesServiceExistInTheContainer($parentId, $container, $inlinedIds)) { + return true; + } + } + } + + return false; + } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php index b79a656aa8eaf..8382d303859e1 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php @@ -114,7 +114,7 @@ protected function processValue($value, $isRoot = false) private function doProcessValue($value, $isRoot = false) { if ($value instanceof TypedReference) { - if ($ref = $this->getAutowiredReference($value)) { + if ($ref = $this->getAutowiredReference($value, $value->getRequiringClass() ? sprintf('for "%s" in "%s"', $value->getType(), $value->getRequiringClass()) : '')) { return $ref; } $this->container->log($this, $this->createTypeNotFoundMessage($value, 'it')); @@ -133,7 +133,13 @@ private function doProcessValue($value, $isRoot = false) $autowiredMethods = $this->getMethodsToAutowire($reflectionClass); $methodCalls = $value->getMethodCalls(); - if ($constructor = $this->getConstructor($value, false)) { + try { + $constructor = $this->getConstructor($value, false); + } catch (RuntimeException $e) { + throw new AutowiringFailedException($this->currentId, $e->getMessage(), 0, $e); + } + + if ($constructor) { array_unshift($methodCalls, array($constructor, $value->getArguments())); } @@ -242,7 +248,7 @@ private function autowireCalls(\ReflectionClass $reflectionClass, array $methodC * * @return array The autowired arguments * - * @throws RuntimeException + * @throws AutowiringFailedException */ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, array $arguments) { @@ -276,7 +282,7 @@ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, a continue; } - if (!$value = $this->getAutowiredReference($ref = new TypedReference($type, $type, !$parameter->isOptional() ? $class : ''))) { + if (!$value = $this->getAutowiredReference($ref = new TypedReference($type, $type, !$parameter->isOptional() ? $class : ''), 'for '.sprintf('argument "$%s" of method "%s()"', $parameter->name, $class.'::'.$method))) { $failureMessage = $this->createTypeNotFoundMessage($ref, sprintf('argument "$%s" of method "%s()"', $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method)); if ($parameter->isDefaultValueAvailable()) { @@ -310,7 +316,7 @@ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, a /** * @return TypedReference|null A reference to the service matching the given type, if any */ - private function getAutowiredReference(TypedReference $reference) + private function getAutowiredReference(TypedReference $reference, $deprecationMessage) { $this->lastFailure = null; $type = $reference->getType(); @@ -328,7 +334,14 @@ private function getAutowiredReference(TypedReference $reference) } if (isset($this->types[$type])) { - @trigger_error(sprintf('Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won\'t be supported in version 4.0. You should %s the "%s" service to "%s" instead.', isset($this->types[$this->types[$type]]) ? 'alias' : 'rename (or alias)', $this->types[$type], $type), E_USER_DEPRECATED); + $message = 'Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won\'t be supported in version 4.0.'; + if ($aliasSuggestion = $this->getAliasesSuggestionForType($type = $reference->getType(), $deprecationMessage)) { + $message .= ' '.$aliasSuggestion; + } else { + $message .= sprintf(' You should %s the "%s" service to "%s" instead.', isset($this->types[$this->types[$type]]) ? 'alias' : 'rename (or alias)', $this->types[$type], $type); + } + + @trigger_error($message, E_USER_DEPRECATED); return new TypedReference($this->types[$type], $type); } @@ -375,7 +388,7 @@ private function populateAvailableType($id, Definition $definition) unset($this->ambiguousServiceTypes[$type]); } - if ($definition->isDeprecated() || !$reflectionClass = $this->container->getReflectionClass($definition->getClass(), true)) { + if ($definition->isDeprecated() || !$reflectionClass = $this->container->getReflectionClass($definition->getClass())) { return; } @@ -431,7 +444,7 @@ private function set($type, $id) */ private function createAutowiredDefinition($type) { - if (!($typeHint = $this->container->getReflectionClass($type, true)) || !$typeHint->isInstantiable()) { + if (!($typeHint = $this->container->getReflectionClass($type)) || !$typeHint->isInstantiable()) { return; } @@ -465,7 +478,7 @@ private function createAutowiredDefinition($type) private function createTypeNotFoundMessage(TypedReference $reference, $label) { - if (!$r = $this->container->getReflectionClass($type = $reference->getType(), true)) { + if (!$r = $this->container->getReflectionClass($type = $reference->getType())) { $message = sprintf('has type "%s" but this class does not exist.', $type); } else { $message = $this->container->has($type) ? 'this service is abstract' : 'no such service exists'; @@ -484,25 +497,9 @@ private function createTypeNotFoundMessage(TypedReference $reference, $label) private function createTypeAlternatives(TypedReference $reference) { - $type = $reference->getType(); - $aliases = array(); - foreach (class_parents($type) + class_implements($type) as $parent) { - if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) { - $aliases[] = $parent; - } - } - - if (1 < $len = count($aliases)) { - $message = ' Try changing the type-hint to one of its parents: '; - for ($i = 0, --$len; $i < $len; ++$i) { - $message .= sprintf('%s "%s", ', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]); - } - $message .= sprintf('or %s "%s".', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]); - - return $message; - } - if ($aliases) { - return sprintf(' Try changing the type-hint to "%s" instead.', $aliases[0]); + // try suggesting available aliases first + if ($message = $this->getAliasesSuggestionForType($type = $reference->getType())) { + return ' '.$message; } if (isset($this->ambiguousServiceTypes[$type])) { @@ -542,4 +539,29 @@ private static function getResourceMetadataForMethod(\ReflectionMethod $method) return $methodArgumentsMetadata; } + + private function getAliasesSuggestionForType($type, $extraContext = null) + { + $aliases = array(); + foreach (class_parents($type) + class_implements($type) as $parent) { + if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) { + $aliases[] = $parent; + } + } + + $extraContext = $extraContext ? ' '.$extraContext : ''; + if (1 < $len = count($aliases)) { + $message = sprintf('Try changing the type-hint%s to one of its parents: ', $extraContext); + for ($i = 0, --$len; $i < $len; ++$i) { + $message .= sprintf('%s "%s", ', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]); + } + $message .= sprintf('or %s "%s".', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]); + + return $message; + } + + if ($aliases) { + return sprintf('Try changing the type-hint%s to "%s" instead.', $extraContext, $aliases[0]); + } + } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php index b084d7e4dce28..7a5da70d09567 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php @@ -36,7 +36,9 @@ public function setRepeatedPass(RepeatedPass $repeatedPass) /** * Returns an array of all services inlined by this pass. * - * @return array Service id strings + * The key is the inlined service id and its value is the list of services it was inlined into. + * + * @return array */ public function getInlinedServiceIds() { @@ -57,7 +59,7 @@ protected function processValue($value, $isRoot = false) if ($this->isInlineableDefinition($id, $definition, $this->container->getCompiler()->getServiceReferenceGraph())) { $this->container->log($this, sprintf('Inlined service "%s" to "%s".', $id, $this->currentId)); - $this->inlinedServiceIds[] = $id; + $this->inlinedServiceIds[$id][] = $this->currentId; if ($definition->isShared()) { return $definition; diff --git a/src/Symfony/Component/DependencyInjection/Config/AutowireServiceResource.php b/src/Symfony/Component/DependencyInjection/Config/AutowireServiceResource.php index f49a1eb78e16c..5e683cbcf0d88 100644 --- a/src/Symfony/Component/DependencyInjection/Config/AutowireServiceResource.php +++ b/src/Symfony/Component/DependencyInjection/Config/AutowireServiceResource.php @@ -65,7 +65,7 @@ public function serialize() public function unserialize($serialized) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { list($this->class, $this->filePath, $this->autowiringMetadata) = unserialize($serialized, array('allowed_classes' => false)); } else { list($this->class, $this->filePath, $this->autowiringMetadata) = unserialize($serialized); diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php index 0675dd6f58071..14dd957e9ea13 100644 --- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php +++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php @@ -12,7 +12,6 @@ namespace Symfony\Component\DependencyInjection; use Psr\Container\ContainerInterface as PsrContainerInterface; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; @@ -338,13 +337,12 @@ public function addClassResource(\ReflectionClass $class) * Retrieves the requested reflection class and registers it for resource tracking. * * @param string $class - * @param bool $koWithThrowingAutoloader Whether autoload should be protected against bad parents or not * * @return \ReflectionClass|null * * @final */ - public function getReflectionClass($class, $koWithThrowingAutoloader = false) + public function getReflectionClass($class) { if (!$class = $this->getParameterBag()->resolveValue($class)) { return; @@ -354,12 +352,9 @@ public function getReflectionClass($class, $koWithThrowingAutoloader = false) try { if (isset($this->classReflectors[$class])) { $classReflector = $this->classReflectors[$class]; - } elseif ($koWithThrowingAutoloader) { - $resource = new ClassExistenceResource($class, ClassExistenceResource::EXISTS_KO_WITH_THROWING_AUTOLOADER); - - $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class); } else { - $classReflector = new \ReflectionClass($class); + $resource = new ClassExistenceResource($class, false); + $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class); } } catch (\ReflectionException $e) { $classReflector = false; @@ -367,7 +362,7 @@ public function getReflectionClass($class, $koWithThrowingAutoloader = false) if ($this->trackResources) { if (!$classReflector) { - $this->addResource($resource ?: new ClassExistenceResource($class, ClassExistenceResource::EXISTS_KO)); + $this->addResource($resource ?: new ClassExistenceResource($class, false)); } elseif (!$classReflector->isInternal()) { $path = $classReflector->getFileName(); @@ -1161,31 +1156,6 @@ public function resolveServices($value) return $count; }); - } elseif ($value instanceof ClosureProxyArgument) { - $parameterBag = $this->getParameterBag(); - list($reference, $method) = $value->getValues(); - if ('service_container' === $id = (string) $reference) { - $class = parent::class; - } elseif (!$this->hasDefinition($id) && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { - return; - } else { - $class = $parameterBag->resolveValue($this->findDefinition($id)->getClass()); - } - if (!method_exists($class, $method = $parameterBag->resolveValue($method))) { - throw new InvalidArgumentException(sprintf('Cannot create closure-proxy for service "%s": method "%s::%s" does not exist.', $id, $class, $method)); - } - $r = new \ReflectionMethod($class, $method); - if (!$r->isPublic()) { - throw new RuntimeException(sprintf('Cannot create closure-proxy for service "%s": method "%s::%s" must be public.', $id, $class, $method)); - } - foreach ($r->getParameters() as $p) { - if ($p->isPassedByReference()) { - throw new RuntimeException(sprintf('Cannot create closure-proxy for service "%s": parameter "$%s" of method "%s::%s" must not be passed by reference.', $id, $p->name, $class, $method)); - } - } - $value = function () use ($id, $method) { - return call_user_func_array(array($this->get($id), $method), func_get_args()); - }; } elseif ($value instanceof Reference) { $value = $this->get((string) $value, $value->getInvalidBehavior()); } elseif ($value instanceof Definition) { diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index a1fb8950e0871..840b670f165f5 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -12,7 +12,6 @@ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Variable; @@ -27,7 +26,6 @@ use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; -use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; use Symfony\Component\DependencyInjection\ExpressionLanguage; @@ -67,7 +65,6 @@ class PhpDumper extends Dumper private $docStar; private $serviceIdToMethodNameMap; private $usedMethodNames; - private $baseClass; /** * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface @@ -125,7 +122,6 @@ public function dump(array $options = array()) $this->classResources = array(); $this->initializeMethodNamesMap($options['base_class']); - $this->baseClass = $options['base_class']; $this->docStar = $options['debug'] ? '*' : ''; @@ -1465,34 +1461,6 @@ private function dumpValue($value, $interpolate = true) return implode("\n", $code); } - - if ($value instanceof ClosureProxyArgument) { - list($reference, $method) = $value->getValues(); - $method = substr($this->dumpLiteralClass($this->dumpValue($method)), 1); - - if ('service_container' === (string) $reference) { - $class = $this->baseClass; - } elseif (!$this->container->hasDefinition((string) $reference) && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { - return 'null'; - } else { - $class = substr($this->dumpLiteralClass($this->dumpValue($this->container->findDefinition((string) $reference)->getClass())), 1); - } - if (false !== strpos($class, '$') || false !== strpos($method, '$')) { - throw new RuntimeException(sprintf('Cannot dump definition for service "%s": dynamic class names or methods, and closure-proxies are incompatible with each other.', $reference)); - } - if (!method_exists($class, $method)) { - throw new InvalidArgumentException(sprintf('Cannot create closure-proxy for service "%s": method "%s::%s" does not exist.', $reference, $class, $method)); - } - $r = $this->container->getReflectionClass($class)->getMethod($method); - if (!$r->isPublic()) { - throw new InvalidArgumentException(sprintf('Cannot create closure-proxy for service "%s": method "%s::%s" must be public.', $reference, $class, $method)); - } - $signature = preg_replace('/^(&?)[^(]*/', '$1', ProxyHelper::getSignature($r, $call)); - - $return = 'void' !== ProxyHelper::getTypeHint($r); - - return sprintf("/** @closure-proxy %s::%s */ function %s {\n %s%s->%s;\n }", $class, $method, $signature, $return ? 'return ' : '', $this->dumpValue($reference), $call); - } } finally { list($this->definitionVariables, $this->referenceVariables, $this->variableCount) = $scope; } diff --git a/src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php index 61978dcd28971..c6b3be06a1402 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php @@ -11,7 +11,6 @@ namespace Symfony\Component\DependencyInjection\Dumper; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -302,11 +301,6 @@ private function convertParameters(array $parameters, $type, \DOMElement $parent } elseif ($value instanceof IteratorArgument) { $element->setAttribute('type', 'iterator'); $this->convertParameters($value->getValues(), $type, $element, 'key'); - } elseif ($value instanceof ClosureProxyArgument) { - list($reference, $method) = $value->getValues(); - $element->setAttribute('type', 'closure-proxy'); - $element->setAttribute('id', (string) $reference); - $element->setAttribute('method', $method); } elseif ($value instanceof Reference) { $element->setAttribute('type', 'service'); $element->setAttribute('id', (string) $value); diff --git a/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php index 81951fe536699..e71df2af24c14 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php @@ -15,7 +15,6 @@ use Symfony\Component\Yaml\Tag\TaggedValue; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -256,8 +255,6 @@ private function dumpValue($value) if ($value instanceof ArgumentInterface) { if ($value instanceof IteratorArgument) { $tag = 'iterator'; - } elseif ($value instanceof ClosureProxyArgument) { - $tag = 'closure_proxy'; } else { throw new RuntimeException(sprintf('Unspecified Yaml tag for type "%s".', get_class($value))); } diff --git a/src/Symfony/Component/DependencyInjection/Exception/AutowiringFailedException.php b/src/Symfony/Component/DependencyInjection/Exception/AutowiringFailedException.php index f5c50d4dee336..145cd8cbdcf24 100644 --- a/src/Symfony/Component/DependencyInjection/Exception/AutowiringFailedException.php +++ b/src/Symfony/Component/DependencyInjection/Exception/AutowiringFailedException.php @@ -18,7 +18,7 @@ class AutowiringFailedException extends RuntimeException { private $serviceId; - public function __construct($serviceId, $message = '', $code = 0, Exception $previous = null) + public function __construct($serviceId, $message = '', $code = 0, \Exception $previous = null) { $this->serviceId = $serviceId; diff --git a/src/Symfony/Component/DependencyInjection/LazyProxy/ProxyHelper.php b/src/Symfony/Component/DependencyInjection/LazyProxy/ProxyHelper.php index 5f0c8772fef43..84686efff5d6a 100644 --- a/src/Symfony/Component/DependencyInjection/LazyProxy/ProxyHelper.php +++ b/src/Symfony/Component/DependencyInjection/LazyProxy/ProxyHelper.php @@ -18,54 +18,6 @@ */ class ProxyHelper { - /** - * @return string The signature of the passed function, return type and function/method name included if any - */ - public static function getSignature(\ReflectionFunctionAbstract $r, &$call = null) - { - $signature = array(); - $call = array(); - - foreach ($r->getParameters() as $i => $p) { - $k = '$'.$p->name; - if (method_exists($p, 'isVariadic') && $p->isVariadic()) { - $k = '...'.$k; - } - $call[] = $k; - - if ($p->isPassedByReference()) { - $k = '&'.$k; - } - if ($type = self::getTypeHint($r, $p)) { - $k = $type.' '.$k; - } - if ($type && $p->allowsNull()) { - $k = '?'.$k; - } - - try { - $k .= ' = '.self::export($p->getDefaultValue()); - if ($type && $p->allowsNull() && null === $p->getDefaultValue()) { - $k = substr($k, 1); - } - } catch (\ReflectionException $e) { - if ($type && $p->allowsNull() && !class_exists('ReflectionNamedType', false)) { - $k .= ' = null'; - $k = substr($k, 1); - } - } - - $signature[] = $k; - } - $call = ($r->isClosure() ? '' : $r->name).'('.implode(', ', $call).')'; - - if ($type = self::getTypeHint($r)) { - $type = ': '.($r->getReturnType()->allowsNull() ? '?' : '').$type; - } - - return ($r->returnsReference() ? '&' : '').($r->isClosure() ? '' : $r->name).'('.implode(', ', $signature).')'.$type; - } - /** * @return string|null The FQCN or builtin name of the type hint, or null when the type hint references an invalid self|parent context */ diff --git a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php index 79c8fbf9677ab..4b07e5c58581e 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php @@ -14,7 +14,6 @@ use Symfony\Component\Config\Util\XmlUtils; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ChildDefinition; @@ -493,15 +492,6 @@ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = case 'expression': $arguments[$key] = new Expression($arg->nodeValue); break; - case 'closure-proxy': - if (!$arg->getAttribute('id')) { - throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="closure-proxy" has no or empty "id" attribute in "%s".', $name, $file)); - } - if (!$arg->getAttribute('method')) { - throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="closure-proxy" has no or empty "method" attribute in "%s".', $name, $file)); - } - $arguments[$key] = new ClosureProxyArgument($arg->getAttribute('id'), $arg->getAttribute('method'), $invalidBehavior); - break; case 'collection': $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, $file, false); break; diff --git a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php index c3e697c1b5207..7a0123ba21bf5 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php @@ -13,7 +13,6 @@ use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -679,21 +678,6 @@ private function resolveServices($value, $file, $isParameter = false) throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts arrays of "@service" references in "%s".', $file)); } } - if ('closure_proxy' === $value->getTag()) { - if (!is_array($argument) || array(0, 1) !== array_keys($argument) || !is_string($argument[0]) || !is_string($argument[1]) || 0 !== strpos($argument[0], '@') || 0 === strpos($argument[0], '@@')) { - throw new InvalidArgumentException(sprintf('"!closure_proxy" tagged values must be arrays of [@service, method] in "%s".', $file)); - } - - if (0 === strpos($argument[0], '@?')) { - $argument[0] = substr($argument[0], 2); - $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE; - } else { - $argument[0] = substr($argument[0], 1); - $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE; - } - - return new ClosureProxyArgument($argument[0], $argument[1], $invalidBehavior); - } if ('service' === $value->getTag()) { if ($isParameter) { throw new InvalidArgumentException(sprintf('Using an anonymous service in a parameter is not allowed in "%s".', $file)); diff --git a/src/Symfony/Component/DependencyInjection/Loader/schema/dic/services/services-1.0.xsd b/src/Symfony/Component/DependencyInjection/Loader/schema/dic/services/services-1.0.xsd index 2de786bdb7cba..6f5c8ccc543d3 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/schema/dic/services/services-1.0.xsd +++ b/src/Symfony/Component/DependencyInjection/Loader/schema/dic/services/services-1.0.xsd @@ -218,7 +218,6 @@ - @@ -244,7 +243,6 @@ - diff --git a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php index a367a8b2c4d03..a941b960746be 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ChildDefinitionTest.php @@ -113,6 +113,10 @@ public function testReplaceArgument() $this->assertSame('baz', $def->getArgument(1)); $this->assertSame(array(0 => 'foo', 1 => 'bar', 'index_1' => 'baz'), $def->getArguments()); + + $this->assertSame($def, $def->replaceArgument('$bar', 'val')); + $this->assertSame('val', $def->getArgument('$bar')); + $this->assertSame(array(0 => 'foo', 1 => 'bar', 'index_1' => 'baz', '$bar' => 'val'), $def->getArguments()); } /** diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php index eb1d838122c7c..f76001a11abf7 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutoAliasServicePassTest.php @@ -25,7 +25,7 @@ public function testProcessWithMissingParameter() $container = new ContainerBuilder(); $container->register('example') - ->addTag('auto_alias', array('format' => '%non_existing%.example')); + ->addTag('auto_alias', array('format' => '%non_existing%.example')); $pass = new AutoAliasServicePass(); $pass->process($container); @@ -39,7 +39,7 @@ public function testProcessWithMissingFormat() $container = new ContainerBuilder(); $container->register('example') - ->addTag('auto_alias', array()); + ->addTag('auto_alias', array()); $container->setParameter('existing', 'mysql'); $pass = new AutoAliasServicePass(); @@ -51,7 +51,7 @@ public function testProcessWithNonExistingAlias() $container = new ContainerBuilder(); $container->register('example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassDefault') - ->addTag('auto_alias', array('format' => '%existing%.example')); + ->addTag('auto_alias', array('format' => '%existing%.example')); $container->setParameter('existing', 'mysql'); $pass = new AutoAliasServicePass(); @@ -65,7 +65,7 @@ public function testProcessWithExistingAlias() $container = new ContainerBuilder(); $container->register('example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassDefault') - ->addTag('auto_alias', array('format' => '%existing%.example')); + ->addTag('auto_alias', array('format' => '%existing%.example')); $container->register('mysql.example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassMysql'); $container->setParameter('existing', 'mysql'); @@ -83,7 +83,7 @@ public function testProcessWithManualAlias() $container = new ContainerBuilder(); $container->register('example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassDefault') - ->addTag('auto_alias', array('format' => '%existing%.example')); + ->addTag('auto_alias', array('format' => '%existing%.example')); $container->register('mysql.example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassMysql'); $container->register('mariadb.example', 'Symfony\Component\DependencyInjection\Tests\Compiler\ServiceClassMariaDb'); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowireExceptionPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowireExceptionPassTest.php index 092b6401c48ef..4f0b3d6c2566c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowireExceptionPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowireExceptionPassTest.php @@ -54,7 +54,7 @@ public function testThrowExceptionIfServiceInlined() $autowirePass = $this->getMockBuilder(AutowirePass::class) ->getMock(); - $autowireException = new AutowiringFailedException('foo_service_id', 'An autowiring exception message'); + $autowireException = new AutowiringFailedException('a_service', 'An autowiring exception message'); $autowirePass->expects($this->any()) ->method('getAutowiringExceptions') ->will($this->returnValue(array($autowireException))); @@ -63,10 +63,16 @@ public function testThrowExceptionIfServiceInlined() ->getMock(); $inlinePass->expects($this->any()) ->method('getInlinedServiceIds') - ->will($this->returnValue(array('foo_service_id'))); + ->will($this->returnValue(array( + // a_service inlined into b_service + 'a_service' => array('b_service'), + // b_service inlined into c_service + 'b_service' => array('c_service'), + ))); - // don't register the foo_service_id service $container = new ContainerBuilder(); + // ONLY register c_service in the final container + $container->register('c_service', 'stdClass'); $pass = new AutowireExceptionPass($autowirePass, $inlinePass); @@ -78,6 +84,37 @@ public function testThrowExceptionIfServiceInlined() } } + public function testDoNotThrowExceptionIfServiceInlinedButRemoved() + { + $autowirePass = $this->getMockBuilder(AutowirePass::class) + ->getMock(); + + $autowireException = new AutowiringFailedException('a_service', 'An autowiring exception message'); + $autowirePass->expects($this->any()) + ->method('getAutowiringExceptions') + ->will($this->returnValue(array($autowireException))); + + $inlinePass = $this->getMockBuilder(InlineServiceDefinitionsPass::class) + ->getMock(); + $inlinePass->expects($this->any()) + ->method('getInlinedServiceIds') + ->will($this->returnValue(array( + // a_service inlined into b_service + 'a_service' => array('b_service'), + // b_service inlined into c_service + 'b_service' => array('c_service'), + ))); + + // do NOT register c_service in the container + $container = new ContainerBuilder(); + + $pass = new AutowireExceptionPass($autowirePass, $inlinePass); + + $pass->process($container); + // mark the test as passed + $this->assertTrue(true); + } + public function testNoExceptionIfServiceRemoved() { $autowirePass = $this->getMockBuilder(AutowirePass::class) diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php index e2ba9ec4e4b97..41ad5634132c0 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php @@ -78,6 +78,28 @@ public function testProcessAutowireParent() $this->assertEquals(B::class, (string) $container->getDefinition('c')->getArgument(0)); } + /** + * @group legacy + * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. Try changing the type-hint for argument "$a" of method "Symfony\Component\DependencyInjection\Tests\Compiler\C::__construct()" to "Symfony\Component\DependencyInjection\Tests\Compiler\AInterface" instead. + * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedExceptionMessageInSymfony4 Cannot autowire service "c": argument "$a" of method "Symfony\Component\DependencyInjection\Tests\Compiler\C::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to the existing "Symfony\Component\DependencyInjection\Tests\Compiler\B" service. + */ + public function testProcessLegacyAutowireWithAvailableInterface() + { + $container = new ContainerBuilder(); + + $container->setAlias(AInterface::class, B::class); + $container->register(B::class); + $cDefinition = $container->register('c', __NAMESPACE__.'\C'); + $cDefinition->setAutowired(true); + + (new ResolveClassPass())->process($container); + (new AutowirePass())->process($container); + + $this->assertCount(1, $container->getDefinition('c')->getArguments()); + $this->assertEquals(B::class, (string) $container->getDefinition('c')->getArgument(0)); + } + /** * @group legacy * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. You should alias the "Symfony\Component\DependencyInjection\Tests\Compiler\F" service to "Symfony\Component\DependencyInjection\Tests\Compiler\DInterface" instead. @@ -151,7 +173,21 @@ public function testExceptionsAreStored() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException + * @expectedExceptionMessage Unable to resolve service "private_service": constructor of class "Symfony\Component\DependencyInjection\Tests\Compiler\PrivateConstructor" must be public. + */ + public function testPrivateConstructorThrowsAutowireException() + { + $container = new ContainerBuilder(); + + $container->autowire('private_service', __NAMESPACE__.'\PrivateConstructor'); + + $pass = new AutowirePass(true); + $pass->process($container); + } + + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2", "c3". */ public function testTypeCollision() @@ -169,7 +205,7 @@ public function testTypeCollision() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgument::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2". */ public function testTypeNotGuessable() @@ -186,7 +222,7 @@ public function testTypeNotGuessable() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgumentForSubclass::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2". */ public function testTypeNotGuessableWithSubclass() @@ -203,7 +239,7 @@ public function testTypeNotGuessableWithSubclass() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. */ public function testTypeNotGuessableNoServicesFound() @@ -322,7 +358,7 @@ public function testDontTriggerAutowiring() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class does not exist. */ public function testClassNotFoundThrowsException() @@ -337,7 +373,7 @@ public function testClassNotFoundThrowsException() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadParentTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\OptionalServiceClass" but this class does not exist. */ public function testParentClassNotFoundThrowsException() @@ -354,7 +390,7 @@ public function testParentClassNotFoundThrowsException() /** * @group legacy * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. You should rename (or alias) the "foo" service to "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" instead. - * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessageInSymfony4 Cannot autowire service "bar": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\Bar::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but this service is abstract. You should maybe alias this class to the existing "foo" service. */ public function testDontUseAbstractServices() @@ -399,7 +435,7 @@ public function testSomeSpecificArgumentsAreSet() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "arg_no_type_hint": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" must have a type-hint or be given a value explicitly. */ public function testScalarArgsCannotBeAutowired() @@ -607,7 +643,7 @@ public function testIgnoreServiceWithClassNotExisting() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "setter_injection_collision": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\SetterInjectionCollision::setMultipleInstancesForOneArg()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2". */ public function testSetterInjectionCollisionThrowsException() @@ -626,7 +662,7 @@ public function testSetterInjectionCollisionThrowsException() /** * @group legacy * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. You should rename (or alias) the "foo" service to "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" instead. - * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessageInSymfony4 Cannot autowire service "bar": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\Bar::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to the existing "foo" service. */ public function testProcessDoesNotTriggerDeprecations() @@ -677,7 +713,7 @@ public function testWithFactory() /** * @dataProvider provideNotWireableCalls - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException */ public function testNotWireableCalls($method, $expectedMsg) { @@ -716,8 +752,8 @@ public function provideNotWireableCalls() /** * @group legacy - * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. You should rename (or alias) the "i" service to "Symfony\Component\DependencyInjection\Tests\Compiler\I" instead. - * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. Try changing the type-hint for argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead. + * @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessageInSymfony4 Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead. */ public function testByIdAlternative() @@ -734,7 +770,26 @@ public function testByIdAlternative() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @group legacy + * @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. Try changing the type-hint for "Symfony\Component\DependencyInjection\Tests\Compiler\A" in "Symfony\Component\DependencyInjection\Tests\Compiler\Bar" to "Symfony\Component\DependencyInjection\Tests\Compiler\AInterface" instead. + */ + public function testTypedReferenceDeprecationNotice() + { + $container = new ContainerBuilder(); + + $container->register('aClass', A::class); + $container->setAlias(AInterface::class, 'aClass'); + $container + ->register('bar', Bar::class) + ->setProperty('a', array(new TypedReference(A::class, A::class, Bar::class))) + ; + + $pass = new AutowirePass(); + $pass->process($container); + } + + /** + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead. */ public function testExceptionWhenAliasExists() @@ -754,7 +809,7 @@ public function testExceptionWhenAliasExists() } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException + * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to one of these existing services: "i", "i2". */ public function testExceptionWhenAliasDoesNotExist() @@ -784,7 +839,11 @@ public function __construct(Foo $foo) } } -class A +interface AInterface +{ +} + +class A implements AInterface { public static function create(Foo $foo) { @@ -1091,3 +1150,10 @@ protected function setProtectedMethod(A $a) { } } + +class PrivateConstructor +{ + private function __construct() + { + } +} diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php index d241758b04425..26b24fa713242 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; class InlineServiceDefinitionsPassTest extends TestCase @@ -233,8 +233,8 @@ public function testProcessDoesNotSetLazyArgumentValuesAfterInlining() ->setShared(false) ; $container - ->register('closure-proxy') - ->setArguments(array(new ClosureProxyArgument('inline', 'method'))) + ->register('service-closure') + ->setArguments(array(new ServiceClosureArgument(new Reference('inline')))) ; $container ->register('iterator') @@ -243,7 +243,7 @@ public function testProcessDoesNotSetLazyArgumentValuesAfterInlining() $this->process($container); - $values = $container->getDefinition('closure-proxy')->getArgument(0)->getValues(); + $values = $container->getDefinition('service-closure')->getArgument(0)->getValues(); $this->assertInstanceOf(Reference::class, $values[0]); $this->assertSame('inline', (string) $values[0]); @@ -252,7 +252,7 @@ public function testProcessDoesNotSetLazyArgumentValuesAfterInlining() $this->assertSame('inline', (string) $values[0]); } - public function testGetInlinedServiceIds() + public function testGetInlinedServiceIdData() { $container = new ContainerBuilder(); $container @@ -265,7 +265,7 @@ public function testGetInlinedServiceIds() ; $container - ->register('service') + ->register('other_service') ->setArguments(array(new Reference('inlinable.service'))) ; @@ -273,7 +273,7 @@ public function testGetInlinedServiceIds() $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), $inlinePass)); $repeatedPass->process($container); - $this->assertEquals(array('inlinable.service'), $inlinePass->getInlinedServiceIds()); + $this->assertEquals(array('inlinable.service' => array('other_service')), $inlinePass->getInlinedServiceIds()); } protected function process(ContainerBuilder $container) diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php index 3558c7bd226e1..51f7001491a19 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php @@ -20,7 +20,6 @@ use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\Config\Resource\DirectoryResource; use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; @@ -1008,63 +1007,6 @@ public function testAutowiring() $this->assertEquals(A::class, (string) $container->getDefinition('b')->getArgument(0)); } - public function testClosureProxy() - { - $container = new ContainerBuilder(); - - $container->register('foo', 'stdClass') - ->setProperty('foo', new ClosureProxyArgument('bar', 'c')) - ; - $container->register('bar', A::class); - - $foo = $container->get('foo'); - - $this->assertInstanceOf('Closure', $foo->foo); - $this->assertSame(123, call_user_func($foo->foo)); - } - - public function testClosureProxyContainer() - { - $container = new ContainerBuilder(); - - $container->register('foo', 'stdClass') - ->setProperty('foo', new ClosureProxyArgument('service_container', 'get')) - ; - - $foo = $container->get('foo'); - - $this->assertInstanceOf('Closure', $foo->foo); - $this->assertSame($foo, call_user_func($foo->foo, 'foo')); - } - - public function testClosureProxyOnInvalidNull() - { - $container = new ContainerBuilder(); - - $container->register('foo', 'stdClass') - ->setProperty('foo', new ClosureProxyArgument('bar', 'c', ContainerInterface::NULL_ON_INVALID_REFERENCE)) - ; - - $foo = $container->get('foo'); - - $this->assertNull($foo->foo); - } - - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage You have requested a non-existent service "bar". - */ - public function testClosureProxyOnInvalidException() - { - $container = new ContainerBuilder(); - - $container->register('foo', 'stdClass') - ->setProperty('foo', new ClosureProxyArgument('bar', 'c')) - ; - - $container->get('foo'); - } - public function testClassFromId() { $container = new ContainerBuilder(); @@ -1148,10 +1090,6 @@ class FooClass class A { - public function c() - { - return 123; - } } class B diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index b11201111c1f5..fe53b941006de 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -472,46 +472,6 @@ public function testLazyArgumentProvideGenerator() $this->assertEmpty(iterator_to_array($lazyContext->lazyEmptyValues)); } - public function testClosureProxy() - { - $container = include self::$fixturesPath.'/containers/container31.php'; - $container->compile(); - $dumper = new PhpDumper($container); - - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services31.php', $dumper->dump()); - $res = $container->getResources(); - $this->assertSame('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Container31\Foo', (string) array_pop($res)); - } - - /** - * @requires PHP 7.1 - */ - public function testClosureProxyWithVoidReturnType() - { - $container = include self::$fixturesPath.'/containers/container_dump_proxy_with_void_return_type.php'; - - $container->compile(); - $dumper = new PhpDumper($container); - - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_dump_proxy_with_void_return_type.php', $dumper->dump()); - $res = $container->getResources(); - $this->assertSame('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\ContainerVoid\Foo', (string) array_pop($res)); - } - - /** - * @requires PHP 7.1 - */ - public function testClosureProxyPhp71() - { - $container = include self::$fixturesPath.'/containers/container32.php'; - $container->compile(); - $dumper = new PhpDumper($container); - - $this->assertStringEqualsFile(self::$fixturesPath.'/php/services32.php', $dumper->dump()); - $res = $container->getResources(); - $this->assertSame('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo', (string) array_pop($res)); - } - public function testNormalizedId() { $container = include self::$fixturesPath.'/containers/container33.php'; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container31.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container31.php deleted file mode 100644 index e8493ad02cdf6..0000000000000 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container31.php +++ /dev/null @@ -1,37 +0,0 @@ -register('foo', Foo::class); - -$container->register('bar', 'stdClass') - ->setProperty('foo', array( - new ClosureProxyArgument('foo', 'withNoArgs'), - new ClosureProxyArgument('foo', 'withArgs'), - new ClosureProxyArgument('foo', 'withRefs'), - )) -; - -return $container; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container32.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container32.php deleted file mode 100644 index 00d5654a5b464..0000000000000 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container32.php +++ /dev/null @@ -1,37 +0,0 @@ -register('foo', Foo::class); - -$container->register('bar', 'stdClass') - ->setProperty('foo', array( - new ClosureProxyArgument('foo', 'withVariadic'), - new ClosureProxyArgument('foo', 'withNullable'), - new ClosureProxyArgument('foo', 'withReturnType'), - )) -; - -return $container; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container33.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container33.php index 482558cb0d352..6deb52d170af8 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container33.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container33.php @@ -2,7 +2,6 @@ namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Container33; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; if (!class_exists(Foo::class, false)) { diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container9.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container9.php index 2a31ec6d76e47..13b45fda07a70 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container9.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container9.php @@ -3,7 +3,6 @@ require_once __DIR__.'/../includes/classes.php'; require_once __DIR__.'/../includes/foo.php'; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -140,9 +139,5 @@ ->register('lazy_context_ignore_invalid_ref', 'LazyContext') ->setArguments(array(new IteratorArgument(array(new Reference('foo.baz'), new Reference('invalid', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))), new IteratorArgument(array()))) ; -$container - ->register('closure_proxy', 'BarClass') - ->setArguments(array(new ClosureProxyArgument('closure_proxy', 'getBaz'))) -; return $container; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container_dump_proxy_with_void_return_type.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container_dump_proxy_with_void_return_type.php deleted file mode 100644 index ef9cb92a6c141..0000000000000 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container_dump_proxy_with_void_return_type.php +++ /dev/null @@ -1,27 +0,0 @@ -register('foo', Foo::class); - -$container->register('bar', 'stdClass') - ->setProperty('foo', array( - new ClosureProxyArgument('foo', 'withVoid'), - )) -; - -return $container; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services9.dot b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services9.dot index ac6a9c38d1d51..b316b93c1576b 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services9.dot +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services9.dot @@ -29,7 +29,6 @@ digraph sc { node_factory_service_simple [label="factory_service_simple\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_lazy_context [label="lazy_context\nLazyContext\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_lazy_context_ignore_invalid_ref [label="lazy_context_ignore_invalid_ref\nLazyContext\n", shape=record, fillcolor="#eeeeee", style="filled"]; - node_closure_proxy [label="closure_proxy\nBarClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_foo2 [label="foo2\n\n", shape=record, fillcolor="#ff9999", style="filled"]; node_foo3 [label="foo3\n\n", shape=record, fillcolor="#ff9999", style="filled"]; node_foobaz [label="foobaz\n\n", shape=record, fillcolor="#ff9999", style="filled"]; @@ -51,5 +50,4 @@ digraph sc { node_lazy_context -> node_service_container [label="" style="filled" color="#9999ff"]; node_lazy_context_ignore_invalid_ref -> node_foo_baz [label="" style="filled" color="#9999ff"]; node_lazy_context_ignore_invalid_ref -> node_invalid [label="" style="filled" color="#9999ff"]; - node_closure_proxy -> node_closure_proxy [label="" style="filled" color="#9999ff"]; } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services31.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services31.php index d22a130cd0514..daf0ed5d60a19 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services31.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services31.php @@ -61,29 +61,6 @@ public function isFrozen() return true; } - /** - * Gets the 'bar' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \stdClass A stdClass instance - */ - protected function getBarService() - { - $this->services['bar'] = $instance = new \stdClass(); - - $instance->foo = array(0 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\Container31\Foo::withNoArgs */ function () { - return ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withNoArgs(); - }, 1 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\Container31\Foo::withArgs */ function ($a, \Symfony\Component\DependencyInjection\Tests\Fixtures\Container31\Foo $b = NULL, $c = array(0 => 123)) { - return ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withArgs($a, $b, $c); - }, 2 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\Container31\Foo::withRefs */ function &(&$a = NULL, &$b) { - return ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withRefs($a, $b); - }); - - return $instance; - } - /** * Gets the 'foo' service. * diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services32.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services32.php deleted file mode 100644 index 08ca63092a6a6..0000000000000 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services32.php +++ /dev/null @@ -1,99 +0,0 @@ -services = array(); - $this->methodMap = array( - 'bar' => 'getBarService', - 'foo' => 'getFooService', - ); - - $this->aliases = array(); - } - - /** - * {@inheritdoc} - */ - public function compile() - { - throw new LogicException('You cannot compile a dumped container that was already compiled.'); - } - - /** - * {@inheritdoc} - */ - public function isCompiled() - { - return true; - } - - /** - * {@inheritdoc} - */ - public function isFrozen() - { - @trigger_error(sprintf('The %s() method is deprecated since version 3.3 and will be removed in 4.0. Use the isCompiled() method instead.', __METHOD__), E_USER_DEPRECATED); - - return true; - } - - /** - * Gets the 'bar' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \stdClass A stdClass instance - */ - protected function getBarService() - { - $this->services['bar'] = $instance = new \stdClass(); - - $instance->foo = array(0 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo::withVariadic */ function ($a, &...$c) { - return ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withVariadic($a, ...$c); - }, 1 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo::withNullable */ function (?int $a) { - return ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withNullable($a); - }, 2 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo::withReturnType */ function (): \Bar { - return ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withReturnType(); - }); - - return $instance; - } - - /** - * Gets the 'foo' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo A Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo instance - */ - protected function getFooService() - { - return $this->services['foo'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\Container32\Foo(); - } -} diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php index b8d5aeafacf24..2f8de5c8c0eb1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.php @@ -34,7 +34,6 @@ public function __construct() $this->methodMap = array( 'bar' => 'getBarService', 'baz' => 'getBazService', - 'closure_proxy' => 'getClosureProxyService', 'configurator_service' => 'getConfiguratorServiceService', 'configurator_service_simple' => 'getConfiguratorServiceSimpleService', 'configured_service' => 'getConfiguredServiceService', @@ -109,21 +108,6 @@ protected function getBazService() return $instance; } - /** - * Gets the 'closure_proxy' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \BarClass A BarClass instance - */ - protected function getClosureProxyService() - { - return $this->services['closure_proxy'] = new \BarClass(/** @closure-proxy BarClass::getBaz */ function () { - return ${($_ = isset($this->services['closure_proxy']) ? $this->services['closure_proxy'] : $this->get('closure_proxy')) && false ?: '_'}->getBaz(); - }); - } - /** * Gets the 'configured_service' service. * 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 a519cece6e297..08707b3b692c1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.php @@ -32,7 +32,6 @@ public function __construct() $this->methodMap = array( 'bar' => 'getBarService', 'baz' => 'getBazService', - 'closure_proxy' => 'getClosureProxyService', 'configured_service' => 'getConfiguredServiceService', 'configured_service_simple' => 'getConfiguredServiceSimpleService', 'decorator_service' => 'getDecoratorServiceService', @@ -119,21 +118,6 @@ protected function getBazService() return $instance; } - /** - * Gets the 'closure_proxy' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \BarClass A BarClass instance - */ - protected function getClosureProxyService() - { - return $this->services['closure_proxy'] = new \BarClass(/** @closure-proxy BarClass::getBaz */ function () { - return ${($_ = isset($this->services['closure_proxy']) ? $this->services['closure_proxy'] : $this->get('closure_proxy')) && false ?: '_'}->getBaz(); - }); - } - /** * Gets the 'configured_service' service. * diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_dump_proxy_with_void_return_type.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_dump_proxy_with_void_return_type.php deleted file mode 100644 index ec6af7fc2c8c5..0000000000000 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_dump_proxy_with_void_return_type.php +++ /dev/null @@ -1,95 +0,0 @@ -services = array(); - $this->methodMap = array( - 'bar' => 'getBarService', - 'foo' => 'getFooService', - ); - - $this->aliases = array(); - } - - /** - * {@inheritdoc} - */ - public function compile() - { - throw new LogicException('You cannot compile a dumped container that was already compiled.'); - } - - /** - * {@inheritdoc} - */ - public function isCompiled() - { - return true; - } - - /** - * {@inheritdoc} - */ - public function isFrozen() - { - @trigger_error(sprintf('The %s() method is deprecated since version 3.3 and will be removed in 4.0. Use the isCompiled() method instead.', __METHOD__), E_USER_DEPRECATED); - - return true; - } - - /** - * Gets the 'bar' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \stdClass A stdClass instance - */ - protected function getBarService() - { - $this->services['bar'] = $instance = new \stdClass(); - - $instance->foo = array(0 => /** @closure-proxy Symfony\Component\DependencyInjection\Tests\Fixtures\ContainerVoid\Foo::withVoid */ function (): void { - ${($_ = isset($this->services['foo']) ? $this->services['foo'] : $this->get('foo')) && false ?: '_'}->withVoid(); - }); - - return $instance; - } - - /** - * Gets the 'foo' service. - * - * This service is shared. - * This method always returns the same instance of the service. - * - * @return \Symfony\Component\DependencyInjection\Tests\Fixtures\ContainerVoid\Foo A Symfony\Component\DependencyInjection\Tests\Fixtures\ContainerVoid\Foo instance - */ - protected function getFooService() - { - return $this->services['foo'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\ContainerVoid\Foo(); - } -} diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services9.xml b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services9.xml index 79fdff4c4e2d0..100a23a9c5b7e 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services9.xml +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services9.xml @@ -130,9 +130,6 @@ - - - diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services9.yml b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services9.yml index bfee29fb605e5..a7a9cc28fd61b 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services9.yml +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services9.yml @@ -116,9 +116,6 @@ services: lazy_context_ignore_invalid_ref: class: LazyContext arguments: [!iterator ['@foo.baz', '@?invalid'], !iterator []] - closure_proxy: - class: BarClass - arguments: [!closure_proxy ['@closure_proxy', getBaz]] alias_for_foo: '@foo' alias_for_alias: '@foo' Psr\Container\ContainerInterface: diff --git a/src/Symfony/Component/DependencyInjection/composer.json b/src/Symfony/Component/DependencyInjection/composer.json index 7b0932881b464..8c88d4f02a790 100644 --- a/src/Symfony/Component/DependencyInjection/composer.json +++ b/src/Symfony/Component/DependencyInjection/composer.json @@ -32,7 +32,7 @@ "symfony/proxy-manager-bridge": "Generate service proxies to lazy load them" }, "conflict": { - "symfony/config": "<=3.3-beta1", + "symfony/config": "<3.3.1", "symfony/finder": "<3.3", "symfony/yaml": "<3.3" }, diff --git a/src/Symfony/Component/EventDispatcher/CHANGELOG.md b/src/Symfony/Component/EventDispatcher/CHANGELOG.md index 51c1d919bb4df..736bd84903b4b 100644 --- a/src/Symfony/Component/EventDispatcher/CHANGELOG.md +++ b/src/Symfony/Component/EventDispatcher/CHANGELOG.md @@ -4,7 +4,7 @@ CHANGELOG 3.3.0 ----- - * The ContainerAwareEventDispatcher class has been deprecated. Use EventDispatcher with closure-proxy injection instead. + * The ContainerAwareEventDispatcher class has been deprecated. Use EventDispatcher with closure factories instead. 3.0.0 ----- diff --git a/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php b/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php index 195acf2e0b6e6..fc7b30f9ccc65 100644 --- a/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php @@ -21,7 +21,7 @@ * @author Bernhard Schussek * @author Jordan Alliot * - * @deprecated since 3.3, to be removed in 4.0. Use EventDispatcher with closure-proxy injection instead. + * @deprecated since 3.3, to be removed in 4.0. Use EventDispatcher with closure factories instead. */ class ContainerAwareEventDispatcher extends EventDispatcher { @@ -60,7 +60,7 @@ public function __construct(ContainerInterface $container) $class = get_parent_class($class); } if (__CLASS__ !== $class) { - @trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure-proxy injection instead.', __CLASS__), E_USER_DEPRECATED); + @trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED); } } @@ -78,7 +78,7 @@ public function __construct(ContainerInterface $container) */ public function addListenerService($eventName, $callback, $priority = 0) { - @trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure-proxy injection instead.', __CLASS__), E_USER_DEPRECATED); + @trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED); if (!is_array($callback) || 2 !== count($callback)) { throw new \InvalidArgumentException('Expected an array("service", "method") argument'); @@ -116,7 +116,7 @@ public function removeListener($eventName, $listener) public function hasListeners($eventName = null) { if (null === $eventName) { - return (bool) count($this->listenerIds) || (bool) count($this->listeners); + return $this->listenerIds || $this->listeners || parent::hasListeners(); } if (isset($this->listenerIds[$eventName])) { @@ -160,7 +160,7 @@ public function getListenerPriority($eventName, $listener) */ public function addSubscriberService($serviceId, $class) { - @trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure-proxy injection instead.', __CLASS__), E_USER_DEPRECATED); + @trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED); foreach ($class::getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { diff --git a/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php b/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php index 130cc54d343bd..4029883dd98c7 100644 --- a/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php +++ b/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php @@ -46,13 +46,7 @@ public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatc $this->name = is_object($listener[0]) ? get_class($listener[0]) : $listener[0]; $this->pretty = $this->name.'::'.$listener[1]; } elseif ($listener instanceof \Closure) { - $r = new \ReflectionFunction($listener); - if (preg_match('#^/\*\* @closure-proxy ([^: ]++)::([^: ]++) \*/$#', $r->getDocComment(), $m)) { - $this->name = $m[1]; - $this->pretty = $m[1].'::'.$m[2]; - } else { - $this->pretty = $this->name = 'closure'; - } + $this->pretty = $this->name = 'closure'; } elseif (is_string($listener)) { $this->pretty = $this->name = $listener; } else { diff --git a/src/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php b/src/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php index 8b2df3ea0f639..50e466a3983c6 100644 --- a/src/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php +++ b/src/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php @@ -11,10 +11,11 @@ namespace Symfony\Component\EventDispatcher\DependencyInjection; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventSubscriberInterface; @@ -78,7 +79,7 @@ public function process(ContainerBuilder $container) $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']); } - $definition->addMethodCall('addListener', array($event['event'], new ClosureProxyArgument($id, $event['method']), $priority)); + $definition->addMethodCall('addListener', array($event['event'], array(new ServiceClosureArgument(new Reference($id)), $event['method']), $priority)); } } @@ -103,7 +104,7 @@ public function process(ContainerBuilder $container) ExtractingEventDispatcher::$subscriber = $class; $extractingDispatcher->addSubscriber($extractingDispatcher); foreach ($extractingDispatcher->listeners as $args) { - $args[1] = new ClosureProxyArgument($id, $args[1]); + $args[1] = array(new ServiceClosureArgument(new Reference($id)), $args[1]); $definition->addMethodCall('addListener', $args); } $extractingDispatcher->listeners = array(); diff --git a/src/Symfony/Component/EventDispatcher/EventDispatcher.php b/src/Symfony/Component/EventDispatcher/EventDispatcher.php index 01bfc0066ea25..4630b01cd8644 100644 --- a/src/Symfony/Component/EventDispatcher/EventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/EventDispatcher.php @@ -24,6 +24,7 @@ * @author Fabien Potencier * @author Jordi Boggiano * @author Jordan Alliot + * @author Nicolas Grekas */ class EventDispatcher implements EventDispatcherInterface { @@ -52,7 +53,7 @@ public function dispatch($eventName, Event $event = null) public function getListeners($eventName = null) { if (null !== $eventName) { - if (!isset($this->listeners[$eventName])) { + if (empty($this->listeners[$eventName])) { return array(); } @@ -77,13 +78,23 @@ public function getListeners($eventName = null) */ public function getListenerPriority($eventName, $listener) { - if (!isset($this->listeners[$eventName])) { + if (empty($this->listeners[$eventName])) { return; } + if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) { + $listener[0] = $listener[0](); + } + foreach ($this->listeners[$eventName] as $priority => $listeners) { - if (false !== in_array($listener, $listeners, true)) { - return $priority; + foreach ($listeners as $k => $v) { + if ($v !== $listener && is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) { + $v[0] = $v[0](); + $this->listeners[$eventName][$priority][$k] = $v; + } + if ($v === $listener) { + return $priority; + } } } } @@ -93,7 +104,17 @@ public function getListenerPriority($eventName, $listener) */ public function hasListeners($eventName = null) { - return (bool) $this->getListeners($eventName); + if (null !== $eventName) { + return !empty($this->listeners[$eventName]); + } + + foreach ($this->listeners as $eventListeners) { + if ($eventListeners) { + return true; + } + } + + return false; } /** @@ -110,13 +131,30 @@ public function addListener($eventName, $listener, $priority = 0) */ public function removeListener($eventName, $listener) { - if (!isset($this->listeners[$eventName])) { + if (empty($this->listeners[$eventName])) { return; } + if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) { + $listener[0] = $listener[0](); + } + foreach ($this->listeners[$eventName] as $priority => $listeners) { - if (false !== ($key = array_search($listener, $listeners, true))) { - unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]); + foreach ($listeners as $k => $v) { + if ($v !== $listener && is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) { + $v[0] = $v[0](); + } + if ($v === $listener) { + unset($listeners[$k], $this->sorted[$eventName]); + } else { + $listeners[$k] = $v; + } + } + + if ($listeners) { + $this->listeners[$eventName][$priority] = $listeners; + } else { + unset($this->listeners[$eventName][$priority]); } } } @@ -183,6 +221,16 @@ protected function doDispatch($listeners, $eventName, Event $event) private function sortListeners($eventName) { krsort($this->listeners[$eventName]); - $this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]); + $this->sorted[$eventName] = array(); + + foreach ($this->listeners[$eventName] as $priority => $listeners) { + foreach ($listeners as $k => $listener) { + if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) { + $listener[0] = $listener[0](); + $this->listeners[$eventName][$priority][$k] = $listener; + } + $this->sorted[$eventName][] = $listener; + } + } } } diff --git a/src/Symfony/Component/EventDispatcher/Tests/AbstractEventDispatcherTest.php b/src/Symfony/Component/EventDispatcher/Tests/AbstractEventDispatcherTest.php index 5943039c9e6de..9443f21664ced 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/AbstractEventDispatcherTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/AbstractEventDispatcherTest.php @@ -56,6 +56,7 @@ public function testAddListener() { $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo')); $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo')); + $this->assertTrue($this->dispatcher->hasListeners()); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); $this->assertCount(1, $this->dispatcher->getListeners(self::preFoo)); @@ -302,6 +303,73 @@ public function testHasListenersWithoutEventsReturnsFalseAfterHasListenersWithEv $this->assertFalse($this->dispatcher->hasListeners('foo')); $this->assertFalse($this->dispatcher->hasListeners()); } + + public function testHasListenersIsLazy() + { + $called = 0; + $listener = array(function () use (&$called) { ++$called; }, 'onFoo'); + $this->dispatcher->addListener('foo', $listener); + $this->assertTrue($this->dispatcher->hasListeners()); + $this->assertTrue($this->dispatcher->hasListeners('foo')); + $this->assertSame(0, $called); + } + + public function testDispatchLazyListener() + { + $called = 0; + $factory = function () use (&$called) { + ++$called; + + return new TestWithDispatcher(); + }; + $this->dispatcher->addListener('foo', array($factory, 'foo')); + $this->assertSame(0, $called); + $this->dispatcher->dispatch('foo', new Event()); + $this->dispatcher->dispatch('foo', new Event()); + $this->assertSame(1, $called); + } + + public function testRemoveFindsLazyListeners() + { + $test = new TestWithDispatcher(); + $factory = function () use ($test) { return $test; }; + + $this->dispatcher->addListener('foo', array($factory, 'foo')); + $this->assertTrue($this->dispatcher->hasListeners('foo')); + $this->dispatcher->removeListener('foo', array($test, 'foo')); + $this->assertFalse($this->dispatcher->hasListeners('foo')); + + $this->dispatcher->addListener('foo', array($test, 'foo')); + $this->assertTrue($this->dispatcher->hasListeners('foo')); + $this->dispatcher->removeListener('foo', array($factory, 'foo')); + $this->assertFalse($this->dispatcher->hasListeners('foo')); + } + + public function testPriorityFindsLazyListeners() + { + $test = new TestWithDispatcher(); + $factory = function () use ($test) { return $test; }; + + $this->dispatcher->addListener('foo', array($factory, 'foo'), 3); + $this->assertSame(3, $this->dispatcher->getListenerPriority('foo', array($test, 'foo'))); + $this->dispatcher->removeListener('foo', array($factory, 'foo')); + + $this->dispatcher->addListener('foo', array($test, 'foo'), 5); + $this->assertSame(5, $this->dispatcher->getListenerPriority('foo', array($factory, 'foo'))); + } + + public function testGetLazyListeners() + { + $test = new TestWithDispatcher(); + $factory = function () use ($test) { return $test; }; + + $this->dispatcher->addListener('foo', array($factory, 'foo'), 3); + $this->assertSame(array(array($test, 'foo')), $this->dispatcher->getListeners('foo')); + + $this->dispatcher->removeListener('foo', array($test, 'foo')); + $this->dispatcher->addListener('bar', array($factory, 'foo'), 3); + $this->assertSame(array('bar' => array(array($test, 'foo'))), $this->dispatcher->getListeners()); + } } class CallableClass diff --git a/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php b/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php index f583cd04cf9a7..d46d8c591195f 100644 --- a/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php +++ b/src/Symfony/Component/EventDispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php @@ -12,8 +12,9 @@ namespace Symfony\Component\EventDispatcher\Tests\DependencyInjection; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument; +use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; class RegisterListenersPassTest extends TestCase @@ -127,17 +128,17 @@ public function testEventSubscriberResolvableClassName() $registerListenersPass->process($container); $definition = $container->getDefinition('event_dispatcher'); - $expected_calls = array( + $expectedCalls = array( array( 'addListener', array( 'event', - new ClosureProxyArgument('foo', 'onEvent'), + array(new ServiceClosureArgument(new Reference('foo')), 'onEvent'), 0, ), ), ); - $this->assertEquals($expected_calls, $definition->getMethodCalls()); + $this->assertEquals($expectedCalls, $definition->getMethodCalls()); } /** diff --git a/src/Symfony/Component/Finder/Iterator/FilterIterator.php b/src/Symfony/Component/Finder/Iterator/FilterIterator.php index 3c3c3fbec0218..acb98361c9643 100644 --- a/src/Symfony/Component/Finder/Iterator/FilterIterator.php +++ b/src/Symfony/Component/Finder/Iterator/FilterIterator.php @@ -29,7 +29,7 @@ abstract class FilterIterator extends \FilterIterator */ public function rewind() { - if (PHP_VERSION_ID > 50607 || (PHP_VERSION_ID > 50523 && PHP_VERSION_ID < 50600)) { + if (\PHP_VERSION_ID > 50607 || (\PHP_VERSION_ID > 50523 && \PHP_VERSION_ID < 50600)) { parent::rewind(); return; diff --git a/src/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.php b/src/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.php index 5bea38e69a772..31178a833f5e7 100644 --- a/src/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.php +++ b/src/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.php @@ -119,7 +119,7 @@ public function rewind() } // @see https://bugs.php.net/68557 - if (PHP_VERSION_ID < 50523 || PHP_VERSION_ID >= 50600 && PHP_VERSION_ID < 50607) { + if (\PHP_VERSION_ID < 50523 || \PHP_VERSION_ID >= 50600 && \PHP_VERSION_ID < 50607) { parent::next(); } diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 68ce27b083f9b..d0f770ca67336 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -162,6 +162,10 @@ protected function getIntlDateFormatter($ignoreTimezone = false) $dateFormat = $this->dateFormat; $timeFormat = $this->timeFormat; $timezone = $ignoreTimezone ? 'UTC' : $this->outputTimezone; + if (class_exists('IntlTimeZone', false)) { + // see https://bugs.php.net/bug.php?id=66323 + $timezone = \IntlTimeZone::createTimeZone($timezone); + } $calendar = $this->calendar; $pattern = $this->pattern; diff --git a/src/Symfony/Component/Form/Extension/Core/Type/DateType.php b/src/Symfony/Component/Form/Extension/Core/Type/DateType.php index af90793282948..7690305f38012 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/DateType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/DateType.php @@ -82,7 +82,8 @@ public function buildForm(FormBuilderInterface $builder, array $options) \Locale::getDefault(), $dateFormat, $timeFormat, - null, + // see https://bugs.php.net/bug.php?id=66323 + class_exists('IntlTimeZone', false) ? \IntlTimeZone::createDefault() : null, $calendar, $pattern ); diff --git a/src/Symfony/Component/Form/FormError.php b/src/Symfony/Component/Form/FormError.php index e4e50a873c942..07d0fa991df72 100644 --- a/src/Symfony/Component/Form/FormError.php +++ b/src/Symfony/Component/Form/FormError.php @@ -185,7 +185,7 @@ public function serialize() */ public function unserialize($serialized) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { list($this->message, $this->messageTemplate, $this->messageParameters, $this->messagePluralization, $this->cause) = unserialize($serialized, array('allowed_classes' => false)); } else { list($this->message, $this->messageTemplate, $this->messageParameters, $this->messagePluralization, $this->cause) = unserialize($serialized); diff --git a/src/Symfony/Component/Form/Tests/AbstractDivLayoutTest.php b/src/Symfony/Component/Form/Tests/AbstractDivLayoutTest.php index 44e2f1d72dee2..36bb31c301515 100644 --- a/src/Symfony/Component/Form/Tests/AbstractDivLayoutTest.php +++ b/src/Symfony/Component/Form/Tests/AbstractDivLayoutTest.php @@ -345,8 +345,8 @@ public function testCollectionRow() ); $form = $this->factory->createNamedBuilder('form', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($collection) - ->getForm(); + ->add($collection) + ->getForm(); $this->assertWidgetMatchesXpath($form->createView(), array(), '/div diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php index fc9f85e3c752e..16302b3483692 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.php @@ -20,14 +20,14 @@ public function testTransform() { $transformer1 = $this->getMockBuilder('Symfony\Component\Form\DataTransformerInterface')->getMock(); $transformer1->expects($this->once()) - ->method('transform') - ->with($this->identicalTo('foo')) - ->will($this->returnValue('bar')); + ->method('transform') + ->with($this->identicalTo('foo')) + ->will($this->returnValue('bar')); $transformer2 = $this->getMockBuilder('Symfony\Component\Form\DataTransformerInterface')->getMock(); $transformer2->expects($this->once()) - ->method('transform') - ->with($this->identicalTo('bar')) - ->will($this->returnValue('baz')); + ->method('transform') + ->with($this->identicalTo('bar')) + ->will($this->returnValue('baz')); $chain = new DataTransformerChain(array($transformer1, $transformer2)); @@ -38,14 +38,14 @@ public function testReverseTransform() { $transformer2 = $this->getMockBuilder('Symfony\Component\Form\DataTransformerInterface')->getMock(); $transformer2->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo('foo')) - ->will($this->returnValue('bar')); + ->method('reverseTransform') + ->with($this->identicalTo('foo')) + ->will($this->returnValue('bar')); $transformer1 = $this->getMockBuilder('Symfony\Component\Form\DataTransformerInterface')->getMock(); $transformer1->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo('bar')) - ->will($this->returnValue('baz')); + ->method('reverseTransform') + ->with($this->identicalTo('bar')) + ->will($this->returnValue('baz')); $chain = new DataTransformerChain(array($transformer1, $transformer2)); diff --git a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php index 8cf89cd7a45c5..ef2edd5a7d115 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php @@ -470,9 +470,9 @@ public function testPassMultipartTrueIfAnyChildIsMultipartToView() public function testViewIsNotRenderedByDefault() { $view = $this->factory->createBuilder(static::TESTED_TYPE) - ->add('foo', static::TESTED_TYPE) - ->getForm() - ->createView(); + ->add('foo', static::TESTED_TYPE) + ->getForm() + ->createView(); $this->assertFalse($view->isRendered()); } diff --git a/src/Symfony/Component/Form/Tests/FormFactoryTest.php b/src/Symfony/Component/Form/Tests/FormFactoryTest.php index 1ed29120b88bf..30aea951fb8d4 100644 --- a/src/Symfony/Component/Form/Tests/FormFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/FormFactoryTest.php @@ -287,9 +287,9 @@ public function testCreateBuilderForPropertyCreatesFormWithHighestConfidence() public function testCreateBuilderCreatesTextFormIfNoGuess() { $this->guesser1->expects($this->once()) - ->method('guessType') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(null)); + ->method('guessType') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(null)); $factory = $this->getMockFactory(array('createNamedBuilder')); @@ -306,13 +306,13 @@ public function testCreateBuilderCreatesTextFormIfNoGuess() public function testOptionsCanBeOverridden() { $this->guesser1->expects($this->once()) - ->method('guessType') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new TypeGuess( - 'Symfony\Component\Form\Extension\Core\Type\TextType', - array('attr' => array('maxlength' => 10)), - Guess::MEDIUM_CONFIDENCE - ))); + ->method('guessType') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new TypeGuess( + 'Symfony\Component\Form\Extension\Core\Type\TextType', + array('attr' => array('maxlength' => 10)), + Guess::MEDIUM_CONFIDENCE + ))); $factory = $this->getMockFactory(array('createNamedBuilder')); @@ -334,17 +334,17 @@ public function testOptionsCanBeOverridden() public function testCreateBuilderUsesMaxLengthIfFound() { $this->guesser1->expects($this->once()) - ->method('guessMaxLength') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new ValueGuess( + ->method('guessMaxLength') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new ValueGuess( 15, Guess::MEDIUM_CONFIDENCE ))); $this->guesser2->expects($this->once()) - ->method('guessMaxLength') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new ValueGuess( + ->method('guessMaxLength') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new ValueGuess( 20, Guess::HIGH_CONFIDENCE ))); @@ -402,17 +402,17 @@ public function testCreateBuilderUsesMaxLengthAndPattern() public function testCreateBuilderUsesRequiredSettingWithHighestConfidence() { $this->guesser1->expects($this->once()) - ->method('guessRequired') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new ValueGuess( + ->method('guessRequired') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new ValueGuess( true, Guess::MEDIUM_CONFIDENCE ))); $this->guesser2->expects($this->once()) - ->method('guessRequired') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new ValueGuess( + ->method('guessRequired') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new ValueGuess( false, Guess::HIGH_CONFIDENCE ))); @@ -435,17 +435,17 @@ public function testCreateBuilderUsesRequiredSettingWithHighestConfidence() public function testCreateBuilderUsesPatternIfFound() { $this->guesser1->expects($this->once()) - ->method('guessPattern') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new ValueGuess( + ->method('guessPattern') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new ValueGuess( '[a-z]', Guess::MEDIUM_CONFIDENCE ))); $this->guesser2->expects($this->once()) - ->method('guessPattern') - ->with('Application\Author', 'firstName') - ->will($this->returnValue(new ValueGuess( + ->method('guessPattern') + ->with('Application\Author', 'firstName') + ->will($this->returnValue(new ValueGuess( '[a-zA-Z]', Guess::HIGH_CONFIDENCE ))); diff --git a/src/Symfony/Component/HttpFoundation/CHANGELOG.md b/src/Symfony/Component/HttpFoundation/CHANGELOG.md index ac812fe1527a0..e1fdf77b9b8ae 100644 --- a/src/Symfony/Component/HttpFoundation/CHANGELOG.md +++ b/src/Symfony/Component/HttpFoundation/CHANGELOG.md @@ -4,7 +4,7 @@ CHANGELOG 3.3.0 ----- - * [BC BREAK] the `Request::setTrustedProxies()` method takes a new `$trustedHeaderSet` argument, + * the `Request::setTrustedProxies()` method takes a new `$trustedHeaderSet` argument, see http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html for more info, * deprecated the `Request::setTrustedHeaderName()` and `Request::getTrustedHeaderName()` methods, * added `File\Stream`, to be passed to `BinaryFileResponse` when the size of the served file is unknown, diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index cf812a960f2d4..13ff1e05528fe 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -581,7 +581,7 @@ public function overrideGlobals() * You should only list the reverse proxies that you manage directly. * * @param array $proxies A list of trusted proxies - * @param int $trustedHeaderSet A bit field of Request::HEADER_*, usually either Request::HEADER_FORWARDED or Request::HEADER_X_FORWARDED_ALL, to set which headers to trust from your proxies + * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies * * @throws \InvalidArgumentException When $trustedHeaderSet is invalid */ @@ -590,10 +590,11 @@ public static function setTrustedProxies(array $proxies/*, int $trustedHeaderSet self::$trustedProxies = $proxies; if (2 > func_num_args()) { - // @deprecated code path in 3.3, to be replaced by mandatory argument in 4.0. - throw new \InvalidArgumentException(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument. Defining it is required since version 3.3. See http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html for more info.', __METHOD__)); + @trigger_error(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument since version 3.3. Defining it will be required in 4.0. ', __METHOD__), E_USER_DEPRECATED); + + return; } - $trustedHeaderSet = func_get_arg(1); + $trustedHeaderSet = (int) func_get_arg(1); foreach (self::$trustedHeaderNames as $header => $name) { self::$trustedHeaders[$header] = $header & $trustedHeaderSet ? $name : null; @@ -665,11 +666,11 @@ public static function getTrustedHosts() * * @throws \InvalidArgumentException * - * @deprecated since version 3.3, to be removed in 4.0. Use "X-Forwarded-*" headers or the "Forwarded" header defined in RFC7239, and the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. + * @deprecated since version 3.3, to be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. */ public static function setTrustedHeaderName($key, $value) { - @trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use "X-Forwarded-*" headers or the "Forwarded" header defined in RFC7239, and the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED); if (!array_key_exists($key, self::$trustedHeaders)) { throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key)); @@ -679,6 +680,9 @@ public static function setTrustedHeaderName($key, $value) if (null !== $value) { self::$trustedHeaderNames[$key] = $value; + self::$trustedHeaderSet |= $key; + } else { + self::$trustedHeaderSet &= ~$key; } } @@ -886,8 +890,8 @@ public function getClientIps() * adding the IP address where it received the request from. * * If your reverse proxy uses a different header name than "X-Forwarded-For", - * ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with - * the "client-ip" key. + * ("Client-Ip" for instance), configure it via the $trustedHeaderSet + * argument of the Request::setTrustedProxies() method instead. * * @return string|null The client IP address * @@ -993,7 +997,8 @@ public function getScheme() * The "X-Forwarded-Port" header must contain the client port. * * If your reverse proxy uses a different header name than "X-Forwarded-Port", - * configure it via "setTrustedHeaderName()" with the "client-port" key. + * configure it via via the $trustedHeaderSet argument of the + * Request::setTrustedProxies() method instead. * * @return int|string can be a string if fetched from the server bag */ @@ -1210,8 +1215,8 @@ public function getQueryString() * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". * * If your reverse proxy uses a different header name than "X-Forwarded-Proto" - * ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with - * the "client-proto" key. + * ("SSL_HTTPS" for instance), configure it via the $trustedHeaderSet + * argument of the Request::setTrustedProxies() method instead. * * @return bool */ @@ -1235,7 +1240,8 @@ public function isSecure() * The "X-Forwarded-Host" header must contain the client host name. * * If your reverse proxy uses a different header name than "X-Forwarded-Host", - * configure it via "setTrustedHeaderName()" with the "client-host" key. + * configure it via the $trustedHeaderSet argument of the + * Request::setTrustedProxies() method instead. * * @return string * @@ -1577,7 +1583,7 @@ public function isMethodCacheable() public function getContent($asResource = false) { $currentContentIsResource = is_resource($this->content); - if (PHP_VERSION_ID < 50600 && false === $this->content) { + if (\PHP_VERSION_ID < 50600 && false === $this->content) { throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.'); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php index dfc37459ab971..b36fbb7e96258 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php @@ -1057,7 +1057,7 @@ public function testContentAsResource() */ public function testGetContentCantBeCalledTwiceWithResources($first, $second) { - if (PHP_VERSION_ID >= 50600) { + if (\PHP_VERSION_ID >= 50600) { $this->markTestSkipped('PHP >= 5.6 allows to open php://input several times.'); } @@ -1729,7 +1729,7 @@ public function testTrustedProxiesXForwardedFor() /** * @group legacy - * @expectedDeprecation The "Symfony\Component\HttpFoundation\Request::setTrustedHeaderName()" method is deprecated since version 3.3 and will be removed in 4.0. Use "X-Forwarded-*" headers or the "Forwarded" header defined in RFC7239, and the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. + * @expectedDeprecation The "Symfony\Component\HttpFoundation\Request::setTrustedHeaderName()" method is deprecated since version 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. */ public function testLegacyTrustedProxies() { diff --git a/src/Symfony/Component/HttpKernel/Config/EnvParametersResource.php b/src/Symfony/Component/HttpKernel/Config/EnvParametersResource.php index fd53f0bcef3b3..0fe6aca8c1d8d 100644 --- a/src/Symfony/Component/HttpKernel/Config/EnvParametersResource.php +++ b/src/Symfony/Component/HttpKernel/Config/EnvParametersResource.php @@ -72,7 +72,7 @@ public function serialize() public function unserialize($serialized) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $unserialized = unserialize($serialized, array('allowed_classes' => false)); } else { $unserialized = unserialize($serialized); diff --git a/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php index b638ba79059bd..b50386cb961c9 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php @@ -20,6 +20,7 @@ use Symfony\Component\VarDumper\Dumper\CliDumper; use Symfony\Component\VarDumper\Dumper\HtmlDumper; use Symfony\Component\VarDumper\Dumper\DataDumperInterface; +use Twig\Template; /** * @author Nicolas Grekas @@ -91,7 +92,7 @@ public function dump(Data $data) $line = $trace[$i]['line']; break; - } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof \Twig_Template) { + } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) { $template = $trace[$i]['object']; $name = $template->getTemplateName(); $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false); diff --git a/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php index d32c581cb6b28..7ae1fbbd61537 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php @@ -138,6 +138,9 @@ private function getContainerCompilerLogs() $logs = array(); foreach (file($file, FILE_IGNORE_NEW_LINES) as $log) { $log = explode(': ', $log, 2); + if (!isset($log[1]) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)++$/', $log[0])) { + $log = array('Unknown Compiler Pass', implode(': ', $log)); + } $logs[$log[0]][] = array('message' => $log[1]); } diff --git a/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php b/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php index 9eefba210a41b..c340d9b67200a 100644 --- a/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php +++ b/src/Symfony/Component/HttpKernel/Debug/FileLinkFormatter.php @@ -63,7 +63,7 @@ public function serialize() public function unserialize($serialized) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $this->fileLinkFormat = unserialize($serialized, array('allowed_classes' => false)); } else { $this->fileLinkFormat = unserialize($serialized); diff --git a/src/Symfony/Component/HttpKernel/DependencyInjection/AddAnnotatedClassesToCachePass.php b/src/Symfony/Component/HttpKernel/DependencyInjection/AddAnnotatedClassesToCachePass.php index 6bcc6a945ace2..9235ae4e96f08 100644 --- a/src/Symfony/Component/HttpKernel/DependencyInjection/AddAnnotatedClassesToCachePass.php +++ b/src/Symfony/Component/HttpKernel/DependencyInjection/AddAnnotatedClassesToCachePass.php @@ -40,7 +40,7 @@ public function process(ContainerBuilder $container) $annotatedClasses = array(); foreach ($container->getExtensions() as $extension) { if ($extension instanceof Extension) { - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $classes = array_merge($classes, $extension->getClassesToCompile()); } $annotatedClasses = array_merge($annotatedClasses, $extension->getAnnotatedClassesToCompile()); @@ -49,7 +49,7 @@ public function process(ContainerBuilder $container) $existingClasses = $this->getClassesInComposerClassMaps(); - if (PHP_VERSION_ID < 70000) { + if (\PHP_VERSION_ID < 70000) { $classes = $container->getParameterBag()->resolveValue($classes); $this->kernel->setClassCache($this->expandClasses($classes, $existingClasses)); } diff --git a/src/Symfony/Component/HttpKernel/DependencyInjection/Extension.php b/src/Symfony/Component/HttpKernel/DependencyInjection/Extension.php index 573e1b4e6b669..f6449f4e52312 100644 --- a/src/Symfony/Component/HttpKernel/DependencyInjection/Extension.php +++ b/src/Symfony/Component/HttpKernel/DependencyInjection/Extension.php @@ -32,7 +32,7 @@ abstract class Extension extends BaseExtension */ public function getClassesToCompile() { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED); } @@ -58,7 +58,7 @@ public function getAnnotatedClassesToCompile() */ public function addClassesToCompile(array $classes) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED); } diff --git a/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php b/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php index c163a09073b4a..ec2a40716ab72 100644 --- a/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php +++ b/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php @@ -16,6 +16,9 @@ use Symfony\Component\Templating\EngineInterface; use Symfony\Component\HttpKernel\Controller\ControllerReference; use Symfony\Component\HttpKernel\UriSigner; +use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Loader\ExistsLoaderInterface; /** * Implements the Hinclude rendering strategy. @@ -32,10 +35,10 @@ class HIncludeFragmentRenderer extends RoutableFragmentRenderer /** * Constructor. * - * @param EngineInterface|\Twig_Environment $templating An EngineInterface or a \Twig_Environment instance - * @param UriSigner $signer A UriSigner instance - * @param string $globalDefaultTemplate The global default content (it can be a template name or the content) - * @param string $charset + * @param EngineInterface|Environment $templating An EngineInterface or a Twig instance + * @param UriSigner $signer A UriSigner instance + * @param string $globalDefaultTemplate The global default content (it can be a template name or the content) + * @param string $charset */ public function __construct($templating = null, UriSigner $signer = null, $globalDefaultTemplate = null, $charset = 'utf-8') { @@ -48,14 +51,14 @@ public function __construct($templating = null, UriSigner $signer = null, $globa /** * Sets the templating engine to use to render the default content. * - * @param EngineInterface|\Twig_Environment|null $templating An EngineInterface or a \Twig_Environment instance + * @param EngineInterface|Environment|null $templating An EngineInterface or an Environment instance * * @throws \InvalidArgumentException */ public function setTemplating($templating) { - if (null !== $templating && !$templating instanceof EngineInterface && !$templating instanceof \Twig_Environment) { - throw new \InvalidArgumentException('The hinclude rendering strategy needs an instance of \Twig_Environment or Symfony\Component\Templating\EngineInterface'); + if (null !== $templating && !$templating instanceof EngineInterface && !$templating instanceof Environment) { + throw new \InvalidArgumentException('The hinclude rendering strategy needs an instance of Twig\Environment or Symfony\Component\Templating\EngineInterface'); } $this->templating = $templating; @@ -136,7 +139,7 @@ private function templateExists($template) } $loader = $this->templating->getLoader(); - if ($loader instanceof \Twig_ExistsLoaderInterface || method_exists($loader, 'exists')) { + if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { return $loader->exists($template); } @@ -148,7 +151,7 @@ private function templateExists($template) } return true; - } catch (\Twig_Error_Loader $e) { + } catch (LoaderError $e) { } return false; diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index e2f1df0351ad0..b9a95ac99dbe2 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -61,11 +61,11 @@ abstract class Kernel implements KernelInterface, TerminableInterface private $projectDir; - const VERSION = '3.3.0'; - const VERSION_ID = 30300; + const VERSION = '3.3.1'; + const VERSION_ID = 30301; const MAJOR_VERSION = 3; const MINOR_VERSION = 3; - const RELEASE_VERSION = 0; + const RELEASE_VERSION = 1; const EXTRA_VERSION = ''; const END_OF_MAINTENANCE = '01/2018'; @@ -354,7 +354,7 @@ public function getContainer() */ public function loadClassCache($name = 'classes', $extension = '.php') { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED); } @@ -368,7 +368,7 @@ public function loadClassCache($name = 'classes', $extension = '.php') */ public function setClassCache(array $classes) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED); } @@ -420,7 +420,7 @@ public function getCharset() */ protected function doLoadClassCache($name, $extension) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED); } @@ -822,7 +822,7 @@ public static function stripComments($source) $output .= $rawChunk; - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098 unset($tokens, $rawChunk); gc_mem_caches(); @@ -838,7 +838,7 @@ public function serialize() public function unserialize($data) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { list($environment, $debug) = unserialize($data, array('allowed_classes' => false)); } else { list($environment, $debug) = unserialize($data); diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/Compiler.log b/src/Symfony/Component/HttpKernel/Tests/DataCollector/Compiler.log new file mode 100644 index 0000000000000..88b6840eae8e9 --- /dev/null +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/Compiler.log @@ -0,0 +1,4 @@ +Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass: Removed service "Psr\Container\ContainerInterface"; reason: private alias. +Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass: Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias. +Some custom logging message +With ending : diff --git a/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php b/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php index 5a01ee88161e9..62bf2c00c7586 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php @@ -17,6 +17,27 @@ class LoggerDataCollectorTest extends TestCase { + public function testCollectWithUnexpectedFormat() + { + $logger = $this->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')->getMock(); + $logger->expects($this->once())->method('countErrors')->will($this->returnValue('foo')); + $logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue(array())); + + $c = new LoggerDataCollector($logger, __DIR__.'/'); + $c->lateCollect(); + $compilerLogs = $c->getCompilerLogs()->getValue('message'); + + $this->assertSame(array( + array('message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'), + array('message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'), + ), $compilerLogs['Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass']); + + $this->assertSame(array( + array('message' => 'Some custom logging message'), + array('message' => 'With ending :'), + ), $compilerLogs['Unknown Compiler Pass']); + } + /** * @dataProvider getCollectTestData */ diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php index 377b8cd3bcf21..a40e57998dee2 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php @@ -41,14 +41,14 @@ protected function setUp() public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort) { $urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $context = new RequestContext(); $context->setHttpPort($defaultHttpPort); $context->setHttpsPort($defaultHttpsPort); $urlMatcher->expects($this->any()) - ->method('getContext') - ->will($this->returnValue($context)); + ->method('getContext') + ->will($this->returnValue($context)); $listener = new RouterListener($urlMatcher, $this->requestStack); $event = $this->createGetResponseEventForUri($uri); @@ -141,13 +141,13 @@ public function testLoggingParameter($parameter, $log, $parameters) { $requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock(); $requestMatcher->expects($this->once()) - ->method('matchRequest') - ->will($this->returnValue($parameter)); + ->method('matchRequest') + ->will($this->returnValue($parameter)); $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); $logger->expects($this->once()) - ->method('info') - ->with($this->equalTo($log), $this->equalTo($parameters)); + ->method('info') + ->with($this->equalTo($log), $this->equalTo($parameters)); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); $request = Request::create('http://localhost/'); diff --git a/src/Symfony/Component/HttpKernel/composer.json b/src/Symfony/Component/HttpKernel/composer.json index a680eb05e856d..babc8663b6487 100644 --- a/src/Symfony/Component/HttpKernel/composer.json +++ b/src/Symfony/Component/HttpKernel/composer.json @@ -43,7 +43,8 @@ "conflict": { "symfony/config": "<2.8", "symfony/dependency-injection": "<3.3", - "symfony/var-dumper": "<3.3" + "symfony/var-dumper": "<3.3", + "twig/twig": "<1.34|<2.4,>=2" }, "suggest": { "symfony/browser-kit": "", diff --git a/src/Symfony/Component/Intl/Tests/DateFormatter/AbstractIntlDateFormatterTest.php b/src/Symfony/Component/Intl/Tests/DateFormatter/AbstractIntlDateFormatterTest.php index ac712b3aa5df2..b7230b8e9dc87 100644 --- a/src/Symfony/Component/Intl/Tests/DateFormatter/AbstractIntlDateFormatterTest.php +++ b/src/Symfony/Component/Intl/Tests/DateFormatter/AbstractIntlDateFormatterTest.php @@ -435,7 +435,7 @@ public function testFormatWithDateTimeZoneGmt() public function testFormatWithDateTimeZoneGmtOffset() { - if (defined('HHVM_VERSION_ID') || PHP_VERSION_ID <= 50509) { + if (defined('HHVM_VERSION_ID') || \PHP_VERSION_ID <= 50509) { $this->markTestSkipped('DateTimeZone GMT offsets are supported since 5.5.10. See https://github.com/facebook/hhvm/issues/5875 for HHVM.'); } diff --git a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php index 6019544a19e8c..69d7fc0e9f1aa 100644 --- a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php +++ b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php @@ -195,7 +195,7 @@ public function setValue(&$objectOrArray, $propertyPath, $value) $overwrite = true; try { - if (PHP_VERSION_ID < 70000 && false === self::$previousErrorHandler) { + if (\PHP_VERSION_ID < 70000 && false === self::$previousErrorHandler) { self::$previousErrorHandler = set_error_handler(self::$errorHandler); } @@ -245,7 +245,7 @@ public function setValue(&$objectOrArray, $propertyPath, $value) } catch (\TypeError $e) { self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0); } finally { - if (PHP_VERSION_ID < 70000 && false !== self::$previousErrorHandler) { + if (\PHP_VERSION_ID < 70000 && false !== self::$previousErrorHandler) { restore_error_handler(); self::$previousErrorHandler = false; } diff --git a/src/Symfony/Component/Routing/CompiledRoute.php b/src/Symfony/Component/Routing/CompiledRoute.php index a3cbdd056f37c..f52e3aa06ee35 100644 --- a/src/Symfony/Component/Routing/CompiledRoute.php +++ b/src/Symfony/Component/Routing/CompiledRoute.php @@ -73,7 +73,7 @@ public function serialize() */ public function unserialize($serialized) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $data = unserialize($serialized, array('allowed_classes' => false)); } else { $data = unserialize($serialized); diff --git a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php index 4dc41e16cd392..22edc86713765 100644 --- a/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/AnnotationFileLoader.php @@ -64,7 +64,7 @@ public function load($file, $type = null) $collection->addResource(new FileResource($path)); $collection->addCollection($this->loader->load($class, $type)); } - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098 gc_mem_caches(); } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php index 7f0d0520b938f..8eae68c4c280e 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php @@ -238,7 +238,7 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren $hostMatches = false; $methods = $route->getMethods(); - $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods)); + $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods) || in_array('GET', $methods)); $regex = $compiledRoute->getRegex(); if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P.*?)\$\1#'.(substr($regex, -1) === 'u' ? 'u' : ''), $regex, $m)) { diff --git a/src/Symfony/Component/Routing/Route.php b/src/Symfony/Component/Routing/Route.php index 137d97548d20d..34b1b75765dc6 100644 --- a/src/Symfony/Component/Routing/Route.php +++ b/src/Symfony/Component/Routing/Route.php @@ -116,7 +116,7 @@ public function serialize() */ public function unserialize($serialized) { - if (PHP_VERSION_ID >= 70000) { + if (\PHP_VERSION_ID >= 70000) { $data = unserialize($serialized, array('allowed_classes' => array(CompiledRoute::class))); } else { $data = unserialize($serialized); diff --git a/src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher6.php b/src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher6.php new file mode 100644 index 0000000000000..c7645521f5a6e --- /dev/null +++ b/src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher6.php @@ -0,0 +1,204 @@ +context = $context; + } + + public function match($pathinfo) + { + $allow = array(); + $pathinfo = rawurldecode($pathinfo); + $trimmedPathinfo = rtrim($pathinfo, '/'); + $context = $this->context; + $request = $this->request; + $requestMethod = $canonicalMethod = $context->getMethod(); + $scheme = $context->getScheme(); + + if ('HEAD' === $requestMethod) { + $canonicalMethod = 'GET'; + } + + + if (0 === strpos($pathinfo, '/trailing/simple')) { + // simple_trailing_slash_no_methods + if ('/trailing/simple/no-methods/' === $pathinfo) { + return array('_route' => 'simple_trailing_slash_no_methods'); + } + + // simple_trailing_slash_GET_method + if ('/trailing/simple/get-method/' === $pathinfo) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_simple_trailing_slash_GET_method; + } + + return array('_route' => 'simple_trailing_slash_GET_method'); + } + not_simple_trailing_slash_GET_method: + + // simple_trailing_slash_HEAD_method + if ('/trailing/simple/head-method/' === $pathinfo) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_simple_trailing_slash_HEAD_method; + } + + return array('_route' => 'simple_trailing_slash_HEAD_method'); + } + not_simple_trailing_slash_HEAD_method: + + // simple_trailing_slash_POST_method + if ('/trailing/simple/post-method/' === $pathinfo) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_simple_trailing_slash_POST_method; + } + + return array('_route' => 'simple_trailing_slash_POST_method'); + } + not_simple_trailing_slash_POST_method: + + } + + elseif (0 === strpos($pathinfo, '/trailing/regex')) { + // regex_trailing_slash_no_methods + if (0 === strpos($pathinfo, '/trailing/regex/no-methods') && preg_match('#^/trailing/regex/no\\-methods/(?P[^/]++)/$#s', $pathinfo, $matches)) { + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_no_methods')), array ()); + } + + // regex_trailing_slash_GET_method + if (0 === strpos($pathinfo, '/trailing/regex/get-method') && preg_match('#^/trailing/regex/get\\-method/(?P[^/]++)/$#s', $pathinfo, $matches)) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_regex_trailing_slash_GET_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_GET_method')), array ()); + } + not_regex_trailing_slash_GET_method: + + // regex_trailing_slash_HEAD_method + if (0 === strpos($pathinfo, '/trailing/regex/head-method') && preg_match('#^/trailing/regex/head\\-method/(?P[^/]++)/$#s', $pathinfo, $matches)) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_regex_trailing_slash_HEAD_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_HEAD_method')), array ()); + } + not_regex_trailing_slash_HEAD_method: + + // regex_trailing_slash_POST_method + if (0 === strpos($pathinfo, '/trailing/regex/post-method') && preg_match('#^/trailing/regex/post\\-method/(?P[^/]++)/$#s', $pathinfo, $matches)) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_regex_trailing_slash_POST_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_POST_method')), array ()); + } + not_regex_trailing_slash_POST_method: + + } + + elseif (0 === strpos($pathinfo, '/not-trailing/simple')) { + // simple_not_trailing_slash_no_methods + if ('/not-trailing/simple/no-methods' === $pathinfo) { + return array('_route' => 'simple_not_trailing_slash_no_methods'); + } + + // simple_not_trailing_slash_GET_method + if ('/not-trailing/simple/get-method' === $pathinfo) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_simple_not_trailing_slash_GET_method; + } + + return array('_route' => 'simple_not_trailing_slash_GET_method'); + } + not_simple_not_trailing_slash_GET_method: + + // simple_not_trailing_slash_HEAD_method + if ('/not-trailing/simple/head-method' === $pathinfo) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_simple_not_trailing_slash_HEAD_method; + } + + return array('_route' => 'simple_not_trailing_slash_HEAD_method'); + } + not_simple_not_trailing_slash_HEAD_method: + + // simple_not_trailing_slash_POST_method + if ('/not-trailing/simple/post-method' === $pathinfo) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_simple_not_trailing_slash_POST_method; + } + + return array('_route' => 'simple_not_trailing_slash_POST_method'); + } + not_simple_not_trailing_slash_POST_method: + + } + + elseif (0 === strpos($pathinfo, '/not-trailing/regex')) { + // regex_not_trailing_slash_no_methods + if (0 === strpos($pathinfo, '/not-trailing/regex/no-methods') && preg_match('#^/not\\-trailing/regex/no\\-methods/(?P[^/]++)$#s', $pathinfo, $matches)) { + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_no_methods')), array ()); + } + + // regex_not_trailing_slash_GET_method + if (0 === strpos($pathinfo, '/not-trailing/regex/get-method') && preg_match('#^/not\\-trailing/regex/get\\-method/(?P[^/]++)$#s', $pathinfo, $matches)) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_regex_not_trailing_slash_GET_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_GET_method')), array ()); + } + not_regex_not_trailing_slash_GET_method: + + // regex_not_trailing_slash_HEAD_method + if (0 === strpos($pathinfo, '/not-trailing/regex/head-method') && preg_match('#^/not\\-trailing/regex/head\\-method/(?P[^/]++)$#s', $pathinfo, $matches)) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_regex_not_trailing_slash_HEAD_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_HEAD_method')), array ()); + } + not_regex_not_trailing_slash_HEAD_method: + + // regex_not_trailing_slash_POST_method + if (0 === strpos($pathinfo, '/not-trailing/regex/post-method') && preg_match('#^/not\\-trailing/regex/post\\-method/(?P[^/]++)$#s', $pathinfo, $matches)) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_regex_not_trailing_slash_POST_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_POST_method')), array ()); + } + not_regex_not_trailing_slash_POST_method: + + } + + throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); + } +} diff --git a/src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher7.php b/src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher7.php new file mode 100644 index 0000000000000..876a90f2da468 --- /dev/null +++ b/src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher7.php @@ -0,0 +1,228 @@ +context = $context; + } + + public function match($pathinfo) + { + $allow = array(); + $pathinfo = rawurldecode($pathinfo); + $trimmedPathinfo = rtrim($pathinfo, '/'); + $context = $this->context; + $request = $this->request; + $requestMethod = $canonicalMethod = $context->getMethod(); + $scheme = $context->getScheme(); + + if ('HEAD' === $requestMethod) { + $canonicalMethod = 'GET'; + } + + + if (0 === strpos($pathinfo, '/trailing/simple')) { + // simple_trailing_slash_no_methods + if ('/trailing/simple/no-methods' === $trimmedPathinfo) { + if (substr($pathinfo, -1) !== '/') { + return $this->redirect($pathinfo.'/', 'simple_trailing_slash_no_methods'); + } + + return array('_route' => 'simple_trailing_slash_no_methods'); + } + + // simple_trailing_slash_GET_method + if ('/trailing/simple/get-method' === $trimmedPathinfo) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_simple_trailing_slash_GET_method; + } + + if (substr($pathinfo, -1) !== '/') { + return $this->redirect($pathinfo.'/', 'simple_trailing_slash_GET_method'); + } + + return array('_route' => 'simple_trailing_slash_GET_method'); + } + not_simple_trailing_slash_GET_method: + + // simple_trailing_slash_HEAD_method + if ('/trailing/simple/head-method' === $trimmedPathinfo) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_simple_trailing_slash_HEAD_method; + } + + if (substr($pathinfo, -1) !== '/') { + return $this->redirect($pathinfo.'/', 'simple_trailing_slash_HEAD_method'); + } + + return array('_route' => 'simple_trailing_slash_HEAD_method'); + } + not_simple_trailing_slash_HEAD_method: + + // simple_trailing_slash_POST_method + if ('/trailing/simple/post-method/' === $pathinfo) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_simple_trailing_slash_POST_method; + } + + return array('_route' => 'simple_trailing_slash_POST_method'); + } + not_simple_trailing_slash_POST_method: + + } + + elseif (0 === strpos($pathinfo, '/trailing/regex')) { + // regex_trailing_slash_no_methods + if (0 === strpos($pathinfo, '/trailing/regex/no-methods') && preg_match('#^/trailing/regex/no\\-methods/(?P[^/]++)/?$#s', $pathinfo, $matches)) { + if (substr($pathinfo, -1) !== '/') { + return $this->redirect($pathinfo.'/', 'regex_trailing_slash_no_methods'); + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_no_methods')), array ()); + } + + // regex_trailing_slash_GET_method + if (0 === strpos($pathinfo, '/trailing/regex/get-method') && preg_match('#^/trailing/regex/get\\-method/(?P[^/]++)/?$#s', $pathinfo, $matches)) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_regex_trailing_slash_GET_method; + } + + if (substr($pathinfo, -1) !== '/') { + return $this->redirect($pathinfo.'/', 'regex_trailing_slash_GET_method'); + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_GET_method')), array ()); + } + not_regex_trailing_slash_GET_method: + + // regex_trailing_slash_HEAD_method + if (0 === strpos($pathinfo, '/trailing/regex/head-method') && preg_match('#^/trailing/regex/head\\-method/(?P[^/]++)/?$#s', $pathinfo, $matches)) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_regex_trailing_slash_HEAD_method; + } + + if (substr($pathinfo, -1) !== '/') { + return $this->redirect($pathinfo.'/', 'regex_trailing_slash_HEAD_method'); + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_HEAD_method')), array ()); + } + not_regex_trailing_slash_HEAD_method: + + // regex_trailing_slash_POST_method + if (0 === strpos($pathinfo, '/trailing/regex/post-method') && preg_match('#^/trailing/regex/post\\-method/(?P[^/]++)/$#s', $pathinfo, $matches)) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_regex_trailing_slash_POST_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_trailing_slash_POST_method')), array ()); + } + not_regex_trailing_slash_POST_method: + + } + + elseif (0 === strpos($pathinfo, '/not-trailing/simple')) { + // simple_not_trailing_slash_no_methods + if ('/not-trailing/simple/no-methods' === $pathinfo) { + return array('_route' => 'simple_not_trailing_slash_no_methods'); + } + + // simple_not_trailing_slash_GET_method + if ('/not-trailing/simple/get-method' === $pathinfo) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_simple_not_trailing_slash_GET_method; + } + + return array('_route' => 'simple_not_trailing_slash_GET_method'); + } + not_simple_not_trailing_slash_GET_method: + + // simple_not_trailing_slash_HEAD_method + if ('/not-trailing/simple/head-method' === $pathinfo) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_simple_not_trailing_slash_HEAD_method; + } + + return array('_route' => 'simple_not_trailing_slash_HEAD_method'); + } + not_simple_not_trailing_slash_HEAD_method: + + // simple_not_trailing_slash_POST_method + if ('/not-trailing/simple/post-method' === $pathinfo) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_simple_not_trailing_slash_POST_method; + } + + return array('_route' => 'simple_not_trailing_slash_POST_method'); + } + not_simple_not_trailing_slash_POST_method: + + } + + elseif (0 === strpos($pathinfo, '/not-trailing/regex')) { + // regex_not_trailing_slash_no_methods + if (0 === strpos($pathinfo, '/not-trailing/regex/no-methods') && preg_match('#^/not\\-trailing/regex/no\\-methods/(?P[^/]++)$#s', $pathinfo, $matches)) { + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_no_methods')), array ()); + } + + // regex_not_trailing_slash_GET_method + if (0 === strpos($pathinfo, '/not-trailing/regex/get-method') && preg_match('#^/not\\-trailing/regex/get\\-method/(?P[^/]++)$#s', $pathinfo, $matches)) { + if ('GET' !== $canonicalMethod) { + $allow[] = 'GET'; + goto not_regex_not_trailing_slash_GET_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_GET_method')), array ()); + } + not_regex_not_trailing_slash_GET_method: + + // regex_not_trailing_slash_HEAD_method + if (0 === strpos($pathinfo, '/not-trailing/regex/head-method') && preg_match('#^/not\\-trailing/regex/head\\-method/(?P[^/]++)$#s', $pathinfo, $matches)) { + if ('HEAD' !== $requestMethod) { + $allow[] = 'HEAD'; + goto not_regex_not_trailing_slash_HEAD_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_HEAD_method')), array ()); + } + not_regex_not_trailing_slash_HEAD_method: + + // regex_not_trailing_slash_POST_method + if (0 === strpos($pathinfo, '/not-trailing/regex/post-method') && preg_match('#^/not\\-trailing/regex/post\\-method/(?P[^/]++)$#s', $pathinfo, $matches)) { + if ('POST' !== $canonicalMethod) { + $allow[] = 'POST'; + goto not_regex_not_trailing_slash_POST_method; + } + + return $this->mergeDefaults(array_replace($matches, array('_route' => 'regex_not_trailing_slash_POST_method')), array ()); + } + not_regex_not_trailing_slash_POST_method: + + } + + throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); + } +} diff --git a/src/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php b/src/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php index e26b48e78d1f5..9d4f086be7702 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php @@ -345,12 +345,33 @@ public function getRouteCollections() $groupOptimisedCollection->add('slashed_b', new Route('/slashed/group/b/')); $groupOptimisedCollection->add('slashed_c', new Route('/slashed/group/c/')); + $trailingSlashCollection = new RouteCollection(); + $trailingSlashCollection->add('simple_trailing_slash_no_methods', new Route('/trailing/simple/no-methods/', array(), array(), array(), '', array(), array())); + $trailingSlashCollection->add('simple_trailing_slash_GET_method', new Route('/trailing/simple/get-method/', array(), array(), array(), '', array(), array('GET'))); + $trailingSlashCollection->add('simple_trailing_slash_HEAD_method', new Route('/trailing/simple/head-method/', array(), array(), array(), '', array(), array('HEAD'))); + $trailingSlashCollection->add('simple_trailing_slash_POST_method', new Route('/trailing/simple/post-method/', array(), array(), array(), '', array(), array('POST'))); + $trailingSlashCollection->add('regex_trailing_slash_no_methods', new Route('/trailing/regex/no-methods/{param}/', array(), array(), array(), '', array(), array())); + $trailingSlashCollection->add('regex_trailing_slash_GET_method', new Route('/trailing/regex/get-method/{param}/', array(), array(), array(), '', array(), array('GET'))); + $trailingSlashCollection->add('regex_trailing_slash_HEAD_method', new Route('/trailing/regex/head-method/{param}/', array(), array(), array(), '', array(), array('HEAD'))); + $trailingSlashCollection->add('regex_trailing_slash_POST_method', new Route('/trailing/regex/post-method/{param}/', array(), array(), array(), '', array(), array('POST'))); + + $trailingSlashCollection->add('simple_not_trailing_slash_no_methods', new Route('/not-trailing/simple/no-methods', array(), array(), array(), '', array(), array())); + $trailingSlashCollection->add('simple_not_trailing_slash_GET_method', new Route('/not-trailing/simple/get-method', array(), array(), array(), '', array(), array('GET'))); + $trailingSlashCollection->add('simple_not_trailing_slash_HEAD_method', new Route('/not-trailing/simple/head-method', array(), array(), array(), '', array(), array('HEAD'))); + $trailingSlashCollection->add('simple_not_trailing_slash_POST_method', new Route('/not-trailing/simple/post-method', array(), array(), array(), '', array(), array('POST'))); + $trailingSlashCollection->add('regex_not_trailing_slash_no_methods', new Route('/not-trailing/regex/no-methods/{param}', array(), array(), array(), '', array(), array())); + $trailingSlashCollection->add('regex_not_trailing_slash_GET_method', new Route('/not-trailing/regex/get-method/{param}', array(), array(), array(), '', array(), array('GET'))); + $trailingSlashCollection->add('regex_not_trailing_slash_HEAD_method', new Route('/not-trailing/regex/head-method/{param}', array(), array(), array(), '', array(), array('HEAD'))); + $trailingSlashCollection->add('regex_not_trailing_slash_POST_method', new Route('/not-trailing/regex/post-method/{param}', array(), array(), array(), '', array(), array('POST'))); + return array( array($collection, 'url_matcher1.php', array()), array($redirectCollection, 'url_matcher2.php', array('base_class' => 'Symfony\Component\Routing\Tests\Fixtures\RedirectableUrlMatcher')), array($rootprefixCollection, 'url_matcher3.php', array()), array($headMatchCasesCollection, 'url_matcher4.php', array()), array($groupOptimisedCollection, 'url_matcher5.php', array('base_class' => 'Symfony\Component\Routing\Tests\Fixtures\RedirectableUrlMatcher')), + array($trailingSlashCollection, 'url_matcher6.php', array()), + array($trailingSlashCollection, 'url_matcher7.php', array('base_class' => 'Symfony\Component\Routing\Tests\Fixtures\RedirectableUrlMatcher')), ); } } diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php index 0eee6d94a41c6..82e7fa672fdd8 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php @@ -43,7 +43,7 @@ public function __construct(array $roles = array()) if (is_string($role)) { $role = new Role($role); } elseif (!$role instanceof RoleInterface) { - throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, or RoleInterface instances, but got %s.', gettype($role))); + throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, Role instances or RoleInterface instances, but got %s.', gettype($role))); } $this->roles[] = $role; diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php index 49a8b5256d0b6..0d28b0a399e48 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.php @@ -23,13 +23,13 @@ public function testAllLoadersAreCalled() $loader1 = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $loader1->expects($this->once()) - ->method('loadClassMetadata') - ->with($this->equalTo($metadata)); + ->method('loadClassMetadata') + ->with($this->equalTo($metadata)); $loader2 = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $loader2->expects($this->once()) - ->method('loadClassMetadata') - ->with($this->equalTo($metadata)); + ->method('loadClassMetadata') + ->with($this->equalTo($metadata)); $chain = new LoaderChain(array( $loader1, @@ -45,13 +45,13 @@ public function testReturnsTrueIfAnyLoaderReturnedTrue() $loader1 = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $loader1->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(true)); + ->method('loadClassMetadata') + ->will($this->returnValue(true)); $loader2 = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $loader2->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(false)); + ->method('loadClassMetadata') + ->will($this->returnValue(false)); $chain = new LoaderChain(array( $loader1, @@ -67,13 +67,13 @@ public function testReturnsFalseIfNoLoaderReturnedTrue() $loader1 = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $loader1->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(false)); + ->method('loadClassMetadata') + ->will($this->returnValue(false)); $loader2 = $this->getMockBuilder('Symfony\Component\Validator\Mapping\Loader\LoaderInterface')->getMock(); $loader2->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(false)); + ->method('loadClassMetadata') + ->will($this->returnValue(false)); $chain = new LoaderChain(array( $loader1, diff --git a/src/Symfony/Component/VarDumper/Caster/ClassStub.php b/src/Symfony/Component/VarDumper/Caster/ClassStub.php index 51990bc356c0d..4765174d08670 100644 --- a/src/Symfony/Component/VarDumper/Caster/ClassStub.php +++ b/src/Symfony/Component/VarDumper/Caster/ClassStub.php @@ -38,10 +38,6 @@ public function __construct($identifier, $callable = null) if (null !== $callable) { if ($callable instanceof \Closure) { $r = new \ReflectionFunction($callable); - - if (preg_match('#^/\*\* @closure-proxy ([^: ]++)::([^: ]++) \*/$#', $r->getDocComment(), $m)) { - $r = array($m[1], $m[2]); - } } elseif (is_object($callable)) { $r = array($callable, '__invoke'); } elseif (is_array($callable)) { diff --git a/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php b/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php index e2a4200c52503..f52972a0efea2 100644 --- a/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php @@ -198,7 +198,7 @@ public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, $is $ellipsis = isset($ellipsis['ellipsis']) ? $ellipsis['ellipsis'] : 0; if (file_exists($f['file']) && 0 <= self::$srcContext) { - if (!empty($f['class']) && is_subclass_of($f['class'], 'Twig_Template') && method_exists($f['class'], 'getDebugInfo')) { + if (!empty($f['class']) && (is_subclass_of($f['class'], 'Twig\Template') || is_subclass_of($f['class'], 'Twig_Template')) && method_exists($f['class'], 'getDebugInfo')) { $template = isset($f['object']) ? $f['object'] : unserialize(sprintf('O:%d:"%s":0:{}', strlen($f['class']), $f['class'])); $ellipsis = 0; diff --git a/src/Symfony/Component/VarDumper/Tests/Caster/ExceptionCasterTest.php b/src/Symfony/Component/VarDumper/Tests/Caster/ExceptionCasterTest.php index 94ad5fe0997ff..3f6a2e8ec3ff1 100644 --- a/src/Symfony/Component/VarDumper/Tests/Caster/ExceptionCasterTest.php +++ b/src/Symfony/Component/VarDumper/Tests/Caster/ExceptionCasterTest.php @@ -171,7 +171,7 @@ public function testHtmlDump() } /** - * @requires function Twig_Template::getSourceContext + * @requires function Twig\Template::getSourceContext */ public function testFrameWithTwig() { diff --git a/src/Symfony/Component/VarDumper/Tests/Dumper/CliDumperTest.php b/src/Symfony/Component/VarDumper/Tests/Dumper/CliDumperTest.php index 37d2bc87b1031..c4348dfa57f7f 100644 --- a/src/Symfony/Component/VarDumper/Tests/Dumper/CliDumperTest.php +++ b/src/Symfony/Component/VarDumper/Tests/Dumper/CliDumperTest.php @@ -15,6 +15,8 @@ use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\CliDumper; use Symfony\Component\VarDumper\Test\VarDumperTestTrait; +use Twig\Environment; +use Twig\Loader\FilesystemLoader; /** * @author Nicolas Grekas @@ -291,14 +293,14 @@ public function testFlags() } /** - * @requires function Twig_Template::getSourceContext + * @requires function Twig\Template::getSourceContext */ public function testThrowingCaster() { $out = fopen('php://memory', 'r+b'); require_once __DIR__.'/../Fixtures/Twig.php'; - $twig = new \__TwigTemplate_VarDumperFixture_u75a09(new \Twig_Environment(new \Twig_Loader_Filesystem())); + $twig = new \__TwigTemplate_VarDumperFixture_u75a09(new Environment(new FilesystemLoader())); $dumper = new CliDumper(); $dumper->setColors(false); @@ -314,7 +316,7 @@ public function testThrowingCaster() ':stream' => eval('return function () use ($twig) { try { $twig->render(array()); - } catch (\Twig_Error_Runtime $e) { + } catch (\Twig\Error\RuntimeError $e) { throw $e->getPrevious(); } };'), @@ -340,7 +342,7 @@ public function testThrowingCaster() %sTemplate.php:%d: { : try { : \$this->doDisplay(\$context, \$blocks); - : } catch (Twig_Error \$e) { + : } catch (Twig%sError \$e) { } %sTemplate.php:%d: { : { @@ -476,7 +478,7 @@ public function testGlobalsNoExt() */ public function testBuggyRefs() { - if (PHP_VERSION_ID >= 50600) { + if (\PHP_VERSION_ID >= 50600) { $this->markTestSkipped('PHP 5.6 fixed refs counting'); } diff --git a/src/Symfony/Component/VarDumper/Tests/Fixtures/Twig.php b/src/Symfony/Component/VarDumper/Tests/Fixtures/Twig.php index bf64d85c1e920..fe2542929b100 100644 --- a/src/Symfony/Component/VarDumper/Tests/Fixtures/Twig.php +++ b/src/Symfony/Component/VarDumper/Tests/Fixtures/Twig.php @@ -1,11 +1,11 @@ path ?: __FILE__); + return new Twig\Source(" foo bar\n twig source\n\n", 'foo.twig', $this->path ?: __FILE__); } } diff --git a/src/Symfony/Component/VarDumper/composer.json b/src/Symfony/Component/VarDumper/composer.json index 464462663eca2..930896026ae53 100644 --- a/src/Symfony/Component/VarDumper/composer.json +++ b/src/Symfony/Component/VarDumper/composer.json @@ -21,7 +21,7 @@ }, "require-dev": { "ext-iconv": "*", - "twig/twig": "~1.20|~2.0" + "twig/twig": "~1.34|~2.4" }, "conflict": { "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0" diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php index 42f61af9de0a4..4a5f2b91e06bf 100644 --- a/src/Symfony/Component/Yaml/Parser.php +++ b/src/Symfony/Component/Yaml/Parser.php @@ -237,7 +237,8 @@ private function doParse($value, $flags) } if (!(Yaml::PARSE_KEYS_AS_STRINGS & $flags) && !is_string($key)) { - @trigger_error('Implicit casting of incompatible mapping keys to strings is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Pass the PARSE_KEYS_AS_STRING flag to explicitly enable the type casts.', E_USER_DEPRECATED); + $keyType = is_numeric($key) ? 'numeric key' : 'incompatible key type'; + @trigger_error(sprintf('Implicit casting of %s to string on line %d is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Pass the PARSE_KEYS_AS_STRING flag to explicitly enable the type casts.', $keyType, $this->getRealCurrentLineNb()), E_USER_DEPRECATED); } // Convert float keys to strings, to avoid being converted to integers by PHP diff --git a/src/Symfony/Component/Yaml/Tests/InlineTest.php b/src/Symfony/Component/Yaml/Tests/InlineTest.php index 5b16a532635d9..647904a91632b 100644 --- a/src/Symfony/Component/Yaml/Tests/InlineTest.php +++ b/src/Symfony/Component/Yaml/Tests/InlineTest.php @@ -575,7 +575,7 @@ public function testParseTimestampAsDateTimeObject($yaml, $year, $month, $day, $ $expected->setTimeZone(new \DateTimeZone('UTC')); $expected->setDate($year, $month, $day); - if (PHP_VERSION_ID >= 70100) { + if (\PHP_VERSION_ID >= 70100) { $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second)); } else { $expected->setTime($hour, $minute, $second); @@ -604,7 +604,7 @@ public function testParseNestedTimestampListAsDateTimeObject($yaml, $year, $mont $expected = new \DateTime($yaml); $expected->setTimeZone(new \DateTimeZone('UTC')); $expected->setDate($year, $month, $day); - if (PHP_VERSION_ID >= 70100) { + if (\PHP_VERSION_ID >= 70100) { $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second)); } else { $expected->setTime($hour, $minute, $second); diff --git a/src/Symfony/Component/Yaml/Tests/ParserTest.php b/src/Symfony/Component/Yaml/Tests/ParserTest.php index a0bef9d528c81..a6c7b6ad12aff 100644 --- a/src/Symfony/Component/Yaml/Tests/ParserTest.php +++ b/src/Symfony/Component/Yaml/Tests/ParserTest.php @@ -1081,7 +1081,7 @@ public function testYamlDirective() /** * @group legacy - * @expectedDeprecation Implicit casting of incompatible mapping keys to strings is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Pass the PARSE_KEYS_AS_STRING flag to explicitly enable the type casts. + * @expectedDeprecation Implicit casting of numeric key to string on line 1 is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Pass the PARSE_KEYS_AS_STRING flag to explicitly enable the type casts. */ public function testFloatKeys() { @@ -1103,7 +1103,7 @@ public function testFloatKeys() /** * @group legacy - * @expectedDeprecation Implicit casting of incompatible mapping keys to strings is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Pass the PARSE_KEYS_AS_STRING flag to explicitly enable the type casts. + * @expectedDeprecation Implicit casting of incompatible key type to string on line 1 is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Pass the PARSE_KEYS_AS_STRING flag to explicitly enable the type casts. */ public function testBooleanKeys() {