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 de1e0fd980928..5542e4160d1c3 100644 --- a/CHANGELOG-3.2.md +++ b/CHANGELOG-3.2.md @@ -7,6 +7,58 @@ 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.10 (2017-07-04) + + * bug #23366 [FrameworkBundle] Don't get() private services from debug:router (chalasr) + * bug #23341 [DoctrineBridge][Security][Validator] do not validate empty values (xabbuh) + * bug #23274 Display a better error design when the toolbar cannot be displayed (yceruto) + * bug #23296 [WebProfilerBundle] Fix css trick used for offsetting html anchor from fixed header (ogizanagi) + * bug #23333 [PropertyAccess] Fix TypeError discard (dunglas) + * bug #23326 [Cache] fix cleanup of expired items for PdoAdapter (dmaicher) + * bug #23345 [Console] fix description of INF default values (xabbuh) + * bug #23299 [Workflow] Added more events to the announce function (Nyholm) + * bug #23279 Don't call count on non countable object (pierredup) + * bug #23283 [TwigBundle] add back exception check (xabbuh) + * bug #23268 Show exception is checked twice in ExceptionController of twig (gmponos) + * bug #23266 Display a better error message when the toolbar cannot be displayed (javiereguiluz) + * bug #23271 [FrameworkBundle] allow SSI fragments configuration in XML files (xabbuh) + * bug #23254 [Form][TwigBridge] render hidden _method field in form_rest() (xabbuh) + * bug #23250 [Translation] return fallback locales whenever possible (xabbuh) + * bug #23240 [Console] Fix catching exception type in QuestionHelper (voronkovich) + * bug #23229 [WebProfilerBundle] Eliminate line wrap on count column (routing) (e-moe) + * bug #22732 [Security] fix switch user _exit without having current token (dmaicher) + * bug #22730 [FrameworkBundle] Sessions: configurable "use_strict_mode" option for NativeSessionStorage (MacDada) + * bug #23195 [FrameworkBundle] [Command] Clean bundle directory, fixes #23177 (NicolasPion) + * bug #23052 [TwigBundle] Add Content-Type header for exception response (rchoquet) + * bug #23199 Reset redirectCount when throwing exception (hvanoch) + * bug #23186 [TwigBundle] Move template.xml loading to a compiler pass (ogizanagi) + * bug #23130 Keep s-maxage when expiry and validation are used in combination (mpdude) + * bug #23129 Fix two edge cases in ResponseCacheStrategy (mpdude) + * feature #22636 [Routing] Expose request in route conditions, if needed and possible (ro0NL) + * bug #22636 [Routing] Expose request in route conditions, if needed and possible (ro0NL) + * bug #22943 [SecurityBundle] Move cache of the firewall context into the request parameters (GromNaN) + * bug #23057 [Translation][FrameworkBundle] Fix resource loading order inconsistency reported in #23034 (mpdude) + * bug #23092 [Filesystem] added workaround in Filesystem::rename for PHP bug (VolCh) + * bug #23128 [HttpFoundation] fix for Support for new 7.1 session options (vincentaubert) + * bug #23176 [VarDumper] fixes (nicolas-grekas) + * bug #23100 [PropertyAccess] Do not silence TypeErrors from client code. (tsufeki) + * bug #23156 [PropertyAccess] Fix Usage with anonymous classes (mablae) + * bug #23091 [Cache] ApcuAdapter::isSupported() should return true when apc.enable_cli=Off (nicolas-grekas) + * bug #22953 #22839 - changed debug toolbar dump section to relative and use full window width (mkurzeja) + * bug #23086 [FrameworkBundle] Fix perf issue in CacheClearCommand::warmup() (nicolas-grekas) + * bug #23098 Cache ipCheck (2.7) (gonzalovilaseca) + * bug #23069 [SecurityBundle] Show unique Inherited roles in profile panel (yceruto) + * bug #23073 [TwigBridge] Fix namespaced classes (ogizanagi) + * bug #23063 [Cache] Fix extensibility of TagAwareAdapter::TAGS_PREFIX (wucdbm) + * bug #22936 [Form] Mix attr option between guessed options and user options (yceruto) + * bug #22976 [DependencyInjection] Use more clear message when unused environment variables detected (voronkovich) + * bug #23045 [Cache] fix Redis scheme detection (xabbuh) + * 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) + * bug #23024 [EventDispatcher] Fix ContainerAwareEventDispatcher::hasListeners(null) (nicolas-grekas) + * bug #22996 [Form] Fix \IntlDateFormatter timezone parameter usage to bypass PHP bug #66323 (romainneutron) + * bug #22994 Harden the debugging of Twig filters and functions (stof) + * 3.2.9 (2017-05-29) * bug #22847 [Console] ChoiceQuestion must have choices (ro0NL) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c543c10dc0336..2ea3ea63b87fd 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -20,24 +20,24 @@ Symfony is the result of the work of many people who made the code better - Javier Eguiluz (javier.eguiluz) - Hugo Hamon (hhamon) - Abdellatif Ait boudad (aitboudad) + - Romain Neutron (romain) - Pascal Borreli (pborreli) - Wouter De Jong (wouterj) - - Romain Neutron (romain) + - Robin Chalas (chalas_r) + - Maxime Steinhausser (ogizanagi) - Grégoire Pineau (lyrixx) - Joseph Bielawski (stloyd) - 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,25 +64,25 @@ 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) - Dariusz Górecki (canni) - Titouan Galopin (tgalopin) - Douglas Greenshields (shieldo) - - Konstantin Myakshin (koc) - Jáchym Toušek (enumag) + - Konstantin Myakshin (koc) - 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) @@ -112,6 +112,7 @@ Symfony is the result of the work of many people who made the code better - Jacob Dreesen (jdreesen) - Tobias Nyholm (tobias) - Tomáš Votruba (tomas_votruba) + - Yonel Ceruto González (yonelceruto) - Fabien Pennequin (fabienpennequin) - Gordon Franke (gimler) - Eric GELOEN (gelo) @@ -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) @@ -130,6 +130,7 @@ Symfony is the result of the work of many people who made the code better - Daniel Gomes (danielcsgomes) - Hidenori Goto (hidenorigoto) - Guilherme Blanco (guilhermeblanco) + - Vincent AUBERT (vincent) - Pablo Godel (pgodel) - Jérémie Augustin (jaugustin) - Andréia Bohner (andreia) @@ -140,10 +141,10 @@ Symfony is the result of the work of many people who made the code better - Joel Wurtz (brouznouf) - Philipp Wahala (hifi) - Vyacheslav Pavlov + - Richard van Laak (rvanlaak) - Javier Spagnoletti (phansys) - Richard Shank (iampersistent) - Thomas Rabaix (rande) - - Vincent AUBERT (vincent) - Rouven Weßling (realityking) - Teoh Han Hui (teohhanhui) - Jérôme Vasseur (jvasseur) @@ -151,12 +152,12 @@ Symfony is the result of the work of many people who made the code better - Helmer Aaviksoo - Grégoire Paris (greg0ire) - Hiromi Hishida (77web) - - Richard van Laak (rvanlaak) - Matthieu Ouellette-Vachon (maoueh) - Michał Pipa (michal.pipa) - 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 @@ -243,6 +244,7 @@ Symfony is the result of the work of many people who made the code better - Uwe Jäger (uwej711) - Eugene Leonovich (rybakit) - Filippo Tessarotto + - Oleg Voronkovich - Joseph Rouff (rouffj) - Félix Labrecque (woodspire) - GordonsLondon @@ -254,6 +256,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,12 +275,11 @@ 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) - - Oleg Voronkovich - Manuel Kiessling (manuelkiessling) - Atsuhiro KUBO (iteman) - Andrew Moore (finewolf) @@ -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,9 +387,9 @@ 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 + - Frank de Jonge (frenkynet) - Michel Salib (michelsalib) - geoffrey - Steffen Roßkamp @@ -402,6 +404,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 +423,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 @@ -524,7 +526,6 @@ Symfony is the result of the work of many people who made the code better - Romain Pierre (romain-pierre) - Jan Behrens - Mantas Var (mvar) - - Frank de Jonge (frenkynet) - Sebastian Krebs - Jean-Christophe Cuvelier [Artack] - Christopher Davis (chrisguitarguy) @@ -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) @@ -1272,7 +1280,9 @@ Symfony is the result of the work of many people who made the code better - ged15 - Daan van Renterghem - Nicole Cordes + - Martin Kirilov - Bram Van der Sype (brammm) + - Christopher Hertel (chertel) - Guile (guile) - Julien Moulin (lizjulien) - Mauro Foti (skler) @@ -1291,6 +1301,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 +1314,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 +1324,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 +1347,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 +1425,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 +1442,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 +1529,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 +1582,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 +1690,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/composer.json b/composer.json index 607d4f2b6e3cc..75e9c916370b2 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "require": { "php": ">=5.5.9", "doctrine/common": "~2.4", - "twig/twig": "~1.28|~2.0", + "twig/twig": "~1.34|~2.4", "psr/cache": "~1.0", "psr/log": "~1.0", "symfony/polyfill-intl-icu": "~1.0", @@ -106,7 +106,6 @@ "Symfony\\Bridge\\Doctrine\\": "src/Symfony/Bridge/Doctrine/", "Symfony\\Bridge\\Monolog\\": "src/Symfony/Bridge/Monolog/", "Symfony\\Bridge\\ProxyManager\\": "src/Symfony/Bridge/ProxyManager/", - "Symfony\\Bridge\\Swiftmailer\\": "src/Symfony/Bridge/Swiftmailer/", "Symfony\\Bridge\\Twig\\": "src/Symfony/Bridge/Twig/", "Symfony\\Bundle\\": "src/Symfony/Bundle/", "Symfony\\Component\\": "src/Symfony/Component/" 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 3059f8aba00a3..7557390bc6ab6 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.php @@ -142,13 +142,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/Doctrine/Validator/Constraints/UniqueEntityValidator.php b/src/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntityValidator.php index c2fcb520e10fe..78d82b322568b 100644 --- a/src/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntityValidator.php +++ b/src/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntityValidator.php @@ -63,6 +63,10 @@ public function validate($entity, Constraint $constraint) throw new ConstraintDefinitionException('At least one field has to be specified.'); } + if (null === $entity) { + return; + } + if ($constraint->em) { $em = $this->registry->getManager($constraint->em); diff --git a/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit b/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit index 17e971bb432d4..35dfc891addb6 100755 --- a/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit +++ b/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit @@ -16,7 +16,7 @@ error_reporting(-1); // PHPUnit 4.8 does not support PHP 7, while 5.1 requires PHP 5.6+ -$PHPUNIT_VERSION = PHP_VERSION_ID >= 50600 ? getenv('SYMFONY_PHPUNIT_VERSION') ?: '5.4' : '4.8'; +$PHPUNIT_VERSION = \PHP_VERSION_ID >= 50600 ? getenv('SYMFONY_PHPUNIT_VERSION') ?: '5.4' : '4.8'; $oldPwd = getcwd(); $PHPUNIT_DIR = getenv('SYMFONY_PHPUNIT_DIR') ?: (__DIR__.'/.phpunit'); $PHP = defined('PHP_BINARY') ? PHP_BINARY : 'php'; diff --git a/src/Symfony/Bridge/Twig/CHANGELOG.md b/src/Symfony/Bridge/Twig/CHANGELOG.md index dee3db5a37655..04c7dfb43d0e3 100644 --- a/src/Symfony/Bridge/Twig/CHANGELOG.md +++ b/src/Symfony/Bridge/Twig/CHANGELOG.md @@ -28,7 +28,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 d871a682f0a4c..9adc9217982fe 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() { @@ -158,14 +154,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) { @@ -176,11 +178,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 ebbfde12c2058..0733b3bda125c 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() { @@ -113,7 +112,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) { @@ -136,16 +135,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); @@ -207,7 +206,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 90b21d0495ff7..302bd4ea2d24a 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,7 +90,7 @@ public function getHtmlCallGraph() '', ), $dump); - return new \Twig_Markup($dump, 'UTF-8'); + return new Markup($dump, 'UTF-8'); } public function getProfile() @@ -108,7 +111,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/WorkflowExtension.php b/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php index 2e5459fa07e68..e93008c84af6d 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,8 +33,8 @@ 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 TwigFunction('workflow_can', array($this, 'canTransition')), + new TwigFunction('workflow_transitions', array($this, 'getEnabledTransitions')), ); } 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 fe99929df0b3d..3805c7416f77c 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); @@ -42,7 +44,7 @@ public function __construct(array $defaultThemes = array(), \Twig_Environment $e /** * {@inheritdoc} */ - public function setEnvironment(\Twig_Environment $environment) + public function setEnvironment(Environment $environment) { $this->environment = $environment; } @@ -160,13 +162,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 c5968a1fa7683..a2ae098e6b6ad 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 2b2172b8cce5a..0f1fbb821cc47 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..b3c89d18eb2bd 100644 --- a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php +++ b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php @@ -13,13 +13,24 @@ use Symfony\Bridge\Twig\Node\TransNode; use Symfony\Bridge\Twig\Node\TransDefaultDomainNode; +use Twig\Environment; +use Twig\Node\BlockNode; +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\Node\SetNode; +use Twig\NodeVisitor\AbstractNodeVisitor; /** * TranslationDefaultDomainNodeVisitor. * * @author Fabien Potencier */ -class TranslationDefaultDomainNodeVisitor extends \Twig_BaseNodeVisitor +class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor { /** * @var Scope @@ -37,23 +48,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 BlockNode || $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 SetNode(false, new Node(array($name)), new Node(array($node->getNode('expr'))), $node->getTemplateLine()); } } @@ -61,7 +72,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 +82,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 +100,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 BlockNode || $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/Resources/views/Form/form_div_layout.html.twig b/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig index e1d09153dfe60..82394abbda50c 100644 --- a/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig +++ b/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig @@ -285,6 +285,7 @@ {%- endblock form -%} {%- block form_start -%} + {%- do form.setMethodRendered() -%} {% set method = method|upper %} {%- if method in ["GET", "POST"] -%} {% set form_method = method %} @@ -320,6 +321,20 @@ {{- form_row(child) -}} {% endif %} {%- endfor %} + + {% if not form.methodRendered %} + {%- do form.setMethodRendered() -%} + {% set method = method|upper %} + {%- if method in ["GET", "POST"] -%} + {% set form_method = method %} + {%- else -%} + {% set form_method = "POST" %} + {%- endif -%} + + {%- if form_method != method -%} + + {%- endif -%} + {% endif %} {% endblock form_rest %} {# Support #} 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 597dfc75f4165..ab3b44ccce0c1 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.php @@ -13,6 +13,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\Twig\Extension\ExpressionExtension; +use Twig\Environment; +use Twig\Loader\ArrayLoader; class ExpressionExtensionTest extends TestCase { @@ -21,7 +23,7 @@ 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 926e51b0098d7..ec0be9df259d5 100644 --- a/src/Symfony/Bridge/Twig/composer.json +++ b/src/Symfony/Bridge/Twig/composer.json @@ -17,12 +17,12 @@ ], "require": { "php": ">=5.5.9", - "twig/twig": "~1.28|~2.0" + "twig/twig": "~1.34|~2.4" }, "require-dev": { "symfony/asset": "~2.8|~3.0", "symfony/finder": "~2.8|~3.0", - "symfony/form": "^3.2.7", + "symfony/form": "^3.2.10|^3.3.3", "symfony/http-kernel": "~3.2", "symfony/polyfill-intl-icu": "~1.0", "symfony/routing": "~2.8|~3.0", @@ -36,6 +36,9 @@ "symfony/var-dumper": "~2.8.10|~3.1.4|~3.2", "symfony/expression-language": "~2.8|~3.0" }, + "conflict": { + "symfony/form": "<3.2.10|~3.3,<3.3.3" + }, "suggest": { "symfony/finder": "", "symfony/asset": "For using the AssetExtension", 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/Command/AssetsInstallCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php index 9f36c8d714d72..395d3e6d335c1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php @@ -110,6 +110,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $rows = array(); $copyUsed = false; $exitCode = 0; + $validAssetDirs = array(); /** @var BundleInterface $bundle */ foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) { if (!is_dir($originDir = $bundle->getPath().'/Resources/public')) { @@ -148,6 +149,13 @@ protected function execute(InputInterface $input, OutputInterface $output) $exitCode = 1; $rows[] = array(sprintf('%s', '\\' === DIRECTORY_SEPARATOR ? 'ERROR' : "\xE2\x9C\x98" /* HEAVY BALLOT X (U+2718) */), $message, $e->getMessage()); } + $validAssetDirs[] = $targetDir; + } + // remove the assets of the bundles that no longer exist + foreach (new \FilesystemIterator($bundlesDir) as $dir) { + if (!in_array($dir, $validAssetDirs)) { + $this->filesystem->remove($dir); + } } $io->table(array('', 'Bundle', 'Method / Error'), $rows); diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php index f926b4153bcd5..de1cfc8e2024f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php @@ -147,7 +147,7 @@ protected function warmup($warmupDir, $realCacheDir, $enableOptionalWarmers = tr $safeTempKernel = str_replace('\\', '\\\\', get_class($tempKernel)); $realKernelFQN = get_class($realKernel); - foreach (Finder::create()->files()->name('*.meta')->in($warmupDir) as $file) { + foreach (Finder::create()->files()->depth('<3')->name('*.meta')->in($warmupDir) as $file) { file_put_contents($file, preg_replace( '/(C\:\d+\:)"'.$safeTempKernel.'"/', sprintf('$1"%s"', $realKernelFQN), @@ -159,14 +159,16 @@ protected function warmup($warmupDir, $realCacheDir, $enableOptionalWarmers = tr $search = array($warmupDir, str_replace('\\', '\\\\', $warmupDir)); $replace = str_replace('\\', '/', $realCacheDir); foreach (Finder::create()->files()->in($warmupDir) as $file) { - $content = str_replace($search, $replace, file_get_contents($file)); - file_put_contents($file, $content); + $content = str_replace($search, $replace, file_get_contents($file), $count); + if ($count) { + file_put_contents($file, $content); + } } // fix references to container's class $tempContainerClass = get_class($tempKernel->getContainer()); $realContainerClass = get_class($realKernel->getContainer()); - foreach (Finder::create()->files()->name($tempContainerClass.'*')->in($warmupDir) as $file) { + foreach (Finder::create()->files()->depth('<2')->name($tempContainerClass.'*')->in($warmupDir) as $file) { $content = str_replace($tempContainerClass, $realContainerClass, file_get_contents($file)); file_put_contents($file, $content); rename($file, str_replace(DIRECTORY_SEPARATOR.$tempContainerClass, DIRECTORY_SEPARATOR.$realContainerClass, $file)); diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php index 97707e8798b59..a08c1a352197f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php @@ -12,6 +12,7 @@ namespace Symfony\Bundle\FrameworkBundle\Command; use Symfony\Bundle\FrameworkBundle\Console\Helper\DescriptorHelper; +use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -109,7 +110,7 @@ protected function execute(InputInterface $input, OutputInterface $output) private function convertController(Route $route) { - $nameParser = $this->getContainer()->get('controller_name_converter'); + $nameParser = new ControllerNameParser($this->getApplication()->getKernel()); if ($route->hasDefault('_controller')) { try { $route->setDefault('_controller', $nameParser->build($route->getDefault('_controller'))); diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index 4a8fef38d3093..5a5473101724a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -400,6 +400,7 @@ private function addSessionSection(ArrayNodeDefinition $rootNode) ->scalarNode('gc_divisor')->end() ->scalarNode('gc_probability')->defaultValue(1)->end() ->scalarNode('gc_maxlifetime')->end() + ->booleanNode('use_strict_mode')->end() ->scalarNode('save_path')->defaultValue('%kernel.cache_dir%/sessions')->end() ->integerNode('metadata_update_threshold') ->defaultValue('0') diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index 277f0dc62ada5..f801596d3c4c8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -555,7 +555,7 @@ private function registerSessionConfiguration(array $config, ContainerBuilder $c // session storage $container->setAlias('session.storage', $config['storage_id']); $options = array(); - foreach (array('name', 'cookie_lifetime', 'cookie_path', 'cookie_domain', 'cookie_secure', 'cookie_httponly', 'use_cookies', 'gc_maxlifetime', 'gc_probability', 'gc_divisor') as $key) { + foreach (array('name', 'cookie_lifetime', 'cookie_path', 'cookie_domain', 'cookie_secure', 'cookie_httponly', 'use_cookies', 'gc_maxlifetime', 'gc_probability', 'gc_divisor', 'use_strict_mode') as $key) { if (isset($config[$key])) { $options[$key] = $config[$key]; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml index 843fc72bdb253..9c2dfad2ee639 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/form_debug.xml @@ -24,7 +24,6 @@ - false diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd index fbf53309f41be..a12cab4ff1fef 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd @@ -13,6 +13,7 @@ + @@ -57,6 +58,10 @@ + + + + @@ -105,6 +110,7 @@ + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml index ba1c3bc168316..10783fdfc688d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml @@ -128,7 +128,7 @@ - + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php index a0cac9a908b24..597082485a0b6 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterDebugCommandTest.php @@ -12,9 +12,10 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Command; use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Application; +use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand; +use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; @@ -51,16 +52,15 @@ public function testDebugInvalidRoute() */ private function createCommandTester() { - $application = new Application(); + $application = new Application($this->getKernel()); $command = new RouterDebugCommand(); - $command->setContainer($this->getContainer()); $application->add($command); return new CommandTester($application->find('debug:router')); } - private function getContainer() + private function getKernel() { $routeCollection = new RouteCollection(); $routeCollection->add('foo', new Route('foo')); @@ -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 @@ -82,14 +82,25 @@ private function getContainer() ->with('router') ->will($this->returnValue(true)) ; - $container + ->expects($this->any()) ->method('get') - ->will($this->returnValueMap(array( - array('router', 1, $router), - array('controller_name_converter', 1, $loader), - ))); + ->with('router') + ->willReturn($router) + ; + + $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel + ->expects($this->any()) + ->method('getContainer') + ->willReturn($container) + ; + $kernel + ->expects($this->once()) + ->method('getBundles') + ->willReturn(array()) + ; - return $container; + return $kernel; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php index db533c09742ba..384bd7ca53079 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/RouterMatchCommandTest.php @@ -12,10 +12,11 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Command; use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Application; +use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand; use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand; +use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RequestContext; @@ -45,20 +46,14 @@ public function testWithNotMatchPath() */ private function createCommandTester() { - $application = new Application(); - - $command = new RouterMatchCommand(); - $command->setContainer($this->getContainer()); - $application->add($command); - - $command = new RouterDebugCommand(); - $command->setContainer($this->getContainer()); - $application->add($command); + $application = new Application($this->getKernel()); + $application->add(new RouterMatchCommand()); + $application->add(new RouterDebugCommand()); return new CommandTester($application->find('router:match')); } - private function getContainer() + private function getKernel() { $routeCollection = new RouteCollection(); $routeCollection->add('foo', new Route('foo')); @@ -76,21 +71,32 @@ private function getContainer() ; $loader = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container - ->expects($this->once()) + ->expects($this->atLeastOnce()) ->method('has') ->with('router') ->will($this->returnValue(true)); - $container->method('get') - ->will($this->returnValueMap(array( - array('router', 1, $router), - array('controller_name_converter', 1, $loader), - ))); + $container + ->expects($this->any()) + ->method('get') + ->willReturn($router); + + $kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); + $kernel + ->expects($this->any()) + ->method('getContainer') + ->willReturn($container) + ; + $kernel + ->expects($this->once()) + ->method('getBundles') + ->willReturn(array()) + ; - return $container; + return $kernel; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTest.php index 80908a9e5b91f..41a9a90e16b9c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTest.php @@ -367,7 +367,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 = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); @@ -383,7 +383,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 = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); @@ -399,7 +399,7 @@ public function testRenderTwig() public function testStreamTwig() { - $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); $container->expects($this->at(0))->method('has')->will($this->returnValue(false)); 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/Fixtures/php/full.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php index 9173dd5615bda..4d2baf157b66c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php @@ -14,6 +14,9 @@ 'esi' => array( 'enabled' => true, ), + 'ssi' => array( + 'enabled' => true, + ), 'profiler' => array( 'only_exceptions' => true, 'enabled' => false, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml index 7c6b11ac44aa6..1dd014f4e3f67 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml @@ -12,6 +12,7 @@ + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml index 237654880c984..4b9d99af25af5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml @@ -9,6 +9,8 @@ framework: trusted_proxies: ['127.0.0.1', '10.0.0.1'] esi: enabled: true + ssi: + enabled: true profiler: only_exceptions: true enabled: false diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 02bf30b96dad6..aa99857a52ea0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -133,6 +133,13 @@ public function testEsi() $this->assertTrue($container->hasDefinition('esi'), '->registerEsiConfiguration() loads esi.xml'); } + public function testSsi() + { + $container = $this->createContainerFromFile('full'); + + $this->assertTrue($container->hasDefinition('ssi'), '->registerSsiConfiguration() loads ssi.xml'); + } + public function testEnabledProfiler() { $container = $this->createContainerFromFile('profiler'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php index d9efdfe6e94d5..376dab5ddbd68 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php @@ -144,7 +144,52 @@ public function testInvalidOptions() { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); - (new Translator($container, new MessageSelector(), array(), array('foo' => 'bar'))); + (new Translator($container, new MessageSelector(), [], ['foo' => 'bar'])); + } + + /** @dataProvider getDebugModeAndCacheDirCombinations */ + public function testResourceFilesOptionLoadsBeforeOtherAddedResources($debug, $enableCache) + { + $someCatalogue = $this->getCatalogue('some_locale', array()); + + $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock(); + + $loader->expects($this->at(0)) + ->method('load') + /* The "messages.some_locale.loader" is passed via the resource_file option and shall be loaded first */ + ->with('messages.some_locale.loader', 'some_locale', 'messages') + ->willReturn($someCatalogue); + + $loader->expects($this->at(1)) + ->method('load') + /* This resource is added by an addResource() call and shall be loaded after the resource_files */ + ->with('second_resource.some_locale.loader', 'some_locale', 'messages') + ->willReturn($someCatalogue); + + $options = array( + 'resource_files' => array('some_locale' => array('messages.some_locale.loader')), + 'debug' => $debug, + ); + + if ($enableCache) { + $options['cache_dir'] = $this->tmpDir; + } + + /** @var Translator $translator */ + $translator = $this->createTranslator($loader, $options); + $translator->addResource('loader', 'second_resource.some_locale.loader', 'some_locale', 'messages'); + + $translator->trans('some_message', array(), null, 'some_locale'); + } + + public function getDebugModeAndCacheDirCombinations() + { + return array( + array(false, false), + array(true, false), + array(false, true), + array(true, true), + ); } protected function getCatalogue($locale, $messages, $resources = array()) 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/Translation/Translator.php b/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php index fedc425a11a07..2efbf67047d4a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php +++ b/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php @@ -38,6 +38,14 @@ class Translator extends BaseTranslator implements WarmableInterface */ private $resourceLocales; + /** + * Holds parameters from addResource() calls so we can defer the actual + * parent::addResource() calls until initialize() is executed. + * + * @var array + */ + private $resources = array(); + /** * Constructor. * @@ -66,9 +74,7 @@ public function __construct(ContainerInterface $container, MessageSelector $sele $this->options = array_merge($this->options, $options); $this->resourceLocales = array_keys($this->options['resource_files']); - if (null !== $this->options['cache_dir'] && $this->options['debug']) { - $this->loadResources(); - } + $this->addResourceFiles($this->options['resource_files']); parent::__construct($container->getParameter('kernel.default_locale'), $selector, $this->options['cache_dir'], $this->options['debug']); } @@ -94,6 +100,11 @@ public function warmUp($cacheDir) } } + public function addResource($format, $resource, $locale, $domain = null) + { + $this->resources[] = array($format, $resource, $locale, $domain); + } + /** * {@inheritdoc} */ @@ -105,7 +116,12 @@ protected function initializeCatalogue($locale) protected function initialize() { - $this->loadResources(); + foreach ($this->resources as $key => $params) { + list($format, $resource, $locale, $domain) = $params; + parent::addResource($format, $resource, $locale, $domain); + } + $this->resources = array(); + foreach ($this->loaderIds as $id => $aliases) { foreach ($aliases as $alias) { $this->addLoader($alias, $this->container->get($id)); @@ -113,14 +129,13 @@ protected function initialize() } } - private function loadResources() + private function addResourceFiles($filesByLocale) { - foreach ($this->options['resource_files'] as $locale => $files) { + foreach ($filesByLocale as $locale => $files) { foreach ($files as $key => $file) { // filename is domain.locale.format list($domain, $locale, $format) = explode('.', basename($file), 3); $this->addResource($format, $file, $locale, $domain); - unset($this->options['resource_files'][$locale][$key]); } } } diff --git a/src/Symfony/Bundle/FrameworkBundle/composer.json b/src/Symfony/Bundle/FrameworkBundle/composer.json index 6360ff6dbce17..5444c89e25f3b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/composer.json +++ b/src/Symfony/Bundle/FrameworkBundle/composer.json @@ -54,7 +54,7 @@ "symfony/property-info": "~3.1", "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": { diff --git a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php index 544e1de1921af..ec028b0926fae 100644 --- a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php +++ b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php @@ -114,7 +114,7 @@ public function collect(Request $request, Response $response, \Exception $except 'logout_url' => $logoutUrl, 'user' => $token->getUsername(), 'roles' => $this->cloneVar(array_map(function (RoleInterface $role) { return $role->getRole(); }, $assignedRoles)), - 'inherited_roles' => $this->cloneVar(array_map(function (RoleInterface $role) { return $role->getRole(); }, $inheritedRoles)), + 'inherited_roles' => $this->cloneVar(array_unique(array_map(function (RoleInterface $role) { return $role->getRole(); }, $inheritedRoles))), 'supports_role_hierarchy' => null !== $this->roleHierarchy, ); } diff --git a/src/Symfony/Bundle/SecurityBundle/Security/FirewallMap.php b/src/Symfony/Bundle/SecurityBundle/Security/FirewallMap.php index f833a63e65966..77fe45f8a8267 100644 --- a/src/Symfony/Bundle/SecurityBundle/Security/FirewallMap.php +++ b/src/Symfony/Bundle/SecurityBundle/Security/FirewallMap.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\SecurityBundle\Security; +use Symfony\Bundle\SecurityBundle\Security\FirewallContext; use Symfony\Component\Security\Http\FirewallMapInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -26,13 +27,11 @@ class FirewallMap implements FirewallMapInterface { protected $container; protected $map; - private $contexts; public function __construct(ContainerInterface $container, array $map) { $this->container = $container; $this->map = $map; - $this->contexts = new \SplObjectStorage(); } /** @@ -63,15 +62,27 @@ public function getFirewallConfig(Request $request) return $context->getConfig(); } + /** + * @return FirewallContext + */ private function getFirewallContext(Request $request) { - if ($this->contexts->contains($request)) { - return $this->contexts[$request]; + if ($request->attributes->has('_firewall_context')) { + $storedContextId = $request->attributes->get('_firewall_context'); + foreach ($this->map as $contextId => $requestMatcher) { + if ($contextId === $storedContextId) { + return $this->container->get($contextId); + } + } + + $request->attributes->remove('_firewall_context'); } foreach ($this->map as $contextId => $requestMatcher) { if (null === $requestMatcher || $requestMatcher->matches($request)) { - return $this->contexts[$request] = $this->container->get($contextId); + $request->attributes->set('_firewall_context', $contextId); + + return $this->container->get($contextId); } } } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php index a5cd0fd1fda06..0ff3ab5f44b07 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php @@ -166,6 +166,11 @@ public function provideRoles() array('ROLE_ADMIN'), array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), ), + array( + array('ROLE_ADMIN', 'ROLE_OPERATOR'), + array('ROLE_ADMIN', 'ROLE_OPERATOR'), + array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), + ), ); } @@ -173,6 +178,7 @@ private function getRoleHierarchy() { return new RoleHierarchy(array( 'ROLE_ADMIN' => array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), + 'ROLE_OPERATOR' => array('ROLE_USER'), )); } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php new file mode 100644 index 0000000000000..a94d8c2026d8f --- /dev/null +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\SecurityBundle\Tests\Security; + +use PHPUnit\Framework\TestCase; +use Symfony\Bundle\SecurityBundle\Security\FirewallContext; +use Symfony\Bundle\SecurityBundle\Security\FirewallMap; +use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestMatcherInterface; + +class FirewallMapTest extends TestCase +{ + const ATTRIBUTE_FIREWALL_CONTEXT = '_firewall_context'; + + public function testGetListenersWithEmptyMap() + { + $request = new Request(); + + $map = array(); + $container = $this->getMockBuilder(Container::class)->getMock(); + $container->expects($this->never())->method('get'); + + $firewallMap = new FirewallMap($container, $map); + + $this->assertEquals(array(array(), null), $firewallMap->getListeners($request)); + $this->assertNull($firewallMap->getFirewallConfig($request)); + $this->assertFalse($request->attributes->has(self::ATTRIBUTE_FIREWALL_CONTEXT)); + } + + public function testGetListenersWithInvalidParameter() + { + $request = new Request(); + $request->attributes->set(self::ATTRIBUTE_FIREWALL_CONTEXT, 'foo'); + + $map = array(); + $container = $this->getMockBuilder(Container::class)->getMock(); + $container->expects($this->never())->method('get'); + + $firewallMap = new FirewallMap($container, $map); + + $this->assertEquals(array(array(), null), $firewallMap->getListeners($request)); + $this->assertNull($firewallMap->getFirewallConfig($request)); + $this->assertFalse($request->attributes->has(self::ATTRIBUTE_FIREWALL_CONTEXT)); + } + + public function testGetListeners() + { + $request = new Request(); + + $firewallContext = $this->getMockBuilder(FirewallContext::class)->disableOriginalConstructor()->getMock(); + $firewallContext->expects($this->once())->method('getConfig')->willReturn('CONFIG'); + $firewallContext->expects($this->once())->method('getContext')->willReturn(array('LISTENERS', 'EXCEPTION LISTENER')); + + $matcher = $this->getMockBuilder(RequestMatcherInterface::class)->getMock(); + $matcher->expects($this->once()) + ->method('matches') + ->with($request) + ->willReturn(true); + + $container = $this->getMockBuilder(Container::class)->getMock(); + $container->expects($this->exactly(2))->method('get')->willReturn($firewallContext); + + $firewallMap = new FirewallMap($container, array('security.firewall.map.context.foo' => $matcher)); + + $this->assertEquals(array('LISTENERS', 'EXCEPTION LISTENER'), $firewallMap->getListeners($request)); + $this->assertEquals('CONFIG', $firewallMap->getFirewallConfig($request)); + $this->assertEquals('security.firewall.map.context.foo', $request->attributes->get(self::ATTRIBUTE_FIREWALL_CONTEXT)); + } +} diff --git a/src/Symfony/Bundle/SecurityBundle/composer.json b/src/Symfony/Bundle/SecurityBundle/composer.json index 97acacd36bc89..dbcec82819615 100644 --- a/src/Symfony/Bundle/SecurityBundle/composer.json +++ b/src/Symfony/Bundle/SecurityBundle/composer.json @@ -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" }, "suggest": { "symfony/security-acl": "For using the ACL functionality of this bundle" diff --git a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php index 9eea901f6dde4..89f8d701cd83f 100644 --- a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php +++ b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php @@ -16,6 +16,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinderInterface; use Symfony\Component\Templating\TemplateReference; +use Twig\Error\Error; /** * Generates the Twig cache for all templates. @@ -76,7 +77,7 @@ public function warmUp($cacheDir) try { $twig->loadTemplate($template); - } catch (\Twig_Error $e) { + } catch (Error $e) { // problem during compilation, give up } } 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 780454aed986e..94815467c0db2 100644 --- a/src/Symfony/Bundle/TwigBundle/ContainerAwareRuntimeLoader.php +++ b/src/Symfony/Bundle/TwigBundle/ContainerAwareRuntimeLoader.php @@ -13,13 +13,14 @@ use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +use Twig\RuntimeLoader\RuntimeLoaderInterface; /** * Loads Twig extension runtimes via the service container. * * @author Fabien Potencier */ -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..f2db82b0995b0 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; @@ -69,7 +72,7 @@ public function showAction(Request $request, FlattenException $exception, DebugL 'logger' => $logger, 'currentContent' => $currentContent, ) - )); + ), 200, array('Content-Type' => $request->getMimeType($request->getRequestFormat()) ?: 'text/html')); } /** @@ -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/Compiler/ExtensionPass.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php index 00d140369d2e3..96278822bf069 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php @@ -65,10 +65,7 @@ public function process(ContainerBuilder $container) $container->getDefinition('twig.extension.httpkernel')->addTag('twig.extension'); // inject Twig in the hinclude service if Twig is the only registered templating engine - if ( - !$container->hasParameter('templating.engines') - || array('twig') == $container->getParameter('templating.engines') - ) { + if ((!$container->hasParameter('templating.engines') || array('twig') == $container->getParameter('templating.engines')) && $container->hasDefinition('fragment.renderer.hinclude')) { $container->getDefinition('fragment.renderer.hinclude') ->addTag('kernel.fragment_renderer', array('alias' => 'hinclude')) ->replaceArgument(0, new Reference('twig')) @@ -96,6 +93,7 @@ public function process(ContainerBuilder $container) } else { $twigLoader->replaceArgument(1, $composerRootDir); $container->setAlias('twig.loader.filesystem', new Alias('twig.loader.native_filesystem', false)); + $container->removeDefinition('templating.engine.twig'); } if ($container->has('assets.packages')) { 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/Loader/FilesystemLoader.php b/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php index 0a9ac7a3ca19a..a93a9afc58ca3 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) { @@ -74,10 +76,9 @@ protected function findTemplate($template, $throw = true) } $file = null; - $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 8eb702c99ee45..34f8d557c8cad 100644 --- a/src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml +++ b/src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -40,24 +40,24 @@ - + - + - + - + @@ -104,7 +104,7 @@ - + diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php index 920a833c6bf03..5d779c68c2a5e 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Controller/ExceptionControllerTest.php @@ -15,19 +15,16 @@ 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/Exception/error404.html.twig' => 'ok', - )) - ); + $twig = $this->createTwigEnv(array('@Twig/Exception/error404.html.twig' => 'not found')); - $request = Request::create('whatever', 'GET'); - $request->headers->set('X-Php-Ob-Level', 1); + $request = $this->createRequest('html'); $request->attributes->set('showException', false); $exception = FlattenException::create(new \Exception(), 404); $controller = new ExceptionController($twig, /* "showException" defaults to --> */ true); @@ -35,25 +32,61 @@ public function testShowActionCanBeForcedToShowErrorPage() $response = $controller->showAction($request, $exception, null); $this->assertEquals(200, $response->getStatusCode()); // successful request - $this->assertEquals('ok', $response->getContent()); // content of the error404.html template + $this->assertEquals('not found', $response->getContent()); } public function testFallbackToHtmlIfNoTemplateForRequestedFormat() { - $twig = new \Twig_Environment( - new \Twig_Loader_Array(array( - '@Twig/Exception/error.html.twig' => 'html', - )) - ); + $twig = $this->createTwigEnv(array('@Twig/Exception/error.html.twig' => '')); - $request = Request::create('whatever'); - $request->headers->set('X-Php-Ob-Level', 1); - $request->setRequestFormat('txt'); + $request = $this->createRequest('txt'); $exception = FlattenException::create(new \Exception()); $controller = new ExceptionController($twig, false); - $response = $controller->showAction($request, $exception); + $controller->showAction($request, $exception); + + $this->assertEquals('html', $request->getRequestFormat()); + } + + public function testFallbackToHtmlWithFullExceptionIfNoTemplateForRequestedFormatAndExceptionsShouldBeShown() + { + $twig = $this->createTwigEnv(array('@Twig/Exception/exception_full.html.twig' => '')); + + $request = $this->createRequest('txt'); + $request->attributes->set('showException', true); + $exception = FlattenException::create(new \Exception()); + $controller = new ExceptionController($twig, false); + + $controller->showAction($request, $exception); $this->assertEquals('html', $request->getRequestFormat()); } + + public function testResponseHasRequestedMimeType() + { + $twig = $this->createTwigEnv(array('@Twig/Exception/error.json.twig' => '{}')); + + $request = $this->createRequest('json'); + $exception = FlattenException::create(new \Exception()); + $controller = new ExceptionController($twig, false); + + $response = $controller->showAction($request, $exception); + + $this->assertEquals('json', $request->getRequestFormat()); + $this->assertEquals($request->getMimeType('json'), $response->headers->get('Content-Type')); + } + + private function createRequest($requestFormat) + { + $request = Request::create('whatever'); + $request->headers->set('X-Php-Ob-Level', 1); + $request->setRequestFormat($requestFormat); + + return $request; + } + + private function createTwigEnv(array $templates) + { + return new Environment(new ArrayLoader($templates)); + } } 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 4073653c8b571..d2fb85bd921a1 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'); @@ -136,9 +136,10 @@ public function testGlobalsWithDifferentTypesAndValues() $calls = $container->getDefinition('twig')->getMethodCalls(); foreach (array_slice($calls, 2) as $call) { - list($name, $value) = each($globals); - $this->assertEquals($name, $call[1][0]); - $this->assertSame($value, $call[1][1]); + $this->assertEquals(key($globals), $call[1][0]); + $this->assertSame(current($globals), $call[1][1]); + + next($globals); } } 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 8b51254f13dd9..ef1a183e822d4 100644 --- a/src/Symfony/Bundle/TwigBundle/composer.json +++ b/src/Symfony/Bundle/TwigBundle/composer.json @@ -21,7 +21,7 @@ "symfony/twig-bridge": "^3.2.1", "symfony/http-foundation": "~2.8|~3.0", "symfony/http-kernel": "~2.8.16|~3.1.9|^3.2.2", - "twig/twig": "~1.28|~2.0" + "twig/twig": "~1.34|~2.4" }, "require-dev": { "symfony/asset": "~2.8|~3.0", @@ -34,7 +34,8 @@ "symfony/templating": "~2.8|~3.0", "symfony/yaml": "~2.8|~3.0", "symfony/framework-bundle": "^3.2.2", - "doctrine/annotations": "~1.0" + "doctrine/annotations": "~1.0", + "doctrine/cache": "~1.0" }, "autoload": { "psr-4": { "Symfony\\Bundle\\TwigBundle\\": "" }, 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/Profiler/open.css.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/open.css.twig index 02bc252f12007..7a0941c955a6d 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/open.css.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/open.css.twig @@ -64,7 +64,7 @@ a.doc:hover { .anchor { position: relative; - padding-top: 7em; - margin-top: -7em; + display: block; + top: -7em; visibility: hidden; } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig index d2db7b700d9b0..590d030c7a55a 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig @@ -369,6 +369,15 @@ 100% { background: #222; } } +.sf-toolbar-block.sf-toolbar-block-dump { + position: static; +} + +.sf-toolbar-block.sf-toolbar-block-dump .sf-toolbar-info { + max-width: none; + right: 0; +} + .sf-toolbar-block-dump pre.sf-dump { background-color: #222; border-color: #777; @@ -513,3 +522,33 @@ display: none; } } + +/***** Error Toolbar *****/ +.sf-error-toolbar .sf-toolbarreset { + background: #222; + color: #f5f5f5; + font: 13px/36px Arial, sans-serif; + height: 36px; + padding: 0 15px; + text-align: left; +} + +.sf-error-toolbar .sf-toolbarreset svg { + height: auto; +} + +.sf-error-toolbar .sf-toolbarreset a { + color: #99cdd8; + margin-left: 5px; + text-decoration: underline; +} + +.sf-error-toolbar .sf-toolbarreset a:hover { + text-decoration: none; +} + +.sf-error-toolbar .sf-toolbarreset .sf-toolbar-icon { + float: left; + padding: 5px 0; + margin-right: 10px; +} diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig index 7dc541caae589..c40ce1d6d5e81 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig @@ -97,7 +97,14 @@ }, function(xhr) { if (xhr.status !== 0) { - confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\n\nDo you want to open the profiler?') && (window.location = '{{ path("_profiler", { "token": token }) }}'); + var sfwdt = document.getElementById('sfwdt{{ token }}'); + sfwdt.innerHTML = '\ +
\ +
\ + An error occurred while loading the web debug toolbar. Open the web profiler.\ +
\ + '; + sfwdt.setAttribute('class', 'sf-toolbar sf-error-toolbar'); } }, { maxTries: 5 } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig index 16487d3fcbd36..1cfa085089685 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Router/panel.html.twig @@ -54,7 +54,7 @@ {% for trace in traces %} - {{ loop.index }} + {{ loop.index }} {{ trace.name }} {{ trace.path }} 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 032d6f08bbfb2..9e37d7c5dd2c9 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("\nmaxRedirects) { if ($this->redirectCount > $this->maxRedirects) { + $this->redirectCount = 0; throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects)); } } diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php index 4a788963ea74b..b5f6a61b56b03 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php @@ -426,6 +426,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/ApcuAdapter.php b/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php index 0a3887eba091f..6687bd4272d1d 100644 --- a/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ApcuAdapter.php @@ -21,7 +21,7 @@ class ApcuAdapter extends AbstractAdapter { public static function isSupported() { - return function_exists('apcu_fetch') && ini_get('apc.enabled') && !('cli' === PHP_SAPI && !ini_get('apc.enable_cli')); + return function_exists('apcu_fetch') && ini_get('apc.enabled'); } public function __construct($namespace = '', $defaultLifetime = 0, $version = null) @@ -69,7 +69,7 @@ protected function doHave($id) */ protected function doClear($namespace) { - return isset($namespace[0]) && class_exists('APCuIterator', false) + return isset($namespace[0]) && class_exists('APCuIterator', false) && ('cli' !== PHP_SAPI || ini_get('apc.enable_cli')) ? apcu_delete(new \APCuIterator(sprintf('/^%s/', preg_quote($namespace, '/')), APC_ITER_KEY)) : apcu_clear_cache(); } diff --git a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php index 3fa3a40533d9e..4a462b35c451e 100644 --- a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php @@ -195,7 +195,7 @@ protected function doFetch(array $ids) foreach ($expired as $id) { $stmt->bindValue(++$i, $id); } - $stmt->execute($expired); + $stmt->execute(); } } diff --git a/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php b/src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php index ad287576f59d3..c8ba804898864 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/PhpFilesAdapter.php b/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php index befa38d8d46df..88107cb9899dc 100644 --- a/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php @@ -26,7 +26,7 @@ class PhpFilesAdapter extends AbstractAdapter public static function isSupported() { - return function_exists('opcache_compile_file') && ini_get('opcache.enable'); + return function_exists('opcache_invalidate') && ini_get('opcache.enable'); } public function __construct($namespace = '', $defaultLifetime = 0, $directory = null) @@ -118,7 +118,7 @@ protected function doSave(array $values, $lifetime) $ok = $this->write($file, ' 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/Cache/Adapter/TagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php index b8c4a08021b70..03ed203bec9cc 100644 --- a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php @@ -261,7 +261,7 @@ private function generateItems($items, array $tagKeys) foreach ($items as $key => $item) { if (!$tagKeys) { - yield $key => isset($invalidKeys[self::TAGS_PREFIX.$key]) ? $f($key, null, $item) : $item; + yield $key => isset($invalidKeys[static::TAGS_PREFIX.$key]) ? $f($key, null, $item) : $item; continue; } if (!isset($tagKeys[$key])) { @@ -287,7 +287,7 @@ private function generateItems($items, array $tagKeys) $itemTags = $tagVersions = $tagKeys = null; foreach ($bufferedItems as $key => $item) { - yield $key => isset($invalidKeys[self::TAGS_PREFIX.$key]) ? $f($key, null, $item) : $item; + yield $key => isset($invalidKeys[static::TAGS_PREFIX.$key]) ? $f($key, null, $item) : $item; } $bufferedItems = null; } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/PdoAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/PdoAdapterTest.php index b0d2b9cb8a105..90c9ece8bcc9d 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/PdoAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/PdoAdapterTest.php @@ -41,4 +41,30 @@ public function createCachePool($defaultLifetime = 0) { return new PdoAdapter('sqlite:'.self::$dbFile, 'ns', $defaultLifetime); } + + public function testCleanupExpiredItems() + { + $pdo = new \PDO('sqlite:'.self::$dbFile); + + $getCacheItemCount = function () use ($pdo) { + return (int) $pdo->query('SELECT COUNT(*) FROM cache_items')->fetch(\PDO::FETCH_COLUMN); + }; + + $this->assertSame(0, $getCacheItemCount()); + + $cache = $this->createCachePool(); + + $item = $cache->getItem('some_nice_key'); + $item->expiresAfter(1); + $item->set(1); + + $cache->save($item); + $this->assertSame(1, $getCacheItemCount()); + + sleep(2); + + $newItem = $cache->getItem($item->getKey()); + $this->assertFalse($newItem->isHit()); + $this->assertSame(0, $getCacheItemCount(), 'PDOAdapter must clean up expired items'); + } } diff --git a/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php b/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php index e45c3f8cb1ab6..1d53c482f98f4 100644 --- a/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php +++ b/src/Symfony/Component/ClassLoader/ClassCollectionLoader.php @@ -256,7 +256,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 810a70b6d2e75..baeb4c1abad42 100644 --- a/src/Symfony/Component/ClassLoader/ClassMapGenerator.php +++ b/src/Symfony/Component/ClassLoader/ClassMapGenerator.php @@ -64,7 +64,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/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/Descriptor/JsonDescriptor.php b/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php index 87e38fdb89071..942fdc96226ac 100644 --- a/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Component/Console/Descriptor/JsonDescriptor.php @@ -103,7 +103,7 @@ private function getInputArgumentData(InputArgument $argument) 'is_required' => $argument->isRequired(), 'is_array' => $argument->isArray(), 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()), - 'default' => $argument->getDefault(), + 'default' => INF === $argument->getDefault() ? 'INF' : $argument->getDefault(), ); } @@ -121,7 +121,7 @@ private function getInputOptionData(InputOption $option) 'is_value_required' => $option->isValueRequired(), 'is_multiple' => $option->isArray(), 'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()), - 'default' => $option->getDefault(), + 'default' => INF === $option->getDefault() ? 'INF' : $option->getDefault(), ); } diff --git a/src/Symfony/Component/Console/Descriptor/TextDescriptor.php b/src/Symfony/Component/Console/Descriptor/TextDescriptor.php index 81710046c610f..c306d59c07a2e 100644 --- a/src/Symfony/Component/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Component/Console/Descriptor/TextDescriptor.php @@ -262,6 +262,10 @@ private function getCommandAliasesText($command) */ private function formatDefaultValue($default) { + if (INF === $default) { + return 'INF'; + } + if (is_string($default)) { $default = OutputFormatter::escape($default); } elseif (is_array($default)) { diff --git a/src/Symfony/Component/Console/Helper/QuestionHelper.php b/src/Symfony/Component/Console/Helper/QuestionHelper.php index fe58bb9fa1fb2..d8b373cc1757b 100644 --- a/src/Symfony/Component/Console/Helper/QuestionHelper.php +++ b/src/Symfony/Component/Console/Helper/QuestionHelper.php @@ -124,8 +124,7 @@ public function getName() * * @return bool|mixed|null|string * - * @throws \Exception - * @throws \RuntimeException + * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden */ private function doAsk(OutputInterface $output, Question $question) { @@ -139,7 +138,7 @@ private function doAsk(OutputInterface $output, Question $question) if ($question->isHidden()) { try { $ret = trim($this->getHiddenResponse($output, $inputStream)); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { if (!$question->isHiddenFallback()) { throw $e; } 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/Tests/Descriptor/ObjectsProvider.php b/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php index 8f825ecb68395..b4f34ada19ec6 100644 --- a/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php +++ b/src/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php @@ -32,6 +32,7 @@ public static function getInputArguments() 'input_argument_3' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', 'default_value'), 'input_argument_4' => new InputArgument('argument_name', InputArgument::REQUIRED, "multiline\nargument description"), 'input_argument_with_style' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', 'style'), + 'input_argument_with_default_inf_value' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', INF), ); } @@ -46,6 +47,7 @@ public static function getInputOptions() 'input_option_6' => new InputOption('option_name', array('o', 'O'), InputOption::VALUE_REQUIRED, 'option with multiple shortcuts'), 'input_option_with_style' => new InputOption('option_name', 'o', InputOption::VALUE_REQUIRED, 'option description', 'style'), 'input_option_with_style_array' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'option description', array('Hello', 'world')), + 'input_option_with_default_inf_value' => new InputOption('option_name', 'o', InputOption::VALUE_OPTIONAL, 'option description', INF), ); } diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.json b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.json new file mode 100644 index 0000000000000..b61ecf7b8c23c --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.json @@ -0,0 +1,7 @@ +{ + "name": "argument_name", + "is_required": false, + "is_array": false, + "description": "argument description", + "default": "INF" +} diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.md b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.md new file mode 100644 index 0000000000000..293d816201271 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.md @@ -0,0 +1,7 @@ +**argument_name:** + +* Name: argument_name +* Is required: no +* Is array: no +* Description: argument description +* Default: `INF` diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.txt b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.txt new file mode 100644 index 0000000000000..c32d768c6f328 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.txt @@ -0,0 +1 @@ + argument_name argument description [default: INF] diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.xml b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.xml new file mode 100644 index 0000000000000..d457260070be0 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_argument_with_default_inf_value.xml @@ -0,0 +1,7 @@ + + + argument description + + INF + + diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.json b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.json new file mode 100644 index 0000000000000..7c96ad30405c6 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.json @@ -0,0 +1,9 @@ +{ + "name": "--option_name", + "shortcut": "-o", + "accept_value": true, + "is_value_required": false, + "is_multiple": false, + "description": "option description", + "default": "INF" +} diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.md b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.md new file mode 100644 index 0000000000000..b57bd04bf9993 --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.md @@ -0,0 +1,9 @@ +**option_name:** + +* Name: `--option_name` +* Shortcut: `-o` +* Accept value: yes +* Is value required: no +* Is multiple: no +* Description: option description +* Default: `INF` diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.txt b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.txt new file mode 100644 index 0000000000000..d467dcf42327b --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.txt @@ -0,0 +1 @@ + -o, --option_name[=OPTION_NAME] option description [default: INF] diff --git a/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.xml b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.xml new file mode 100644 index 0000000000000..5d1d21753e9dc --- /dev/null +++ b/src/Symfony/Component/Console/Tests/Fixtures/input_option_with_default_inf_value.xml @@ -0,0 +1,7 @@ + + diff --git a/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php b/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php index b4cf139130d73..6ed6402d249d4 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/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index 4431418d85848..dd514962ea47c 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -166,7 +166,7 @@ public function dump(array $options = array()) } } if ($unusedEnvs) { - throw new EnvParameterException($unusedEnvs); + throw new EnvParameterException($unusedEnvs, null, 'Environment variables "%s" are never used. Please, check your container\'s configuration.'); } return $code; diff --git a/src/Symfony/Component/DependencyInjection/Exception/EnvParameterException.php b/src/Symfony/Component/DependencyInjection/Exception/EnvParameterException.php index 44dbab45b6284..3839a4633be40 100644 --- a/src/Symfony/Component/DependencyInjection/Exception/EnvParameterException.php +++ b/src/Symfony/Component/DependencyInjection/Exception/EnvParameterException.php @@ -18,8 +18,8 @@ */ class EnvParameterException extends InvalidArgumentException { - public function __construct(array $usedEnvs, \Exception $previous = null) + public function __construct(array $envs, \Exception $previous = null, $message = 'Incompatible use of dynamic environment variables "%s" found in parameters.') { - parent::__construct(sprintf('Incompatible use of dynamic environment variables "%s" found in parameters.', implode('", "', $usedEnvs)), 0, $previous); + parent::__construct(sprintf($message, implode('", "', $envs)), 0, $previous); } } 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/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index 2ad701aa6d327..ee81219ef01d0 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -302,7 +302,7 @@ public function testEnvParameter() /** * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - * @expectedExceptionMessage Incompatible use of dynamic environment variables "FOO" found in parameters. + * @expectedExceptionMessage Environment variables "FOO" are never used. Please, check your container's configuration. */ public function testUnusedEnvParameter() { diff --git a/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php b/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php index 5982b85f3021d..3b98a684446a9 100644 --- a/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php @@ -104,7 +104,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])) { diff --git a/src/Symfony/Component/EventDispatcher/Tests/AbstractEventDispatcherTest.php b/src/Symfony/Component/EventDispatcher/Tests/AbstractEventDispatcherTest.php index 5943039c9e6de..0521d6bd965ee 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)); diff --git a/src/Symfony/Component/Filesystem/Filesystem.php b/src/Symfony/Component/Filesystem/Filesystem.php index b50f5ffe76a18..1a67a971358fe 100644 --- a/src/Symfony/Component/Filesystem/Filesystem.php +++ b/src/Symfony/Component/Filesystem/Filesystem.php @@ -276,6 +276,13 @@ public function rename($origin, $target, $overwrite = false) } if (true !== @rename($origin, $target)) { + if (is_dir($origin)) { + // See https://bugs.php.net/bug.php?id=54097 & http://php.net/manual/en/function.rename.php#113943 + $this->mirror($origin, $target, null, array('override' => $overwrite, 'delete' => $overwrite)); + $this->remove($origin); + + return; + } throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target); } } diff --git a/src/Symfony/Component/Filesystem/Tests/LockHandlerTest.php b/src/Symfony/Component/Filesystem/Tests/LockHandlerTest.php index 0791cebc694b8..9ed871ea5a2a3 100644 --- a/src/Symfony/Component/Filesystem/Tests/LockHandlerTest.php +++ b/src/Symfony/Component/Filesystem/Tests/LockHandlerTest.php @@ -49,7 +49,7 @@ public function testErrorHandlingInLockIfLockPathBecomesUnwritable() $this->markTestSkipped('This test cannot run on Windows.'); } - $lockPath = sys_get_temp_dir().'/'.uniqid(); + $lockPath = sys_get_temp_dir().'/'.uniqid('', true); $e = null; $wrongMessage = null; 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/ChoiceList/Factory/DefaultChoiceListFactory.php b/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php index 3398c98edd742..8d28376fd1bd2 100644 --- a/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -54,7 +54,7 @@ public function createView(ChoiceListInterface $list, $preferredChoices = null, if (!is_callable($preferredChoices) && !empty($preferredChoices)) { $preferredChoices = function ($choice) use ($preferredChoices) { - return false !== array_search($choice, $preferredChoices, true); + return in_array($choice, $preferredChoices, true); }; } 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/FormBuilderInterface.php b/src/Symfony/Component/Form/FormBuilderInterface.php index bd7ce9b61e518..32582336aba9e 100644 --- a/src/Symfony/Component/Form/FormBuilderInterface.php +++ b/src/Symfony/Component/Form/FormBuilderInterface.php @@ -27,7 +27,7 @@ interface FormBuilderInterface extends \Traversable, \Countable, FormConfigBuild * @param string|null $type * @param array $options * - * @return $this + * @return self */ public function add($child, $type = null, array $options = array()); @@ -58,7 +58,7 @@ public function get($name); * * @param string $name * - * @return $this + * @return self */ public function remove($name); diff --git a/src/Symfony/Component/Form/FormFactory.php b/src/Symfony/Component/Form/FormFactory.php index 169bc3f6b5a32..25c43454e6725 100644 --- a/src/Symfony/Component/Form/FormFactory.php +++ b/src/Symfony/Component/Form/FormFactory.php @@ -124,7 +124,13 @@ public function createBuilderForProperty($class, $property, $data = null, array // user options may override guessed options if ($typeGuess) { - $options = array_merge($typeGuess->getOptions(), $options); + $attrs = array(); + $typeGuessOptions = $typeGuess->getOptions(); + if (isset($typeGuessOptions['attr']) && isset($options['attr'])) { + $attrs = array('attr' => array_merge($typeGuessOptions['attr'], $options['attr'])); + } + + $options = array_merge($typeGuessOptions, $options, $attrs); } return $this->createNamedBuilder($property, $type, $data, $options); diff --git a/src/Symfony/Component/Form/FormRenderer.php b/src/Symfony/Component/Form/FormRenderer.php index 60f4c363d865e..2aa4b917d69d4 100644 --- a/src/Symfony/Component/Form/FormRenderer.php +++ b/src/Symfony/Component/Form/FormRenderer.php @@ -305,6 +305,6 @@ public function searchAndRenderBlock(FormView $view, $blockNameSuffix, array $va */ public function humanize($text) { - return ucfirst(trim(strtolower(preg_replace(array('/([A-Z])/', '/[_\s]+/'), array('_$1', ' '), $text)))); + return ucfirst(strtolower(trim(preg_replace(array('/([A-Z])/', '/[_\s]+/'), array('_$1', ' '), $text)))); } } diff --git a/src/Symfony/Component/Form/FormView.php b/src/Symfony/Component/Form/FormView.php index c1da5f8fc9bb1..8655bedf6e135 100644 --- a/src/Symfony/Component/Form/FormView.php +++ b/src/Symfony/Component/Form/FormView.php @@ -53,6 +53,8 @@ class FormView implements \ArrayAccess, \IteratorAggregate, \Countable */ private $rendered = false; + private $methodRendered = false; + public function __construct(FormView $parent = null) { $this->parent = $parent; @@ -90,6 +92,19 @@ public function setRendered() return $this; } + /** + * @return bool + */ + public function isMethodRendered() + { + return $this->methodRendered; + } + + public function setMethodRendered() + { + $this->methodRendered = true; + } + /** * Returns a child by name (implements \ArrayAccess). * 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 06ae544f86ab8..9b6c57c444ca1 100644 --- a/src/Symfony/Component/Form/Tests/FormFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/FormFactoryTest.php @@ -293,9 +293,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')); @@ -312,19 +312,19 @@ 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('class' => 'foo', 'maxlength' => 10)), + Guess::MEDIUM_CONFIDENCE + ))); $factory = $this->getMockFactory(array('createNamedBuilder')); $factory->expects($this->once()) ->method('createNamedBuilder') - ->with('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array('attr' => array('maxlength' => 11))) + ->with('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array('attr' => array('class' => 'foo', 'maxlength' => 11))) ->will($this->returnValue('builderInstance')); $this->builder = $factory->createBuilderForProperty( @@ -340,17 +340,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 ))); @@ -408,17 +408,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 ))); @@ -441,17 +441,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/IpUtils.php b/src/Symfony/Component/HttpFoundation/IpUtils.php index 28093be43403f..eba603b15df01 100644 --- a/src/Symfony/Component/HttpFoundation/IpUtils.php +++ b/src/Symfony/Component/HttpFoundation/IpUtils.php @@ -18,6 +18,8 @@ */ class IpUtils { + private static $checkedIps = array(); + /** * This class should not be instantiated. */ @@ -61,26 +63,31 @@ public static function checkIp($requestIp, $ips) */ public static function checkIp4($requestIp, $ip) { + $cacheKey = $requestIp.'-'.$ip; + if (isset(self::$checkedIps[$cacheKey])) { + return self::$checkedIps[$cacheKey]; + } + if (!filter_var($requestIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - return false; + return self::$checkedIps[$cacheKey] = false; } if (false !== strpos($ip, '/')) { list($address, $netmask) = explode('/', $ip, 2); if ($netmask === '0') { - return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); + return self::$checkedIps[$cacheKey] = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); } if ($netmask < 0 || $netmask > 32) { - return false; + return self::$checkedIps[$cacheKey] = false; } } else { $address = $ip; $netmask = 32; } - return 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask); + return self::$checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask); } /** @@ -100,6 +107,11 @@ public static function checkIp4($requestIp, $ip) */ public static function checkIp6($requestIp, $ip) { + $cacheKey = $requestIp.'-'.$ip; + if (isset(self::$checkedIps[$cacheKey])) { + return self::$checkedIps[$cacheKey]; + } + if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) { throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".'); } @@ -108,7 +120,7 @@ public static function checkIp6($requestIp, $ip) list($address, $netmask) = explode('/', $ip, 2); if ($netmask < 1 || $netmask > 128) { - return false; + return self::$checkedIps[$cacheKey] = false; } } else { $address = $ip; @@ -119,7 +131,7 @@ public static function checkIp6($requestIp, $ip) $bytesTest = unpack('n*', @inet_pton($requestIp)); if (!$bytesAddr || !$bytesTest) { - return false; + return self::$checkedIps[$cacheKey] = false; } for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) { @@ -127,10 +139,10 @@ public static function checkIp6($requestIp, $ip) $left = ($left <= 16) ? $left : 16; $mask = ~(0xffff >> $left) & 0xffff; if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) { - return false; + return self::$checkedIps[$cacheKey] = false; } } - return true; + return self::$checkedIps[$cacheKey] = true; } } diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index 2768b21a7d05c..4fbad5ee6c801 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -1502,7 +1502,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/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php index fd46b1d145bd7..54195facaec5e 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php @@ -91,6 +91,10 @@ class NativeSessionStorage implements SessionStorageInterface * upload_progress.freq, "1%" * upload_progress.min-freq, "1" * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset=" + * sid_length, "32" + * sid_bits_per_character, "5" + * trans_sid_hosts, $_SERVER['HTTP_HOST'] + * trans_sid_tags, "a=href,area=href,frame=src,form=" * * @param array $options Session configuration options * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler @@ -316,6 +320,7 @@ public function setOptions(array $options) 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled', 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name', 'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags', + 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', )); foreach ($options as $key => $value) { diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php index cbf8a24ce7bdd..48d8d6af59f9f 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php @@ -1060,7 +1060,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.'); } 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/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/HttpCache/ResponseCacheStrategy.php b/src/Symfony/Component/HttpKernel/HttpCache/ResponseCacheStrategy.php index 39a99e6966c22..027b2b1761334 100644 --- a/src/Symfony/Component/HttpKernel/HttpCache/ResponseCacheStrategy.php +++ b/src/Symfony/Component/HttpKernel/HttpCache/ResponseCacheStrategy.php @@ -39,7 +39,7 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface */ public function add(Response $response) { - if ($response->isValidateable()) { + if (!$response->isFresh() || !$response->isCacheable()) { $this->cacheable = false; } else { $maxAge = $response->getMaxAge(); @@ -70,6 +70,9 @@ public function update(Response $response) if ($response->isValidateable()) { $response->setEtag(null); $response->setLastModified(null); + } + + if (!$response->isFresh()) { $this->cacheable = false; } diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index af4fcaa4f30eb..e36c621722565 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -58,11 +58,11 @@ abstract class Kernel implements KernelInterface, TerminableInterface protected $startTime; protected $loadClassCache; - const VERSION = '3.2.9'; - const VERSION_ID = 30209; + const VERSION = '3.2.10'; + const VERSION_ID = 30210; const MAJOR_VERSION = 3; const MINOR_VERSION = 2; - const RELEASE_VERSION = 9; + const RELEASE_VERSION = 10; const EXTRA_VERSION = ''; const END_OF_MAINTENANCE = '07/2017'; @@ -729,7 +729,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(); diff --git a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php index d06679bfe3fe3..78734535e5607 100644 --- a/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.php @@ -33,14 +33,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); @@ -133,13 +133,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/Tests/HttpCache/ResponseCacheStrategyTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/ResponseCacheStrategyTest.php index f30a3b6ad94ab..5e4c322223eb3 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/ResponseCacheStrategyTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/ResponseCacheStrategyTest.php @@ -75,4 +75,148 @@ public function testSharedMaxAgeNotSetIfNotSetInMasterRequest() $this->assertFalse($response->headers->hasCacheControlDirective('s-maxage')); } + + public function testMasterResponseNotCacheableWhenEmbeddedResponseRequiresValidation() + { + $cacheStrategy = new ResponseCacheStrategy(); + + $embeddedResponse = new Response(); + $embeddedResponse->setLastModified(new \DateTime()); + $cacheStrategy->add($embeddedResponse); + + $masterResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); + $cacheStrategy->update($masterResponse); + + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache')); + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate')); + $this->assertFalse($masterResponse->isFresh()); + } + + public function testValidationOnMasterResponseIsNotPossibleWhenItContainsEmbeddedResponses() + { + $cacheStrategy = new ResponseCacheStrategy(); + + // This master response uses the "validation" model + $masterResponse = new Response(); + $masterResponse->setLastModified(new \DateTime()); + $masterResponse->setEtag('foo'); + + // Embedded response uses "expiry" model + $embeddedResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); + $cacheStrategy->add($embeddedResponse); + + $cacheStrategy->update($masterResponse); + + $this->assertFalse($masterResponse->isValidateable()); + $this->assertFalse($masterResponse->headers->has('Last-Modified')); + $this->assertFalse($masterResponse->headers->has('ETag')); + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache')); + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate')); + } + + public function testMasterResponseWithValidationIsUnchangedWhenThereIsNoEmbeddedResponse() + { + $cacheStrategy = new ResponseCacheStrategy(); + + $masterResponse = new Response(); + $masterResponse->setLastModified(new \DateTime()); + $cacheStrategy->update($masterResponse); + + $this->assertTrue($masterResponse->isValidateable()); + } + + public function testMasterResponseWithExpirationIsUnchangedWhenThereIsNoEmbeddedResponse() + { + $cacheStrategy = new ResponseCacheStrategy(); + + $masterResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); + $cacheStrategy->update($masterResponse); + + $this->assertTrue($masterResponse->isFresh()); + } + + public function testMasterResponseIsNotCacheableWhenEmbeddedResponseIsNotCacheable() + { + $cacheStrategy = new ResponseCacheStrategy(); + + $masterResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); // Public, cacheable + + /* This response has no validation or expiration information. + That makes it uncacheable, it is always stale. + (It does *not* make this private, though.) */ + $embeddedResponse = new Response(); + $this->assertFalse($embeddedResponse->isFresh()); // not fresh, as no lifetime is provided + + $cacheStrategy->add($embeddedResponse); + $cacheStrategy->update($masterResponse); + + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache')); + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate')); + $this->assertFalse($masterResponse->isFresh()); + } + + public function testEmbeddingPrivateResponseMakesMainResponsePrivate() + { + $cacheStrategy = new ResponseCacheStrategy(); + + $masterResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); // public, cacheable + + // The embedded response might for example contain per-user data that remains valid for 60 seconds + $embeddedResponse = new Response(); + $embeddedResponse->setPrivate(); + $embeddedResponse->setMaxAge(60); // this would implicitly set "private" as well, but let's be explicit + + $cacheStrategy->add($embeddedResponse); + $cacheStrategy->update($masterResponse); + + $this->assertTrue($masterResponse->headers->hasCacheControlDirective('private')); + // Not sure if we should pass "max-age: 60" in this case, as long as the response is private and + // that's the more conservative of both the master and embedded response...? + } + + public function testResponseIsExiprableWhenEmbeddedResponseCombinesExpiryAndValidation() + { + /* When "expiration wins over validation" (https://symfony.com/doc/current/http_cache/validation.html) + * and both the main and embedded response provide s-maxage, then the more restricting value of both + * should be fine, regardless of whether the embedded response can be validated later on or must be + * completely regenerated. + */ + $cacheStrategy = new ResponseCacheStrategy(); + + $masterResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); + + $embeddedResponse = new Response(); + $embeddedResponse->setSharedMaxAge(60); + $embeddedResponse->setEtag('foo'); + + $cacheStrategy->add($embeddedResponse); + $cacheStrategy->update($masterResponse); + + $this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage')); + } + + public function testResponseIsExpirableButNotValidateableWhenMasterResponseCombinesExpirationAndValidation() + { + $cacheStrategy = new ResponseCacheStrategy(); + + $masterResponse = new Response(); + $masterResponse->setSharedMaxAge(3600); + $masterResponse->setEtag('foo'); + $masterResponse->setLastModified(new \DateTime()); + + $embeddedResponse = new Response(); + $embeddedResponse->setSharedMaxAge(60); + + $cacheStrategy->add($embeddedResponse); + $cacheStrategy->update($masterResponse); + + $this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage')); + $this->assertFalse($masterResponse->isValidateable()); + } } diff --git a/src/Symfony/Component/HttpKernel/composer.json b/src/Symfony/Component/HttpKernel/composer.json index b4e6f23ea9290..92eb4a54848b7 100644 --- a/src/Symfony/Component/HttpKernel/composer.json +++ b/src/Symfony/Component/HttpKernel/composer.json @@ -40,7 +40,8 @@ "symfony/var-dumper": "~3.2" }, "conflict": { - "symfony/config": "<2.8" + "symfony/config": "<2.8", + "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/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index ca5c248dee1cd..2b3f982e23e86 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -435,6 +435,9 @@ public function testExitCodeCommandFailed() $this->assertGreaterThan(0, $process->getExitCode()); } + /** + * @group tty + */ public function testTTYCommand() { if ('\\' === DIRECTORY_SEPARATOR) { @@ -450,6 +453,9 @@ public function testTTYCommand() $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus()); } + /** + * @group tty + */ public function testTTYCommandExitCode() { if ('\\' === DIRECTORY_SEPARATOR) { diff --git a/src/Symfony/Component/PropertyAccess/PropertyAccessor.php b/src/Symfony/Component/PropertyAccess/PropertyAccessor.php index 6019544a19e8c..d0cadcf65722c 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); } @@ -244,8 +244,11 @@ public function setValue(&$objectOrArray, $propertyPath, $value) } } catch (\TypeError $e) { self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0); + + // It wasn't thrown in this class so rethrow it + throw $e; } finally { - if (PHP_VERSION_ID < 70000 && false !== self::$previousErrorHandler) { + if (\PHP_VERSION_ID < 70000 && false !== self::$previousErrorHandler) { restore_error_handler(); self::$previousErrorHandler = false; } @@ -266,7 +269,7 @@ public static function handleError($type, $message, $file, $line, $context) private static function throwInvalidArgumentException($message, $trace, $i) { - if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file']) { + if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && isset($trace[$i]['args'][0])) { $pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface ')); $pos += strlen($delim); $type = $trace[$i]['args'][0]; @@ -523,7 +526,7 @@ private function readProperty($zval, $property) */ private function getReadAccessInfo($class, $property) { - $key = $class.'..'.$property; + $key = (false !== strpos($class, '@') ? rawurlencode($class) : $class).'..'.$property; if (isset($this->readPropertyCache[$key])) { return $this->readPropertyCache[$key]; @@ -702,7 +705,7 @@ private function writeCollection($zval, $property, $collection, $addMethod, $rem */ private function getWriteAccessInfo($class, $property, $value) { - $key = $class.'..'.$property; + $key = (false !== strpos($class, '@') ? rawurlencode($class) : $class).'..'.$property; if (isset($this->writePropertyCache[$key])) { return $this->writePropertyCache[$key]; diff --git a/src/Symfony/Component/PropertyAccess/Tests/Fixtures/ReturnTyped.php b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/ReturnTyped.php new file mode 100644 index 0000000000000..b6a9852715d79 --- /dev/null +++ b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/ReturnTyped.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\PropertyAccess\Tests\Fixtures; + +/** + * @author Kévin Dunglas + */ +class ReturnTyped +{ + public function getFoos(): array + { + return 'It doesn\'t respect the return type on purpose'; + } + + public function addFoo(\DateTime $dateTime) + { + } + + public function removeFoo(\DateTime $dateTime) + { + } +} diff --git a/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TestClassTypeErrorInsideCall.php b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TestClassTypeErrorInsideCall.php new file mode 100644 index 0000000000000..44a93900fae34 --- /dev/null +++ b/src/Symfony/Component/PropertyAccess/Tests/Fixtures/TestClassTypeErrorInsideCall.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\PropertyAccess\Tests\Fixtures; + +class TestClassTypeErrorInsideCall +{ + public function expectsDateTime(\DateTime $date) + { + } + + public function getProperty() + { + } + + public function setProperty($property) + { + $this->expectsDateTime(null); // throws TypeError + } +} diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php index e2ef9296ed50f..b8356500a5881 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php @@ -15,12 +15,14 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; use Symfony\Component\PropertyAccess\PropertyAccessor; +use Symfony\Component\PropertyAccess\Tests\Fixtures\ReturnTyped; use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClass; use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassMagicCall; use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassMagicGet; use Symfony\Component\PropertyAccess\Tests\Fixtures\Ticket5775Object; use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassSetValue; use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassIsWritable; +use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassTypeErrorInsideCall; use Symfony\Component\PropertyAccess\Tests\Fixtures\TypeHinted; class PropertyAccessorTest extends TestCase @@ -578,4 +580,87 @@ public function testThrowTypeErrorWithInterface() $this->propertyAccessor->setValue($object, 'countable', 'This is a string, \Countable expected.'); } + + /** + * @requires PHP 7.0 + */ + public function testAnonymousClassRead() + { + $value = 'bar'; + + $obj = $this->generateAnonymousClass($value); + + $propertyAccessor = new PropertyAccessor(false, false, new ArrayAdapter()); + + $this->assertEquals($value, $propertyAccessor->getValue($obj, 'foo')); + } + + /** + * @requires PHP 7.0 + */ + public function testAnonymousClassWrite() + { + $value = 'bar'; + + $obj = $this->generateAnonymousClass(''); + + $propertyAccessor = new PropertyAccessor(false, false, new ArrayAdapter()); + $propertyAccessor->setValue($obj, 'foo', $value); + + $this->assertEquals($value, $propertyAccessor->getValue($obj, 'foo')); + } + + private function generateAnonymousClass($value) + { + $obj = eval('return new class($value) + { + private $foo; + + public function __construct($foo) + { + $this->foo = $foo; + } + + /** + * @return mixed + */ + public function getFoo() + { + return $this->foo; + } + + /** + * @param mixed $foo + */ + public function setFoo($foo) + { + $this->foo = $foo; + } + };'); + + return $obj; + } + + /** + * @requires PHP 7.0 + * @expectedException \TypeError + */ + public function testThrowTypeErrorInsideSetterCall() + { + $object = new TestClassTypeErrorInsideCall(); + + $this->propertyAccessor->setValue($object, 'property', 'foo'); + } + + /** + * @requires PHP 7 + * + * @expectedException \TypeError + */ + public function testDoNotDiscardReturnTypeError() + { + $object = new ReturnTyped(); + + $this->propertyAccessor->setValue($object, 'foos', array(new \DateTime())); + } } 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/Loader/XmlFileLoader.php b/src/Symfony/Component/Routing/Loader/XmlFileLoader.php index aff0ba27eecf8..8a6e8ce35989f 100644 --- a/src/Symfony/Component/Routing/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/Routing/Loader/XmlFileLoader.php @@ -225,7 +225,7 @@ private function parseConfigs(\DOMElement $node, $path) $condition = trim($n->textContent); break; default: - throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement" or "option".', $n->localName, $path)); + throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path)); } } diff --git a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php index 463bc0d056809..900c59fa37392 100644 --- a/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php +++ b/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php @@ -49,7 +49,7 @@ public function match($pathinfo) protected function handleRouteRequirements($pathinfo, $name, Route $route) { // expression condition - if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request))) { + if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) { return array(self::REQUIREMENT_MISMATCH, null); } diff --git a/src/Symfony/Component/Routing/Matcher/TraceableUrlMatcher.php b/src/Symfony/Component/Routing/Matcher/TraceableUrlMatcher.php index cb1a35f4d3023..9085be0424886 100644 --- a/src/Symfony/Component/Routing/Matcher/TraceableUrlMatcher.php +++ b/src/Symfony/Component/Routing/Matcher/TraceableUrlMatcher.php @@ -105,7 +105,7 @@ protected function matchCollection($pathinfo, RouteCollection $routes) // check condition if ($condition = $route->getCondition()) { - if (!$this->getExpressionLanguage()->evaluate($condition, array('context' => $this->context, 'request' => $this->request))) { + if (!$this->getExpressionLanguage()->evaluate($condition, array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) { $this->addTrace(sprintf('Condition "%s" does not evaluate to "true"', $condition), self::ROUTE_ALMOST_MATCHES, $name, $route); continue; diff --git a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php index 9786a9b42cc60..c646723b3ab08 100644 --- a/src/Symfony/Component/Routing/Matcher/UrlMatcher.php +++ b/src/Symfony/Component/Routing/Matcher/UrlMatcher.php @@ -207,7 +207,7 @@ protected function getAttributes(Route $route, $name, array $attributes) protected function handleRouteRequirements($pathinfo, $name, Route $route) { // expression condition - if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request))) { + if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) { return array(self::REQUIREMENT_MISMATCH, null); } @@ -248,4 +248,19 @@ protected function getExpressionLanguage() return $this->expressionLanguage; } + + /** + * @internal + */ + protected function createRequest($pathinfo) + { + if (!class_exists('Symfony\Component\HttpFoundation\Request')) { + return null; + } + + return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), array(), array(), array( + 'SCRIPT_FILENAME' => $this->context->getBaseUrl(), + 'SCRIPT_NAME' => $this->context->getBaseUrl(), + )); + } } diff --git a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php index 06a7779a02012..1eeb5d4360cde 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php @@ -337,6 +337,16 @@ public function testCondition() $matcher->match('/foo'); } + public function testRequestCondition() + { + $coll = new RouteCollection(); + $route = new Route('/foo/{bar}'); + $route->setCondition('request.getBaseUrl() == "/sub/front.php" and request.getPathInfo() == "/foo/bar"'); + $coll->add('foo', $route); + $matcher = new UrlMatcher($coll, new RequestContext('/sub/front.php')); + $this->assertEquals(array('bar' => 'bar', '_route' => 'foo'), $matcher->match('/foo/bar')); + } + public function testDecodeOnce() { $coll = new RouteCollection(); diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php index 71d19adc14f2b..7bfc556bdbf25 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php @@ -27,7 +27,7 @@ class UsernamePasswordToken extends AbstractToken * Constructor. * * @param string|object $user The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method - * @param string $credentials This usually is the password of the user + * @param mixed $credentials This usually is the password of the user * @param string $providerKey The provider key * @param (RoleInterface|string)[] $roles An array of roles * diff --git a/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php b/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php index 2dc7fee49992e..5f4c146cab469 100644 --- a/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php +++ b/src/Symfony/Component/Security/Core/Validator/Constraints/UserPasswordValidator.php @@ -39,6 +39,10 @@ public function validate($password, Constraint $constraint) throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\UserPassword'); } + if (null === $password || '' === $password) { + return; + } + $user = $this->tokenStorage->getToken()->getUser(); if (!$user instanceof UserInterface) { diff --git a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php index e9c3e4068d530..821bfae499378 100644 --- a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php @@ -161,7 +161,7 @@ private function attemptSwitchUser(Request $request) */ private function attemptExitUser(Request $request) { - if (false === $original = $this->getOriginalToken($this->tokenStorage->getToken())) { + if (null === ($currentToken = $this->tokenStorage->getToken()) || false === $original = $this->getOriginalToken($currentToken)) { throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.'); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php index 43013520c36ba..6b6cb246c985f 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php @@ -65,6 +65,17 @@ public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest() $this->assertNull($this->tokenStorage->getToken()); } + /** + * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException + */ + public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken() + { + $this->tokenStorage->setToken(null); + $this->request->query->set('_switch_user', '_exit'); + $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); + $listener->handle($this->event); + } + /** * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException */ diff --git a/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php index 8f5d2099291bc..d624b8f455c61 100644 --- a/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php @@ -191,7 +191,7 @@ protected function handleCircularReference($object) return call_user_func($this->circularReferenceHandler, $object); } - throw new CircularReferenceException(sprintf('A circular reference has been detected (configured limit: %d).', $this->circularReferenceLimit)); + throw new CircularReferenceException(sprintf('A circular reference has been detected when serializing the object of class "%s" (configured limit: %d)', get_class($object), $this->circularReferenceLimit)); } /** diff --git a/src/Symfony/Component/Translation/DataCollectorTranslator.php b/src/Symfony/Component/Translation/DataCollectorTranslator.php index cdfde100b8f9d..48b3c473c5670 100644 --- a/src/Symfony/Component/Translation/DataCollectorTranslator.php +++ b/src/Symfony/Component/Translation/DataCollectorTranslator.php @@ -97,7 +97,7 @@ public function getCatalogue($locale = null) */ public function getFallbackLocales() { - if ($this->translator instanceof Translator) { + if ($this->translator instanceof Translator || method_exists($this->translator, 'getFallbackLocales')) { return $this->translator->getFallbackLocales(); } diff --git a/src/Symfony/Component/Translation/Dumper/IcuResFileDumper.php b/src/Symfony/Component/Translation/Dumper/IcuResFileDumper.php index 77ce27b2aa4ca..42f159501a859 100644 --- a/src/Symfony/Component/Translation/Dumper/IcuResFileDumper.php +++ b/src/Symfony/Component/Translation/Dumper/IcuResFileDumper.php @@ -52,7 +52,7 @@ public function formatCatalogue(MessageCatalogue $messages, $domain, array $opti $resOffset = $this->getPosition($data); - $data .= pack('v', count($messages)) + $data .= pack('v', count($messages->all($domain))) .$indexes .$this->writePadding($data) .$resources @@ -63,11 +63,11 @@ public function formatCatalogue(MessageCatalogue $messages, $domain, array $opti $root = pack('V7', $resOffset + (2 << 28), // Resource Offset + Resource Type 6, // Index length - $keyTop, // Index keys top - $bundleTop, // Index resources top - $bundleTop, // Index bundle top - count($messages), // Index max table length - 0 // Index attributes + $keyTop, // Index keys top + $bundleTop, // Index resources top + $bundleTop, // Index bundle top + count($messages->all($domain)), // Index max table length + 0 // Index attributes ); $header = pack('vC2v4C12@32', diff --git a/src/Symfony/Component/Translation/Loader/FileLoader.php b/src/Symfony/Component/Translation/Loader/FileLoader.php index a7f24f41a6535..1885963a99550 100644 --- a/src/Symfony/Component/Translation/Loader/FileLoader.php +++ b/src/Symfony/Component/Translation/Loader/FileLoader.php @@ -54,7 +54,7 @@ public function load($resource, $locale, $domain = 'messages') return $catalogue; } - /* + /** * @param string $resource * * @return array diff --git a/src/Symfony/Component/Translation/LoggingTranslator.php b/src/Symfony/Component/Translation/LoggingTranslator.php index 469b3d133b9f7..194e554ad9106 100644 --- a/src/Symfony/Component/Translation/LoggingTranslator.php +++ b/src/Symfony/Component/Translation/LoggingTranslator.php @@ -96,7 +96,7 @@ public function getCatalogue($locale = null) */ public function getFallbackLocales() { - if ($this->translator instanceof Translator) { + if ($this->translator instanceof Translator || method_exists($this->translator, 'getFallbackLocales')) { return $this->translator->getFallbackLocales(); } diff --git a/src/Symfony/Component/Validator/Constraints/AbstractComparison.php b/src/Symfony/Component/Validator/Constraints/AbstractComparison.php index 78db943f74f14..e20a8f3fb7b05 100644 --- a/src/Symfony/Component/Validator/Constraints/AbstractComparison.php +++ b/src/Symfony/Component/Validator/Constraints/AbstractComparison.php @@ -30,6 +30,10 @@ abstract class AbstractComparison extends Constraint */ public function __construct($options = null) { + if (null === $options) { + $options = array(); + } + if (is_array($options) && !isset($options['value'])) { throw new ConstraintDefinitionException(sprintf( 'The %s constraint requires the "value" option to be set.', diff --git a/src/Symfony/Component/Validator/Constraints/UrlValidator.php b/src/Symfony/Component/Validator/Constraints/UrlValidator.php index 118a8defc1468..5d6780e4122e3 100644 --- a/src/Symfony/Component/Validator/Constraints/UrlValidator.php +++ b/src/Symfony/Component/Validator/Constraints/UrlValidator.php @@ -47,7 +47,7 @@ public function validate($value, Constraint $constraint) throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Url'); } - if (null === $value) { + if (null === $value || '' === $value) { return; } diff --git a/src/Symfony/Component/Validator/Resources/translations/validators.fr.xlf b/src/Symfony/Component/Validator/Resources/translations/validators.fr.xlf index 72d4d92973fdc..30a883bbf239d 100644 --- a/src/Symfony/Component/Validator/Resources/translations/validators.fr.xlf +++ b/src/Symfony/Component/Validator/Resources/translations/validators.fr.xlf @@ -76,7 +76,7 @@ This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less. - Cette chaine est trop longue. Elle doit avoir au maximum {{ limit }} caractère.|Cette chaine est trop longue. Elle doit avoir au maximum {{ limit }} caractères. + Cette chaîne est trop longue. Elle doit avoir au maximum {{ limit }} caractère.|Cette chaîne est trop longue. Elle doit avoir au maximum {{ limit }} caractères. This value should be {{ limit }} or more. @@ -84,7 +84,7 @@ This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more. - Cette chaine est trop courte. Elle doit avoir au minimum {{ limit }} caractère.|Cette chaine est trop courte. Elle doit avoir au minimum {{ limit }} caractères. + Cette chaîne est trop courte. Elle doit avoir au minimum {{ limit }} caractère.|Cette chaîne est trop courte. Elle doit avoir au minimum {{ limit }} caractères. This value should not be blank. @@ -180,7 +180,7 @@ This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters. - Cette chaine doit avoir exactement {{ limit }} caractère.|Cette chaine doit avoir exactement {{ limit }} caractères. + Cette chaîne doit avoir exactement {{ limit }} caractère.|Cette chaîne doit avoir exactement {{ limit }} caractères. The file was only partially uploaded. diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php index 437c7453cfe83..a613d18ead3fb 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php @@ -65,14 +65,21 @@ protected static function addPhp5Dot5Comparisons(array $comparisons) return $result; } + public function provideInvalidConstraintOptions() + { + return array( + array(null), + array(array()), + ); + } + /** + * @dataProvider provideInvalidConstraintOptions * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ - public function testThrowsConstraintExceptionIfNoValueOrProperty() + public function testThrowsConstraintExceptionIfNoValueOrProperty($options) { - $comparison = $this->createConstraint(array()); - - $this->validator->validate('some value', $comparison); + $this->createConstraint($options); } /** @@ -163,11 +170,11 @@ public function provideAllInvalidComparisons() abstract public function provideInvalidComparisons(); /** - * @param array $options Options for the constraint + * @param array|null $options Options for the constraint * * @return Constraint */ - abstract protected function createConstraint(array $options); + abstract protected function createConstraint(array $options = null); /** * @return string|null diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php index ad3f0d7737f30..5e079ce525058 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new EqualToValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new EqualTo($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorTest.php index 0fe3001d5ed09..f13cbd9d396ac 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new GreaterThanOrEqualValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new GreaterThanOrEqual($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php index 6742fcb9b9ec8..4347473fe006e 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new GreaterThanValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new GreaterThan($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php index 0a23db7e046dc..100600d04bb3b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new IdenticalToValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new IdenticalTo($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php index 3d0cc902c8219..bbd0604f84e1c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new LessThanOrEqualValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new LessThanOrEqual($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php index 807c43adaf46b..d5a5c7378d8da 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new LessThanValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new LessThan($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php index ed3568b8f50db..fb9aa9f6e8b86 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new NotEqualToValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new NotEqualTo($options); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php index d9a3d16f8bfe7..7938b0a7e3899 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php @@ -24,7 +24,7 @@ protected function createValidator() return new NotIdenticalToValidator(); } - protected function createConstraint(array $options) + protected function createConstraint(array $options = null) { return new NotIdenticalTo($options); } 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/Validator/composer.json b/src/Symfony/Component/Validator/composer.json index f17085aa98c45..36e404ffe92e7 100644 --- a/src/Symfony/Component/Validator/composer.json +++ b/src/Symfony/Component/Validator/composer.json @@ -43,7 +43,6 @@ "symfony/yaml": "", "symfony/config": "", "egulias/email-validator": "Strict (RFC compliant) email validation", - "symfony/property-access": "For using the Expression validator", "symfony/expression-language": "For using the Expression validator" }, "autoload": { diff --git a/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php b/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php index 6a9fc101c2d28..8c84137e646cc 100644 --- a/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php @@ -163,7 +163,7 @@ public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, $is $ellipsis = 3 < count($ellipsis) ? 2 + strlen(implode(array_slice($ellipsis, -2))) : 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/Caster/ResourceCaster.php b/src/Symfony/Component/VarDumper/Caster/ResourceCaster.php index bc9cb115264fb..3cdb27c30879b 100644 --- a/src/Symfony/Component/VarDumper/Caster/ResourceCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/ResourceCaster.php @@ -50,7 +50,7 @@ public static function castStream($stream, array $a, Stub $stub, $isNested) public static function castStreamContext($stream, array $a, Stub $stub, $isNested) { - return stream_context_get_params($stream); + return @stream_context_get_params($stream) ?: $a; } public static function castGd($gd, array $a, Stub $stub, $isNested) diff --git a/src/Symfony/Component/VarDumper/Caster/SplCaster.php b/src/Symfony/Component/VarDumper/Caster/SplCaster.php index 2c676957584d6..4f23efa52d28d 100644 --- a/src/Symfony/Component/VarDumper/Caster/SplCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/SplCaster.php @@ -184,7 +184,7 @@ public static function castObjectStorage(\SplObjectStorage $c, array $a, Stub $s $storage = array(); unset($a[Caster::PREFIX_DYNAMIC."\0gcdata"]); // Don't hit https://bugs.php.net/65967 - foreach ($c as $obj) { + foreach (clone $c as $obj) { $storage[spl_object_hash($obj)] = array( 'object' => $obj, 'info' => $c->getInfo(), diff --git a/src/Symfony/Component/VarDumper/Tests/Caster/ExceptionCasterTest.php b/src/Symfony/Component/VarDumper/Tests/Caster/ExceptionCasterTest.php index e4a72ed7cf271..e0fb177b4bbea 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/CliDumperTest.php b/src/Symfony/Component/VarDumper/Tests/CliDumperTest.php index 5251f418925d7..feaf85da24fd2 100644 --- a/src/Symfony/Component/VarDumper/Tests/CliDumperTest.php +++ b/src/Symfony/Component/VarDumper/Tests/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 @@ -230,14 +232,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); @@ -253,7 +255,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(); } };'), @@ -279,7 +281,7 @@ public function testThrowingCaster() %sTemplate.php:%d: { : try { : \$this->doDisplay(\$context, \$blocks); - : } catch (Twig_Error \$e) { + : } catch (Twig%sError \$e) { } %sTemplate.php:%d: { : { @@ -415,7 +417,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 a4265b5ecb746..44dbdebcce2ed 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/Workflow/Tests/WorkflowTest.php b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php index c1efb0182765a..bbc9323c154c4 100644 --- a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php +++ b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php @@ -259,6 +259,8 @@ public function testApplyWithEventDispatcher() 'workflow.workflow_name.enter.b', 'workflow.workflow_name.enter.c', // Following events are fired because of announce() method + 'workflow.announce', + 'workflow.workflow_name.announce', 'workflow.guard', 'workflow.workflow_name.guard', 'workflow.workflow_name.guard.t2', diff --git a/src/Symfony/Component/Workflow/Workflow.php b/src/Symfony/Component/Workflow/Workflow.php index ec49895a3c604..3c0b07be3fbaf 100644 --- a/src/Symfony/Component/Workflow/Workflow.php +++ b/src/Symfony/Component/Workflow/Workflow.php @@ -282,6 +282,9 @@ private function announce($subject, Transition $initialTransition, Marking $mark $event = new Event($subject, $marking, $initialTransition); + $this->dispatcher->dispatch('workflow.announce', $event); + $this->dispatcher->dispatch(sprintf('workflow.%s.announce', $this->name), $event); + foreach ($this->getEnabledTransitions($subject) as $transition) { $this->dispatcher->dispatch(sprintf('workflow.%s.announce.%s', $this->name, $transition->getName()), $event); } diff --git a/src/Symfony/Component/Workflow/composer.json b/src/Symfony/Component/Workflow/composer.json index b30d50091e1d6..f64d3cf8a4cd7 100644 --- a/src/Symfony/Component/Workflow/composer.json +++ b/src/Symfony/Component/Workflow/composer.json @@ -2,7 +2,7 @@ "name": "symfony/workflow", "type": "library", "description": "Symfony Workflow Component", - "keywords": ["workflow", "petrinet", "place", "transition"], + "keywords": ["workflow", "petrinet", "place", "transition", "statemachine", "state"], "homepage": "http://symfony.com", "license": "MIT", "authors": [ diff --git a/src/Symfony/Component/Yaml/Tests/InlineTest.php b/src/Symfony/Component/Yaml/Tests/InlineTest.php index 09175a6881d46..8074123e6df75 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);